experimental-ash 0.60.0 → 0.61.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/docs/public/advanced/auth-and-route-protection.mdx +8 -6
- package/dist/docs/public/agent-ts.md +17 -47
- package/dist/docs/public/channels/README.md +60 -0
- package/dist/docs/public/channels/ash.mdx +103 -0
- package/dist/docs/public/channels/custom.mdx +288 -0
- package/dist/docs/public/channels/discord.mdx +1 -3
- package/dist/docs/public/channels/github.md +1 -1
- package/dist/docs/public/channels/meta.json +3 -0
- package/dist/docs/public/channels/slack.mdx +29 -1
- package/dist/docs/public/channels/teams.mdx +1 -3
- package/dist/docs/public/channels/telegram.mdx +1 -3
- package/dist/docs/public/channels/twilio.mdx +1 -3
- package/dist/docs/public/frontend/nextjs.md +24 -8
- package/dist/docs/public/onboarding.md +4 -3
- package/dist/docs/public/schedules.mdx +4 -4
- package/dist/docs/public/tools.mdx +1 -1
- package/dist/src/channel/compiled-channel.d.ts +2 -6
- package/dist/src/channel/routes.d.ts +75 -7
- package/dist/src/channel/routes.js +1 -1
- package/dist/src/compiler/manifest.d.ts +4 -4
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/host/channel-routes.d.ts +2 -2
- package/dist/src/internal/nitro/host/channel-routes.js +2 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.d.ts +2 -0
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +2 -2
- package/dist/src/internal/vercel-agent-summary.js +1 -1
- package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/channels/index.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +7 -0
- package/dist/src/public/definitions/defineChannel.d.ts +3 -6
- package/dist/src/public/definitions/defineChannel.js +1 -1
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/resolve-channel.js +1 -1
- package/dist/src/runtime/types.d.ts +8 -3
- package/package.json +1 -1
- package/dist/docs/public/channels/attachments.md +0 -71
- package/dist/docs/public/channels/index.md +0 -661
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
---
|
|
2
|
-
title: "Twilio
|
|
2
|
+
title: "Twilio"
|
|
3
3
|
description: "Create a Twilio-backed Ash channel for SMS and speech-transcribed phone calls."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
|
-
# Twilio Channel Setup
|
|
7
|
-
|
|
8
6
|
The Twilio channel accepts inbound SMS webhooks and inbound voice calls. Voice calls are answered
|
|
9
7
|
with TwiML `<Gather input="speech">`; the Twilio speech transcript is then delivered to the same
|
|
10
8
|
Ash session model as SMS. The raw continuation token is the caller/sender phone number plus the
|
|
@@ -36,24 +36,40 @@ export default withAsh(nextConfig, {
|
|
|
36
36
|
|
|
37
37
|
## Add The Ash Channel
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
`withAsh()` exposes the default Ash HTTP routes for the browser. Before deploying
|
|
40
|
+
a user-facing app, add `agent/channels/ash.ts` so production requests use your
|
|
41
|
+
app's auth policy.
|
|
41
42
|
|
|
42
|
-
|
|
43
|
-
|
|
43
|
+
Start with the development and infrastructure helpers, then replace the
|
|
44
|
+
production branch with your real app auth:
|
|
44
45
|
|
|
45
46
|
```ts
|
|
46
47
|
// agent/channels/ash.ts
|
|
47
48
|
import { ashChannel } from "experimental-ash/channels/ash";
|
|
48
|
-
import {
|
|
49
|
+
import { localDev, vercelOidc, type AuthFn } from "experimental-ash/channels/auth";
|
|
50
|
+
|
|
51
|
+
const productionAuth: AuthFn = async (request) => {
|
|
52
|
+
// Read your app session from cookies, headers, or your auth provider.
|
|
53
|
+
const user = await authenticate(request);
|
|
54
|
+
if (!user) return null;
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
attributes: {},
|
|
58
|
+
principalType: "user",
|
|
59
|
+
principalId: user.id,
|
|
60
|
+
authenticator: "app",
|
|
61
|
+
issuer: "my-nextjs-app",
|
|
62
|
+
};
|
|
63
|
+
};
|
|
49
64
|
|
|
50
65
|
export default ashChannel({
|
|
51
|
-
auth:
|
|
66
|
+
auth: [localDev(), vercelOidc(), productionAuth],
|
|
52
67
|
});
|
|
53
68
|
```
|
|
54
69
|
|
|
55
|
-
|
|
56
|
-
|
|
70
|
+
See [Ash Channel](/docs/channels/ash) for the routes this file controls, and
|
|
71
|
+
[Auth And Route Protection](/docs/auth-and-route-protection) for auth helpers
|
|
72
|
+
and production examples.
|
|
57
73
|
|
|
58
74
|
## Use The React Hook
|
|
59
75
|
|
|
@@ -31,12 +31,13 @@ Collect these up front. A capable agent should use a structured question UI (suc
|
|
|
31
31
|
- Skip Vercel — pass `--skip-vercel` for web/REPL-only setups that should scaffold without a Vercel project or Vercel Services config; the agent will not reach a model until you add a provider. Slack still requires a Vercel project.
|
|
32
32
|
5. **Deploy** — whether to deploy to Vercel production now. Required for Slack to receive events; pass `--skip-deploy` to skip only the final deployment.
|
|
33
33
|
|
|
34
|
-
## Step 1 — Scaffold
|
|
34
|
+
## Step 1 — Scaffold Headlessly
|
|
35
35
|
|
|
36
|
-
Run the create CLI
|
|
36
|
+
Run the create CLI with `--headless`. It scaffolds the project, provisions the model provider, and emits a structured JSON event stream. If the user chose Slack, do **not** pass `slack` here; add it in [Step 2](#step-2--add-slack-interactively).
|
|
37
37
|
|
|
38
38
|
```bash
|
|
39
39
|
npx create-experimental-ash-agent@latest <name> \
|
|
40
|
+
--headless \
|
|
40
41
|
--model <model> \
|
|
41
42
|
--channels web \
|
|
42
43
|
[--team <slug>] \
|
|
@@ -65,7 +66,7 @@ The CLI advances as far as it can without human input. When it reaches a login o
|
|
|
65
66
|
|
|
66
67
|
When you see `action-required`: present `command` to the user to run themselves, wait for them to confirm, then **re-run the exact same create command**. Repeat until the stream emits `{ "type": "done" }`.
|
|
67
68
|
|
|
68
|
-
> If the installed CLI does not support `--
|
|
69
|
+
> If the installed CLI does not support `--headless` / `--json` (an older version), fall back to the interactive wizard `pnpm create experimental-ash-agent` and walk the user through the same decisions above.
|
|
69
70
|
|
|
70
71
|
## Step 2 — Add Slack interactively
|
|
71
72
|
|
|
@@ -51,14 +51,14 @@ export default defineSchedule({
|
|
|
51
51
|
|
|
52
52
|
`ScheduleHandlerArgs`:
|
|
53
53
|
|
|
54
|
-
- `receive(channel, { message, target, auth })` — same contract as a route handler's [`args.receive`](
|
|
54
|
+
- `receive(channel, { message, target, auth })` — same contract as a route handler's [`args.receive`](/docs/channels/custom#cross-channel-hand-off). Hands the work off to a channel's authored `receive` hook.
|
|
55
55
|
- `waitUntil(promise)` — extends the cron task's lifetime past handler return so in-flight work settles before the Nitro task completes.
|
|
56
56
|
- `appAuth` — pre-built APP auth context (`{ authenticator: "app", principalId: "ash:app", principalType: "runtime" }`). Pass to `receive(..., { auth: appAuth })` for schedules that run on behalf of the agent itself.
|
|
57
57
|
|
|
58
58
|
#### Slack thread anchoring
|
|
59
59
|
|
|
60
60
|
A schedule that hands off to Slack does not need a pre-existing thread. The channel
|
|
61
|
-
[auto-anchors](
|
|
61
|
+
[auto-anchors](/docs/channels/slack#thread-anchoring) on the first agent post:
|
|
62
62
|
that message becomes the thread root, the channel calls
|
|
63
63
|
`ctx.session.setContinuationToken(...)` with the channel-local anchor token, and the
|
|
64
64
|
runtime re-keys the parked session under the namespaced Slack token. The rest of the
|
|
@@ -196,10 +196,10 @@ Use a schedule when the agent should initiate work on its own cadence:
|
|
|
196
196
|
- heartbeat checks
|
|
197
197
|
- automated reports
|
|
198
198
|
|
|
199
|
-
If the workflow starts from an inbound user message, use a [channel](
|
|
199
|
+
If the workflow starts from an inbound user message, use a [channel](/docs/channels) instead.
|
|
200
200
|
|
|
201
201
|
## What to read next
|
|
202
202
|
|
|
203
|
-
- [Channels](
|
|
203
|
+
- [Channels](/docs/channels)
|
|
204
204
|
- [Runs and streaming](./runs-and-streaming.md)
|
|
205
205
|
- [Session context](./session-context.md)
|
|
@@ -520,7 +520,7 @@ export default defineDynamic({
|
|
|
520
520
|
});
|
|
521
521
|
```
|
|
522
522
|
|
|
523
|
-
The metadata is available in subagents too — the framework forwards the parent's channel metadata projection so the same tool file works in both the root agent and its subagents. See [Channel Metadata](/channels#channel-metadata) for the full pattern including execution order.
|
|
523
|
+
The metadata is available in subagents too — the framework forwards the parent's channel metadata projection so the same tool file works in both the root agent and its subagents. See [Channel Metadata](/docs/channels/custom#channel-metadata) for the full pattern including execution order.
|
|
524
524
|
|
|
525
525
|
### Events
|
|
526
526
|
|
|
@@ -1,15 +1,11 @@
|
|
|
1
1
|
import type { ChannelAdapter } from "#channel/adapter.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { RouteDefinition, SendFn } from "#channel/routes.js";
|
|
3
3
|
import type { Session } from "#channel/session.js";
|
|
4
4
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
5
5
|
export declare const CHANNEL_SENTINEL: "ash:channel";
|
|
6
6
|
export interface CompiledChannel<TState = undefined, TReceiveTarget = Record<string, unknown>, TMetadata extends Record<string, unknown> = Record<string, unknown>> {
|
|
7
7
|
readonly __kind: typeof CHANNEL_SENTINEL;
|
|
8
|
-
readonly routes: readonly
|
|
9
|
-
method: string;
|
|
10
|
-
path: string;
|
|
11
|
-
handler: RouteHandler<TState>;
|
|
12
|
-
}[];
|
|
8
|
+
readonly routes: readonly RouteDefinition<TState>[];
|
|
13
9
|
readonly adapter: ChannelAdapter<any>;
|
|
14
10
|
readonly __metadata?: TMetadata;
|
|
15
11
|
readonly receive?: (input: {
|
|
@@ -5,6 +5,8 @@ import type { InputResponse } from "#runtime/input/types.js";
|
|
|
5
5
|
import type { Session } from "#channel/session.js";
|
|
6
6
|
import type { RunMode } from "#shared/run-mode.js";
|
|
7
7
|
import type { JsonObject } from "#shared/json.js";
|
|
8
|
+
import type { ChannelMethod } from "#public/definitions/channel.js";
|
|
9
|
+
type WebSocketHeaders = Headers | readonly (readonly [string, string])[] | Record<string, string>;
|
|
8
10
|
export interface RouteHandlerArgs<TState = undefined> {
|
|
9
11
|
send: SendFn<TState>;
|
|
10
12
|
getSession: GetSessionFn;
|
|
@@ -57,14 +59,80 @@ export type SendOptions<TState = undefined> = [TState] extends [undefined] ? Bas
|
|
|
57
59
|
};
|
|
58
60
|
export type GetSessionFn = (sessionId: string) => Session;
|
|
59
61
|
export type RouteHandler<TState = undefined> = (req: Request, args: RouteHandlerArgs<TState>) => Promise<Response>;
|
|
60
|
-
export interface
|
|
61
|
-
readonly
|
|
62
|
+
export interface WebSocketPeer {
|
|
63
|
+
readonly id: string;
|
|
64
|
+
readonly context: Record<string, unknown>;
|
|
65
|
+
readonly namespace: string;
|
|
66
|
+
readonly request: Request;
|
|
67
|
+
readonly remoteAddress?: string;
|
|
68
|
+
readonly topics: Set<string>;
|
|
69
|
+
close(code?: number, reason?: string): void;
|
|
70
|
+
publish(topic: string, data: unknown, options?: {
|
|
71
|
+
compress?: boolean;
|
|
72
|
+
}): void;
|
|
73
|
+
send(data: unknown, options?: {
|
|
74
|
+
compress?: boolean;
|
|
75
|
+
}): number | void | undefined;
|
|
76
|
+
subscribe(topic: string): void;
|
|
77
|
+
terminate(): void;
|
|
78
|
+
unsubscribe(topic: string): void;
|
|
79
|
+
}
|
|
80
|
+
export interface WebSocketMessage {
|
|
81
|
+
readonly data: unknown;
|
|
82
|
+
readonly id: string;
|
|
83
|
+
readonly rawData: unknown;
|
|
84
|
+
arrayBuffer(): ArrayBuffer | SharedArrayBuffer;
|
|
85
|
+
blob(): Blob;
|
|
86
|
+
json<T = unknown>(): T;
|
|
87
|
+
text(): string;
|
|
88
|
+
uint8Array(): Uint8Array;
|
|
89
|
+
}
|
|
90
|
+
export interface WebSocketUpgradeRequest extends Request {
|
|
91
|
+
readonly context?: Record<string, unknown>;
|
|
92
|
+
}
|
|
93
|
+
export type WebSocketUpgradeResult = {
|
|
94
|
+
readonly context?: Record<string, unknown>;
|
|
95
|
+
readonly handled?: boolean;
|
|
96
|
+
readonly headers?: WebSocketHeaders;
|
|
97
|
+
readonly namespace?: string;
|
|
98
|
+
} | Response | void;
|
|
99
|
+
export interface WebSocketRouteHooks {
|
|
100
|
+
close?(peer: WebSocketPeer, details: {
|
|
101
|
+
code?: number;
|
|
102
|
+
reason?: string;
|
|
103
|
+
}): void | Promise<void>;
|
|
104
|
+
error?(peer: WebSocketPeer, error: Error): void | Promise<void>;
|
|
105
|
+
message?(peer: WebSocketPeer, message: WebSocketMessage): void | Promise<void>;
|
|
106
|
+
open?(peer: WebSocketPeer): void | Promise<void>;
|
|
107
|
+
upgrade?(request: WebSocketUpgradeRequest): Promise<WebSocketUpgradeResult> | WebSocketUpgradeResult;
|
|
108
|
+
}
|
|
109
|
+
export type WebSocketRouteHandler<TState = undefined> = (req: Request, args: RouteHandlerArgs<TState>) => Promise<WebSocketRouteHooks> | WebSocketRouteHooks;
|
|
110
|
+
export interface HttpRouteDefinition<TState = undefined> {
|
|
111
|
+
readonly transport?: "http";
|
|
112
|
+
readonly method: ChannelMethod;
|
|
62
113
|
readonly path: string;
|
|
63
114
|
readonly handler: RouteHandler<TState>;
|
|
64
115
|
}
|
|
65
|
-
export
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
116
|
+
export interface WebSocketRouteDefinition<TState = undefined> {
|
|
117
|
+
readonly transport: "websocket";
|
|
118
|
+
readonly method: "WEBSOCKET";
|
|
119
|
+
readonly path: string;
|
|
120
|
+
readonly handler: WebSocketRouteHandler<TState>;
|
|
121
|
+
}
|
|
122
|
+
export type RouteDefinition<TState = undefined> = HttpRouteDefinition<TState> | WebSocketRouteDefinition<TState>;
|
|
123
|
+
export declare function GET<TState = undefined>(path: string, handler: RouteHandler<TState>): HttpRouteDefinition<TState>;
|
|
124
|
+
export declare function POST<TState = undefined>(path: string, handler: RouteHandler<TState>): HttpRouteDefinition<TState>;
|
|
125
|
+
export declare function PUT<TState = undefined>(path: string, handler: RouteHandler<TState>): HttpRouteDefinition<TState>;
|
|
126
|
+
export declare function PATCH<TState = undefined>(path: string, handler: RouteHandler<TState>): HttpRouteDefinition<TState>;
|
|
127
|
+
export declare function DELETE<TState = undefined>(path: string, handler: RouteHandler<TState>): HttpRouteDefinition<TState>;
|
|
128
|
+
/**
|
|
129
|
+
* Declares a WebSocket channel route.
|
|
130
|
+
*
|
|
131
|
+
* The handler runs once per upgrade request and returns lifecycle hooks for
|
|
132
|
+
* that connection. The hooks are Ash-owned structural types so channel authors
|
|
133
|
+
* can use CrossWS-compatible helpers without Ash exposing CrossWS directly.
|
|
134
|
+
*/
|
|
135
|
+
export declare function WS<TState = undefined>(path: string, handler: WebSocketRouteHandler<TState>): WebSocketRouteDefinition<TState>;
|
|
136
|
+
export declare function isHttpRouteDefinition<TState>(route: RouteDefinition<TState>): route is HttpRouteDefinition<TState>;
|
|
137
|
+
export declare function isWebSocketRouteDefinition<TState>(route: RouteDefinition<TState>): route is WebSocketRouteDefinition<TState>;
|
|
70
138
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function GET(e,t){return{method:`GET`,path:e,handler:t}}function POST(e,t){return{method:`POST`,path:e,handler:t}}function PUT(e,t){return{method:`PUT`,path:e,handler:t}}function PATCH(e,t){return{method:`PATCH`,path:e,handler:t}}function DELETE(e,t){return{method:`DELETE`,path:e,handler:t}}export{DELETE,GET,PATCH,POST,PUT};
|
|
1
|
+
function GET(e,t){return{transport:`http`,method:`GET`,path:e,handler:t}}function POST(e,t){return{transport:`http`,method:`POST`,path:e,handler:t}}function PUT(e,t){return{transport:`http`,method:`PUT`,path:e,handler:t}}function PATCH(e,t){return{transport:`http`,method:`PATCH`,path:e,handler:t}}function DELETE(e,t){return{transport:`http`,method:`DELETE`,path:e,handler:t}}function WS(e,t){return{transport:`websocket`,method:`WEBSOCKET`,path:e,handler:t}}function isHttpRouteDefinition(e){return e.transport!==`websocket`}function isWebSocketRouteDefinition(e){return e.transport===`websocket`}export{DELETE,GET,PATCH,POST,PUT,WS,isHttpRouteDefinition,isWebSocketRouteDefinition};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from "#compiled/zod/index.js";
|
|
2
2
|
import { type DiscoverDiagnosticsSummary } from "#discover/diagnostics.js";
|
|
3
3
|
import { type CompiledRemoteAgentNode } from "#compiler/remote-agent-node.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type { ChannelRouteMethod } from "#public/definitions/channel.js";
|
|
5
5
|
import type { Node } from "#shared/node.js";
|
|
6
6
|
import type { MarkdownSourceRef, ModuleSourceRef, SkillPackageSourceRef } from "#shared/source-ref.js";
|
|
7
7
|
import type { NamedSkillDefinition } from "#shared/skill-definition.js";
|
|
@@ -18,7 +18,7 @@ export declare const ROOT_COMPILED_AGENT_NODE_ID = "__root__";
|
|
|
18
18
|
/**
|
|
19
19
|
* Current compiled manifest schema version.
|
|
20
20
|
*/
|
|
21
|
-
export declare const COMPILED_AGENT_MANIFEST_VERSION =
|
|
21
|
+
export declare const COMPILED_AGENT_MANIFEST_VERSION = 28;
|
|
22
22
|
/**
|
|
23
23
|
* Compiled channel entry preserved in the compiled manifest.
|
|
24
24
|
*/
|
|
@@ -30,7 +30,7 @@ export interface CompiledChannelDefinition {
|
|
|
30
30
|
readonly kind: "channel";
|
|
31
31
|
readonly name: string;
|
|
32
32
|
readonly logicalPath: string;
|
|
33
|
-
readonly method:
|
|
33
|
+
readonly method: ChannelRouteMethod;
|
|
34
34
|
readonly urlPath: string;
|
|
35
35
|
readonly sourceId: string;
|
|
36
36
|
readonly sourceKind: "module";
|
|
@@ -414,7 +414,7 @@ export declare const compiledAgentManifestSchema: z.ZodObject<{
|
|
|
414
414
|
sourceId: z.ZodString;
|
|
415
415
|
sourceKind: z.ZodLiteral<"module">;
|
|
416
416
|
}, z.core.$strict>>;
|
|
417
|
-
version: z.ZodLiteral<
|
|
417
|
+
version: z.ZodLiteral<28>;
|
|
418
418
|
workspaceResourceRoot: z.ZodObject<{
|
|
419
419
|
contentHash: z.ZodOptional<z.ZodString>;
|
|
420
420
|
logicalPath: z.ZodString;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=27,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({codeMode:z.boolean().optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(27),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{codeMode:e.config.experimental.codeMode},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:27}}function cloneCompiledRuntimeModelReference(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{discoverDiagnosticsSummarySchema}from"#discover/diagnostics.js";import{compiledRemoteAgentNodeSchema}from"#compiler/remote-agent-node.js";import{jsonObjectSchema}from"#shared/json-schemas.js";const COMPILED_AGENT_MANIFEST_KIND=`ash-agent-compiled-manifest`,ROOT_COMPILED_AGENT_NODE_ID=`__root__`,COMPILED_AGENT_MANIFEST_VERSION=28,moduleSourceRefSchema=z.object({exportName:z.string().optional(),sourceKind:z.literal(`module`),logicalPath:z.string(),sourceId:z.string()}).strict(),channelMethodSchema=z.union([z.literal(`GET`),z.literal(`POST`),z.literal(`PUT`),z.literal(`PATCH`),z.literal(`DELETE`),z.literal(`WEBSOCKET`)]),compiledChannelDefinitionSchema=z.object({kind:z.literal(`channel`),name:z.string(),logicalPath:z.string(),method:channelMethodSchema,urlPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional(),adapterKind:z.string().optional()}).strict(),disabledCompiledChannelEntrySchema=z.object({kind:z.literal(`disabled`),name:z.string(),logicalPath:z.string()}).strict(),compiledChannelEntrySchema=z.union([compiledChannelDefinitionSchema,disabledCompiledChannelEntrySchema]),compiledRuntimeModelReferenceSchema=z.object({contextWindowTokens:z.number().int().positive().optional(),id:z.string(),source:moduleSourceRefSchema.optional(),providerOptions:z.record(z.string(),jsonObjectSchema).optional()}).strict(),compiledAgentBuildDefinitionSchema=z.object({externalDependencies:z.array(z.string()).optional()}).strict(),compiledAgentCompactionDefinitionSchema=z.object({model:compiledRuntimeModelReferenceSchema.optional(),thresholdPercent:z.number().finite().min(0).max(1).optional()}).strict(),compiledAgentConfigSchema=z.object({build:compiledAgentBuildDefinitionSchema.optional(),compaction:compiledAgentCompactionDefinitionSchema.optional(),description:z.string().optional(),experimental:z.object({codeMode:z.boolean().optional()}).strict().optional(),model:compiledRuntimeModelReferenceSchema,name:z.string(),outputSchema:jsonObjectSchema.optional(),source:moduleSourceRefSchema.optional()}).strict(),compiledInstructionsSchema=z.object({name:z.string(),logicalPath:z.string(),markdown:z.string(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSkillBaseFields={name:z.string(),description:z.string(),license:z.string().optional(),markdown:z.string(),metadata:z.record(z.string(),z.string()).optional(),sourceId:z.string(),logicalPath:z.string()},compiledSkillSourceSchema=z.discriminatedUnion(`sourceKind`,[z.object({...compiledSkillBaseFields,sourceKind:z.literal(`markdown`)}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),z.object({...compiledSkillBaseFields,sourceKind:z.literal(`skill-package`),skillId:z.string(),skillFilePath:z.string(),rootPath:z.string(),assetsPath:z.string().optional(),referencesPath:z.string().optional(),scriptsPath:z.string().optional()}).strict()]),compiledScheduleDefinitionSchema=z.object({cron:z.string(),hasRun:z.boolean(),name:z.string(),logicalPath:z.string(),markdown:z.string().optional(),sourceId:z.string(),sourceKind:z.union([z.literal(`markdown`),z.literal(`module`)])}).strict(),compiledSandboxDefinitionSchema=z.object({description:z.string().optional(),exportName:z.string().optional(),logicalPath:z.string(),revalidationKey:z.string().optional(),sourceHash:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledSandboxWorkspaceSchema=z.object({logicalPath:z.string(),rootEntries:z.array(z.string()).readonly(),sourceId:z.string(),sourcePath:z.string()}).strict(),compiledWorkspaceResourceRootSchema=z.object({contentHash:z.string().optional(),logicalPath:z.string(),rootEntries:z.array(z.string()).readonly()}).strict(),compiledConnectionDefinitionSchema=z.object({connectionName:z.string(),description:z.string(),exportName:z.string().optional(),logicalPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),url:z.string(),vercelConnect:z.object({connector:z.string()}).strict().optional()}).strict(),compiledToolDefinitionSchema=z.object({description:z.string(),exportName:z.string().optional(),inputSchema:jsonObjectSchema.nullable(),logicalPath:z.string(),name:z.string(),outputSchema:jsonObjectSchema.optional(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicSkillDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicInstructionsDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledHookDefinitionSchema=z.object({exportName:z.string().optional(),logicalPath:z.string(),slug:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledAgentNodeManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),remoteAgents:z.array(compiledRemoteAgentNodeSchema),skills:z.array(compiledSkillSourceSchema).readonly(),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict(),compiledSubagentNodeSchema=z.object({agent:compiledAgentNodeManifestSchema,description:z.string(),entryPath:z.string(),logicalPath:z.string(),name:z.string(),nodeId:z.string(),rootPath:z.string(),sourceId:z.string(),sourceKind:z.literal(`module`),exportName:z.string().optional()}).strict(),compiledSubagentEdgeSchema=z.object({childNodeId:z.string(),parentNodeId:z.string()}).strict(),compiledAgentManifestSchema=z.object({agentRoot:z.string(),appRoot:z.string(),channels:z.array(compiledChannelEntrySchema),config:compiledAgentConfigSchema,connections:z.array(compiledConnectionDefinitionSchema),diagnosticsSummary:discoverDiagnosticsSummarySchema,disabledFrameworkTools:z.array(z.string()).readonly(),dynamicInstructions:z.array(compiledDynamicInstructionsDefinitionSchema).default([]),dynamicSkills:z.array(compiledDynamicSkillDefinitionSchema).default([]),dynamicTools:z.array(compiledDynamicToolDefinitionSchema).default([]),hooks:z.array(compiledHookDefinitionSchema),kind:z.literal(COMPILED_AGENT_MANIFEST_KIND),remoteAgents:z.array(compiledRemoteAgentNodeSchema),sandbox:compiledSandboxDefinitionSchema.nullable(),sandboxWorkspaces:z.array(compiledSandboxWorkspaceSchema),schedules:z.array(compiledScheduleDefinitionSchema),skills:z.array(compiledSkillSourceSchema).readonly(),subagentEdges:z.array(compiledSubagentEdgeSchema),subagents:z.array(compiledSubagentNodeSchema),instructions:compiledInstructionsSchema.optional(),tools:z.array(compiledToolDefinitionSchema),version:z.literal(28),workspaceResourceRoot:compiledWorkspaceResourceRootSchema}).strict();function createCompiledAgentNodeManifest(e){let t={agentRoot:e.agentRoot,appRoot:e.appRoot,channels:[...e.channels??[]],connections:[...e.connections??[]],config:{build:e.config.build===void 0?void 0:{externalDependencies:e.config.build.externalDependencies===void 0?void 0:[...e.config.build.externalDependencies]},compaction:{model:e.config.compaction?.model===void 0?void 0:cloneCompiledRuntimeModelReference(e.config.compaction.model),thresholdPercent:e.config.compaction?.thresholdPercent},description:e.config.description,experimental:e.config.experimental===void 0?void 0:{codeMode:e.config.experimental.codeMode},model:cloneCompiledRuntimeModelReference(e.config.model),name:e.config.name,outputSchema:e.config.outputSchema,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],dynamicInstructions:[...e.dynamicInstructions??[]],dynamicSkills:[...e.dynamicSkills??[]],dynamicTools:[...e.dynamicTools??[]],hooks:[...e.hooks??[]],remoteAgents:[...e.remoteAgents??[]],sandbox:e.sandbox??null,sandboxWorkspaces:[...e.sandboxWorkspaces??[]],schedules:[...e.schedules??[]],skills:[...e.skills??[]],tools:[...e.tools??[]],workspaceResourceRoot:e.workspaceResourceRoot??{logicalPath:``,rootEntries:deriveResourceRootEntries({sandboxWorkspaces:e.sandboxWorkspaces,skills:e.skills})}};return e.instructions!==void 0&&(t.instructions=e.instructions),t}function deriveResourceRootEntries(e){let t=new Set;(e.skills??[]).length>0&&t.add(`skills/`);for(let n of e.sandboxWorkspaces??[])for(let e of n.rootEntries)t.add(e);return[...t].sort((e,t)=>e.localeCompare(t))}function createCompiledSubagentNodeId(e,t){return e===`__root__`?t:`${e}::${t}`}function createCompiledAgentManifest(e){return{...createCompiledAgentNodeManifest(e),kind:COMPILED_AGENT_MANIFEST_KIND,subagentEdges:[...e.subagentEdges??[]],subagents:[...e.subagents??[]],version:28}}function cloneCompiledRuntimeModelReference(e){return e.contextWindowTokens===void 0&&e.source===void 0&&e.providerOptions===void 0?{id:e.id}:e.source===void 0?e.providerOptions===void 0?{contextWindowTokens:e.contextWindowTokens,id:e.id}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:{...e.providerOptions}}:e.contextWindowTokens===void 0&&e.providerOptions===void 0?{id:e.id,source:{...e.source}}:{contextWindowTokens:e.contextWindowTokens,id:e.id,providerOptions:e.providerOptions===void 0?void 0:{...e.providerOptions},source:{...e.source}}}export{COMPILED_AGENT_MANIFEST_KIND,COMPILED_AGENT_MANIFEST_VERSION,ROOT_COMPILED_AGENT_NODE_ID,compiledAgentManifestSchema,createCompiledAgentManifest,createCompiledAgentNodeManifest,createCompiledSubagentNodeId,deriveResourceRootEntries};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return`0.
|
|
1
|
+
import{createRequire}from"node:module";import{basename,dirname,join}from"node:path";import{existsSync,readFileSync,realpathSync}from"node:fs";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const WORKFLOW_MODULE_ALIASES={"workflow/api":`src/compiled/@workflow/core/runtime.js`,"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`,"workflow/runtime":`src/compiled/@workflow/core/runtime.js`};function resolveFallbackPackageVersion(){return`0.61.0`}const FALLBACK_PACKAGE_INFO={name:ASH_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let t=e;for(;;){if(existsSync(join(t,`package.json`))&&!isBuildOutputPackageRoot(t))return t;let r=dirname(t);if(r===t)throw Error(`Failed to resolve package root from "${e}".`);t=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let n=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(n?.name===t)return n}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),ASH_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${ASH_PACKAGE_NAME}/package.json`),ASH_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveInstalledPackageInfo,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Nitro } from "nitro/types";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ChannelRouteMethod } from "#public/definitions/channel.js";
|
|
3
3
|
import type { NitroArtifactsConfigInput } from "#internal/nitro/host/artifacts-config.js";
|
|
4
4
|
import type { PreparedApplicationHost } from "#internal/nitro/host/types.js";
|
|
5
5
|
interface ChannelRouteNitro {
|
|
@@ -12,7 +12,7 @@ interface ChannelRouteNitro {
|
|
|
12
12
|
* One Nitro route registration for an Ash channel.
|
|
13
13
|
*/
|
|
14
14
|
export interface NitroChannelRouteRegistration {
|
|
15
|
-
readonly method:
|
|
15
|
+
readonly method: ChannelRouteMethod;
|
|
16
16
|
readonly route: string;
|
|
17
17
|
}
|
|
18
18
|
/**
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";const ASH_CHANNEL_VIRTUAL_ID_PREFIX=`#ash-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,i=new Set,a=[],o=new Set,s=getAllFrameworkChannelNames();for(let e of t){if(e.kind===`disabled`){if(!s.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...s].sort().join(`, `)}.`);o.add(e.name);continue}i.add(e.name),a.push({method:e.method,route:e.urlPath})}let c=getFrameworkChannelDefinitions().filter(e=>!i.has(e.name)&&!o.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),l=new Set,u=[];for(let e of[...c,...a]){let t=createChannelRouteKey(e);l.has(t)||(l.add(t),u.push(e))}return u}function registerChannelVirtualHandlers(e,t){for(let n of t.registrations)addChannelVirtualHandler(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function syncChannelVirtualHandlers(e,t){return areChannelRouteRegistrationsEqual(t.previous,t.next)?!1:(removeChannelVirtualHandlers(e),registerChannelVirtualHandlers(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function createChannelRouteKey(e){return`${e.method.toUpperCase()} ${e.route}`}function addChannelVirtualHandler(n,r){let a=createChannelRouteKey(r),o=`${ASH_CHANNEL_VIRTUAL_ID_PREFIX}${a}`,s=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/nitro/routes/channel-dispatch.ts`));n.options.handlers.push({handler:o,
|
|
1
|
+
import{resolvePackageSourceFilePath}from"#internal/application/package.js";import{stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{getAllFrameworkChannelNames,getFrameworkChannelDefinitions}from"#runtime/framework-channels/index.js";const ASH_CHANNEL_VIRTUAL_ID_PREFIX=`#ash-channel/`;function computeChannelRouteRegistrations(e){let t=e.compileResult.manifest.channels,i=new Set,a=[],o=new Set,s=getAllFrameworkChannelNames();for(let e of t){if(e.kind===`disabled`){if(!s.has(e.name))throw Error(`agent/channels/${e.name}.ts exports disableRoute() but "${e.name}" is not a framework channel. Rename the file to one of: ${[...s].sort().join(`, `)}.`);o.add(e.name);continue}i.add(e.name),a.push({method:e.method,route:e.urlPath})}let c=getFrameworkChannelDefinitions().filter(e=>!i.has(e.name)&&!o.has(e.name)).map(e=>({method:e.method,route:e.urlPath})),l=new Set,u=[];for(let e of[...c,...a]){let t=createChannelRouteKey(e);l.has(t)||(l.add(t),u.push(e))}return u}function registerChannelVirtualHandlers(e,t){for(let n of t.registrations)addChannelVirtualHandler(e,{artifactsConfig:t.artifactsConfig,method:n.method,route:n.route})}function syncChannelVirtualHandlers(e,t){return areChannelRouteRegistrationsEqual(t.previous,t.next)?!1:(removeChannelVirtualHandlers(e),registerChannelVirtualHandlers(e,{artifactsConfig:t.artifactsConfig,registrations:t.next}),e.routing.sync(),!0)}function createChannelRouteKey(e){return`${e.method.toUpperCase()} ${e.route}`}function addChannelVirtualHandler(n,r){let a=createChannelRouteKey(r),o=`${ASH_CHANNEL_VIRTUAL_ID_PREFIX}${a}`,s=stringifyEsmImportSpecifier(resolvePackageSourceFilePath(`src/internal/nitro/routes/channel-dispatch.ts`));if(r.method===`WEBSOCKET`){n.options.handlers.push({handler:o,route:r.route}),n.options.virtual[o]=[`import { defineWebSocketHandler } from "nitro";`,`import { dispatchChannelWebSocketRequest } from ${s};`,`const config = ${JSON.stringify(r.artifactsConfig)};`,`export default defineWebSocketHandler((event) => dispatchChannelWebSocketRequest(event, ${JSON.stringify(a)}, config));`].join(`
|
|
2
|
+
`);return}n.options.handlers.push({handler:o,method:r.method,route:r.route}),n.options.virtual[o]=[`import { dispatchChannelRequest } from ${s};`,`const config = ${JSON.stringify(r.artifactsConfig)};`,`export default (event) => dispatchChannelRequest(event, ${JSON.stringify(a)}, config);`].join(`
|
|
2
3
|
`)}function removeChannelVirtualHandlers(e){for(let t=e.options.handlers.length-1;t>=0;--t){let n=e.options.handlers[t];n!==void 0&&isChannelVirtualHandler(n)&&e.options.handlers.splice(t,1)}for(let t of Object.keys(e.options.virtual))t.startsWith(ASH_CHANNEL_VIRTUAL_ID_PREFIX)&&delete e.options.virtual[t]}function isChannelVirtualHandler(e){return e.handler.startsWith(ASH_CHANNEL_VIRTUAL_ID_PREFIX)}function areChannelRouteRegistrationsEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r===void 0||i===void 0||r.method!==i.method||r.route!==i.route)return!1}return!0}export{computeChannelRouteRegistrations,registerChannelVirtualHandlers,syncChannelVirtualHandlers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroBuildDirectory}from"#internal/application/paths.js";import{resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createNitro}from"nitro/builder";import{prepareAshVersionedCacheDirectory,writeAshVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyAshCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createAshVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`ash.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`];function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveNitroPreset(e){if(!e&&process.env.VERCEL)return`vercel`}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesCodeMode(e){return[e.config,...e.subagents.map(e=>e.agent.config)].some(e=>resolveCodeModeEnabled(e.experimental?.codeMode))}function resolveWorkflowStepEntrypointPath(e,t){return e.options.dev?join(e.options.buildDir,`workflow`,`steps.mjs`):join(t.workflowBuildDir,`steps.mjs`)}function collectHostedTraceDependencies(e){let t=e.compileResult.manifest.config.build;return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...SERVER_EXTERNAL_PACKAGES,...t?.externalDependencies??[]])].filter(e=>e!==ASH_PACKAGE_NAME)}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,n){return n.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(n)))):isAbsolute(n)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(n))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,n))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(t,n,r){return n.startsWith(`workflow`)?resolveWorkflowModulePath(n):n.startsWith(`.`)||n.startsWith(`/`)||n.startsWith(`file://`)?resolveNitroModuleComparisonPath(r===void 0?t:dirname(resolveNitroModuleComparisonPath(t,r)),n):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=n.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(n.length+1);if(o===a)return`.`;let s=relative(n,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function addWorkflowModuleSideEffectsPlugin(e,t){let r=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,n){let i=resolveNitroImportPath(e.options.rootDir,t,n)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return r.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`ash:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}async function createApplicationNitro(e,t,r={}){let i=r.surface??`all`,a=!t&&includesApplicationSurface(i)&&e.scheduleRegistrations.length>0,c=resolveNitroPreset(t),l=c===`vercel`?createCompiledSandboxBackendPrunePlugin():null,u=l===null?[]:[l],d=createNitroBundlerConfig(u),f=createNitroBundlerConfig(u),p=collectHostedTraceDependencies(e),m=resolveNitroBuildDirectory(e.appRoot,i),h=[];manifestEnablesCodeMode(e.compileResult.manifest)&&h.push(resolvePackageSourceFilePath(`src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&h.push(e.compiledArtifacts.instrumentationPluginPath),h.push(e.compiledArtifacts.bootstrapPath),await prepareAshVersionedCacheDirectory(m);let g=await createNitro({_cli:{command:t?`dev`:`build`},buildDir:m,dev:t,logLevel:t?1:void 0,output:r.outputDir===void 0?void 0:{dir:r.outputDir},preset:c,plugins:h,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(i)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:d,rollupConfig:f,rootDir:e.appRoot,serverDir:!1,traceDeps:p,vercel:createAshVercelOptions(c===`vercel`&&includesApplicationSurface(i))},t?{watch:!0}:void 0);if(await writeAshVersionedCacheMetadata(m),addNitroRoutingImportSpecifierPlugin(g),includesWorkflowSurface(i)){let t=resolveWorkflowAliases();for(let[e,n]of Object.entries(t))g.options.alias[e]=n;addWorkflowModuleSideEffectsPlugin(g,e.workflowBuildDir),patchWorkflowTransformExcludePath(g,e.workflowBuildDir)}if(includesWorkflowStepRegistrations(i)){let t=resolveWorkflowStepEntrypointPath(g,e);addNitroStepModuleSideEffectsPlugin(g,{stepEntrypointPath:t}),addNitroStepTransformPlugin(g,{stepEntrypointPath:t})}if(addDynamicToolTransformPlugin(g),e.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(g,e.compiledArtifacts.instrumentationSourcePath),t&&includesWorkflowSurface(i)){let t=e.workflowBuildDir,r=new Set([normalizePath(join(t,`workflows.mjs`))]);g.hooks.hook(`rollup:before`,(e,t)=>{let n=t.external;t.external=(e,...t)=>{if(r.has(normalizePath(e)))return!0;if(typeof n==`function`)return n(e,...t)}})}return a&&(applyAshCronHandlerRoute(g),registerScheduleTaskHandlers(g,{artifactsConfig:createNitroArtifactsConfig({appRoot:e.appRoot,dev:g.options.dev}),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureNitroRoutes(g,e,{surface:i}),includesWorkflowStepRegistrations(i)&&await addNitroStepNoExternals(g,resolveWorkflowStepEntrypointPath(g,e)),g}export{createApplicationNitro};
|
|
1
|
+
import{dirname,isAbsolute,join,relative,resolve}from"node:path";import{readFile}from"node:fs/promises";import{resolveNitroBuildDirectory}from"#internal/application/paths.js";import{resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{ASH_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";import{createNitro}from"nitro/builder";import{prepareAshVersionedCacheDirectory,writeAshVersionedCacheMetadata}from"#internal/application/cache-metadata.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{createCompiledSandboxBackendPrunePlugin}from"#internal/nitro/host/compiled-sandbox-backend-prune-plugin.js";import{configureNitroRoutes}from"#internal/nitro/host/configure-nitro-routes.js";import{applyAshCronHandlerRoute}from"#internal/nitro/host/cron-handler-route.js";import{createNitroBundlerConfig}from"#internal/nitro/host/nitro-bundler-config.js";import{addNitroRoutingImportSpecifierPlugin}from"#internal/nitro/host/nitro-routing-import-specifier-plugin.js";import{registerScheduleTaskHandlers}from"#internal/nitro/host/schedule-task-routes.js";import{SERVER_EXTERNAL_PACKAGES}from"#internal/nitro/host/server-external-packages.js";import{createAshVercelOptions}from"#internal/nitro/host/vercel-build-output-config.js";import{applyWorkflowTransform}from"#internal/workflow-bundle/workflow-builders.js";import{transformDynamicToolExecute}from"#internal/workflow-bundle/dynamic-tool-transform.js";const WORKFLOW_ALIAS_SPECIFIERS=[`workflow`,`workflow/api`,`workflow/errors`,`workflow/internal/builtins`,`workflow/internal/private`,`workflow/runtime`],WORKFLOW_TRANSFORM_PATCHED=Symbol(`ash.workflow-transform-patched`),FRAMEWORK_HOSTED_EXTERNAL_PACKAGES=[`@napi-rs/keyring`];function resolveWorkflowAliases(){let e={};for(let t of WORKFLOW_ALIAS_SPECIFIERS)e[t]=resolveWorkflowModulePath(t);return e}function resolveNitroPreset(e){if(!e&&process.env.VERCEL)return`vercel`}function includesApplicationSurface(e){return e===`all`||e===`app`}function includesWorkflowSurface(e){return e===`all`||e===`flow`}function includesWorkflowStepRegistrations(e){return includesWorkflowSurface(e)}function manifestEnablesCodeMode(e){return[e.config,...e.subagents.map(e=>e.agent.config)].some(e=>resolveCodeModeEnabled(e.experimental?.codeMode))}function manifestHasWebSocketChannel(e){return e.channels.some(e=>e.kind===`channel`&&e.method===`WEBSOCKET`)}function resolveWorkflowStepEntrypointPath(e,t){return e.options.dev?join(e.options.buildDir,`workflow`,`steps.mjs`):join(t.workflowBuildDir,`steps.mjs`)}function collectHostedTraceDependencies(e){let t=e.compileResult.manifest.config.build;return[...new Set([...FRAMEWORK_HOSTED_EXTERNAL_PACKAGES,...SERVER_EXTERNAL_PACKAGES,...t?.externalDependencies??[]])].filter(e=>e!==ASH_PACKAGE_NAME)}function normalizePath(e){return e.replaceAll(`\\`,`/`)}function stripPathQueryAndHash(e){let t=e.indexOf(`?`),n=e.indexOf(`#`),r=t===-1?n:n===-1?t:Math.min(t,n);return r===-1?e:e.slice(0,r)}function stripFileSystemPrefix(e){return e.startsWith(`/@fs/`)?e.slice(4):e}function resolveNitroModuleComparisonPath(e,n){return n.startsWith(`file://`)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(fileURLToPath(n)))):isAbsolute(n)?normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(n))):normalizePath(stripFileSystemPrefix(stripPathQueryAndHash(resolve(e,n))))}function isWorkflowBundlePath(e,t){let n=normalizePath(e);return n.startsWith(t)||n.includes(`/.ash/workflow-cache/`)}function normalizeStepTransformComparisonPath(e){let t=normalizePath(e);return process.platform===`win32`?t.toLowerCase():t}function parseImportedModuleSpecifiers(e){let t=/^\s*import\s+(?:.+?\s+from\s+)?["']([^"']+)["'];?\s*$/gm,n=[];for(let r of e.matchAll(t)){let e=r[1];e!==void 0&&n.push(e)}return n}function resolveNitroImportPath(t,n,r){return n.startsWith(`workflow`)?resolveWorkflowModulePath(n):n.startsWith(`.`)||n.startsWith(`/`)||n.startsWith(`file://`)?resolveNitroModuleComparisonPath(r===void 0?t:dirname(resolveNitroModuleComparisonPath(t,r)),n):null}async function collectNitroStepTransformTargets(e,t){let n=await readFile(e,`utf8`),r=new Set;for(let i of parseImportedModuleSpecifiers(n)){let n=resolveNitroImportPath(t,i,e);n!==null&&r.add(normalizeStepTransformComparisonPath(n))}return r}async function addNitroStepNoExternals(e,t){if(e.options.noExternals===!0)return;let n;try{n=await collectNitroStepTransformTargets(t,e.options.rootDir)}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return;throw e}let r=Array.isArray(e.options.noExternals)?[...e.options.noExternals]:[];e.options.noExternals=[...new Set([...r,...n])]}function createRelativeTransformFilename(e,t){let n=normalizePath(e).replace(/\/$/,``),i=normalizePath(t),a=n.toLowerCase(),o=i.toLowerCase();if(o.startsWith(`${a}/`))return i.slice(n.length+1);if(o===a)return`.`;let s=relative(n,i).replaceAll(`\\`,`/`);if(s.startsWith(`../`)&&(s=s.split(`/`).filter(e=>e!==`..`).join(`/`)),s.includes(`:`)||s.startsWith(`/`)){let e=i.split(`/`).pop();return e===void 0||e.length===0?`unknown.ts`:e}return s}function addWorkflowModuleSideEffectsPlugin(e,t){let r=[t,join(e.options.buildDir,`workflow`)].map(t=>resolveNitroModuleComparisonPath(e.options.rootDir,t));e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-module-side-effects`,resolveId(t,n){let i=resolveNitroImportPath(e.options.rootDir,t,n)??resolveNitroModuleComparisonPath(e.options.rootDir,t);return r.some(e=>isWorkflowBundlePath(i,e))?{id:i,moduleSideEffects:`no-treeshake`}:null}})})}function addNitroStepModuleSideEffectsPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({name:`ash:workflow-step-module-side-effects`,async resolveId(t,n){let r=resolveNitroImportPath(e.options.rootDir,t,n);return r===null||!(await getStepTransformTargets()).has(normalizeStepTransformComparisonPath(r))?null:{id:r,moduleSideEffects:`no-treeshake`}}})})}function addNitroStepTransformPlugin(e,t){let n=null,getStepTransformTargets=async()=>(n===null&&(n=await collectNitroStepTransformTargets(t.stepEntrypointPath,e.options.rootDir)),n);e.hooks.hook(`build:before`,()=>{n=null}),e.options.dev&&e.hooks.hook(`dev:reload`,()=>{n=null}),e.hooks.hook(`rollup:before`,(t,n)=>{Array.isArray(n.plugins)&&n.plugins.unshift({async transform(t,n){let r=await getStepTransformTargets(),i=resolveNitroModuleComparisonPath(e.options.rootDir,n);return r.has(normalizeStepTransformComparisonPath(i))?{code:(await applyWorkflowTransform(createRelativeTransformFilename(e.options.rootDir,i),t,`step`,i,e.options.rootDir)).code,map:null}:null},name:`ash:workflow-step-transform`})})}function addDynamicToolTransformPlugin(e){e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({async transform(e,t){if(!t.includes(`/tools/`))return null;let n=await transformDynamicToolExecute(t,e);return n===null?null:{code:n.code,map:null}},name:`ash:dynamic-tool-transform`})})}function addInstrumentationModuleSideEffectsPlugin(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{Array.isArray(t.plugins)&&t.plugins.unshift({name:`ash:instrumentation-module-side-effects`,resolveId(e){return normalizePath(e)===n?{id:e,moduleSideEffects:`no-treeshake`}:null}})})}function patchWorkflowTransformExcludePath(e,t){let n=normalizePath(t);e.hooks.hook(`rollup:before`,(e,t)=>{if(Array.isArray(t.plugins))for(let e of t.plugins){if(typeof e!=`object`||!e)continue;let t=e;if(t.name!==`workflow:transform`||t[WORKFLOW_TRANSFORM_PATCHED]===!0||typeof t.transform!=`function`)continue;let r=t.transform;t.transform=function(e,t,...i){return isWorkflowBundlePath(t,n)?null:r.call(this,e,t,...i)},t[WORKFLOW_TRANSFORM_PATCHED]=!0}})}async function createApplicationNitro(e,t,r={}){let i=r.surface??`all`,a=!t&&includesApplicationSurface(i)&&e.scheduleRegistrations.length>0,c=resolveNitroPreset(t),l=c===`vercel`?createCompiledSandboxBackendPrunePlugin():null,u=l===null?[]:[l],d=createNitroBundlerConfig(u),f=createNitroBundlerConfig(u),p=collectHostedTraceDependencies(e),m=resolveNitroBuildDirectory(e.appRoot,i),h=includesApplicationSurface(i)&&(t||manifestHasWebSocketChannel(e.compileResult.manifest)),g=[];manifestEnablesCodeMode(e.compileResult.manifest)&&g.push(resolvePackageSourceFilePath(`src/internal/nitro/host/code-mode-runtime-dependency-plugin.ts`)),e.compiledArtifacts.instrumentationPluginPath!==void 0&&g.push(e.compiledArtifacts.instrumentationPluginPath),g.push(e.compiledArtifacts.bootstrapPath),await prepareAshVersionedCacheDirectory(m);let _=await createNitro({_cli:{command:t?`dev`:`build`},buildDir:m,dev:t,features:{websocket:h},logLevel:t?1:void 0,output:r.outputDir===void 0?void 0:{dir:r.outputDir},preset:c,plugins:g,publicAssets:[],scanDirs:includesWorkflowStepRegistrations(i)?[resolvePackageSourceDirectoryPath(`src/execution`)]:void 0,rolldownConfig:d,rollupConfig:f,rootDir:e.appRoot,serverDir:!1,traceDeps:p,vercel:createAshVercelOptions(c===`vercel`&&includesApplicationSurface(i))},t?{watch:!0}:void 0);if(await writeAshVersionedCacheMetadata(m),addNitroRoutingImportSpecifierPlugin(_),includesWorkflowSurface(i)){let t=resolveWorkflowAliases();for(let[e,n]of Object.entries(t))_.options.alias[e]=n;addWorkflowModuleSideEffectsPlugin(_,e.workflowBuildDir),patchWorkflowTransformExcludePath(_,e.workflowBuildDir)}if(includesWorkflowStepRegistrations(i)){let t=resolveWorkflowStepEntrypointPath(_,e);addNitroStepModuleSideEffectsPlugin(_,{stepEntrypointPath:t}),addNitroStepTransformPlugin(_,{stepEntrypointPath:t})}if(addDynamicToolTransformPlugin(_),e.compiledArtifacts.instrumentationSourcePath!==void 0&&addInstrumentationModuleSideEffectsPlugin(_,e.compiledArtifacts.instrumentationSourcePath),t&&includesWorkflowSurface(i)){let t=e.workflowBuildDir,r=new Set([normalizePath(join(t,`workflows.mjs`))]);_.hooks.hook(`rollup:before`,(e,t)=>{let n=t.external;t.external=(e,...t)=>{if(r.has(normalizePath(e)))return!0;if(typeof n==`function`)return n(e,...t)}})}return a&&(applyAshCronHandlerRoute(_),registerScheduleTaskHandlers(_,{artifactsConfig:createNitroArtifactsConfig({appRoot:e.appRoot,dev:_.options.dev}),dispatchModulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/schedule-task.ts`),registrations:e.scheduleRegistrations})),await configureNitroRoutes(_,e,{surface:i}),includesWorkflowStepRegistrations(i)&&await addNitroStepNoExternals(_,resolveWorkflowStepEntrypointPath(_,e)),_}export{createApplicationNitro};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { H3Event } from "nitro";
|
|
2
|
+
import type { WebSocketRouteHooks } from "#channel/routes.js";
|
|
2
3
|
import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifacts.js";
|
|
3
4
|
/**
|
|
4
5
|
* Dispatches one channel request identified by `routeKey`.
|
|
@@ -18,3 +19,4 @@ import type { NitroArtifactsConfig } from "#internal/nitro/routes/runtime-artifa
|
|
|
18
19
|
* with just `fetch` and receive a `RouteContext` carrying `agent`.
|
|
19
20
|
*/
|
|
20
21
|
export declare function dispatchChannelRequest(event: H3Event, routeKey: string, config: NitroArtifactsConfig): Promise<Response>;
|
|
22
|
+
export declare function dispatchChannelWebSocketRequest(event: H3Event, routeKey: string, config: NitroArtifactsConfig): Promise<WebSocketRouteHooks>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(t,
|
|
1
|
+
import{createGetSessionFn}from"#channel/session.js";import{createLogger,logError}from"#internal/logging.js";import{createSendFn}from"#channel/send.js";import{createCrossChannelReceiveFn,toCrossChannelTargets}from"#channel/cross-channel-receive.js";import{resolveNitroChannelRuntimeBundle}from"#internal/nitro/routes/runtime-stack.js";const log=createLogger(`channel.dispatch`);async function dispatchChannelRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0)return Response.json({error:`No matching channel for this request.`,ok:!1},{status:404});let c=buildRouteArgs(e,i,a.name),l;try{if(a.handler)l=await a.handler(e.req,c.args);else{let t={agent:i.runtime,waitUntil:c.args.waitUntil,params:c.args.params,requestIp:c.args.requestIp};l=await a.fetch(e.req,t)}}catch(r){let i=logError(log,`channel handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),Response.json({error:`Channel handler failed.`,errorId:i,ok:!1},{status:500})}return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),l}async function dispatchChannelWebSocketRequest(e,t,r){let i=await resolveNitroChannelRuntimeBundle(r),a=i.channels.find(e=>`${e.method.toUpperCase()} ${e.urlPath}`===t);if(a===void 0||a.websocket===void 0)return rejectWebSocketUpgrade({error:`No matching websocket channel for this request.`,ok:!1},404);let c=buildRouteArgs(e,i,a.name);try{let n=await a.websocket(e.req,c.args);return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),n}catch(r){let i=logError(log,`channel websocket handler threw`,r,{routeKey:t,channel:a.name});return flushBackgroundTasks(e,c.backgroundTasks,t,a.name),rejectWebSocketUpgrade({error:`Channel websocket handler failed.`,errorId:i,ok:!1},500)}}function buildRouteArgs(t,n,o){let s=extractSocketIp(t),c=[],l=t.context.params??{},u={};for(let[e,t]of Object.entries(l))u[e]=decodeURIComponent(t);let waitUntil=e=>{c.push(e)},d=n.channels.find(e=>e.name===o)?.adapter??{kind:`channel`};return{args:{send:createSendFn(n.runtime,d,o),getSession:createGetSessionFn(n.runtime),receive:createCrossChannelReceiveFn(n.runtime,toCrossChannelTargets(n.channels)),params:u,waitUntil,requestIp:s},backgroundTasks:c}}function rejectWebSocketUpgrade(e,t){return{upgrade(){throw Response.json(e,{status:t})}}}function flushBackgroundTasks(e,t,r,i){t.length!==0&&e.waitUntil(Promise.allSettled(t).then(e=>{for(let t of e)t.status===`rejected`&&logError(log,`channel background task failed`,t.reason,{routeKey:r,channel:i})}))}function extractSocketIp(e){let t=e.req.ip;return typeof t==`string`&&t.length>0?t:null}export{dispatchChannelRequest,dispatchChannelWebSocketRequest};
|
|
@@ -35,7 +35,7 @@ export declare const VERCEL_ASH_AGENT_SUMMARY_KIND: "vercel-ash-agent-summary";
|
|
|
35
35
|
* making semantic changes consumers must opt into. Adding optional fields
|
|
36
36
|
* does not require a version bump.
|
|
37
37
|
*/
|
|
38
|
-
export declare const VERCEL_ASH_AGENT_SUMMARY_VERSION =
|
|
38
|
+
export declare const VERCEL_ASH_AGENT_SUMMARY_VERSION = 3;
|
|
39
39
|
/**
|
|
40
40
|
* Output path (relative to the agent's `appRoot`) where Ash writes the
|
|
41
41
|
* summary file at build time.
|
|
@@ -129,7 +129,7 @@ export interface VercelAshConnectionEntry {
|
|
|
129
129
|
}
|
|
130
130
|
export interface VercelAshChannelEntry {
|
|
131
131
|
readonly name: string;
|
|
132
|
-
readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
132
|
+
readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "WEBSOCKET";
|
|
133
133
|
readonly urlPath: string;
|
|
134
134
|
readonly type: VercelAshChannelType;
|
|
135
135
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const VERCEL_ASH_AGENT_SUMMARY_KIND=`vercel-ash-agent-summary`,VERCEL_ASH_AGENT_SUMMARY_VERSION=
|
|
1
|
+
const VERCEL_ASH_AGENT_SUMMARY_KIND=`vercel-ash-agent-summary`,VERCEL_ASH_AGENT_SUMMARY_VERSION=3,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH=`.ash/agent-summary.json`;function normalizeChannelKindForDisplay(e){if(typeof e!=`string`||e.length===0)return`unknown`;let t=e.toLowerCase();return t===`slack`||t.includes(`slack`)?`slack`:t===`http`?`http`:t.includes(`webhook`)?`webhook`:`unknown`}export{VERCEL_ASH_AGENT_SUMMARY_KIND,VERCEL_ASH_AGENT_SUMMARY_OUTPUT_PATH,VERCEL_ASH_AGENT_SUMMARY_VERSION,normalizeChannelKindForDisplay};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import{PNPM_WORKSPACE_PATH,ensurePnpmWorkspacePolicy}from"./pnpm-workspace.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"./web-template.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},ash:{buildCommand:`ash build`,entrypoint:`.`,framework:`ash`,routePrefix:`/_ash_internal/ash`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,t){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,t)}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{ashPackageVersion:e?.ashPackageVersion??`0.
|
|
1
|
+
import{getSupportedModuleBaseName,matchesSupportedModuleBaseName}from"./module-files.js";import{pathExists,writeTextFile}from"./files.js";import{PNPM_WORKSPACE_PATH,ensurePnpmWorkspacePolicy}from"./pnpm-workspace.js";import{WEB_APP_TEMPLATE_FILES,WEB_APP_TEMPLATE_PACKAGE_JSON}from"./web-template.js";import"./project.js";import{patchPackageJson}from"./package-json.js";import{basename,join,resolve}from"node:path";import{readFile,readdir,writeFile}from"node:fs/promises";const SLACK_CHANNEL_DEFAULT_ROUTE=`/ash/v1/slack`,DEFAULT_SLACK_CONNECTOR_SLUG=`my-agent`,PACKAGE_DEPENDENCY_FIELDS=[`dependencies`,`devDependencies`,`peerDependencies`,`optionalDependencies`],WEB_NEXT_CONFIG_PATH=`next.config.ts`,WEB_VERCEL_JSON_PATH=`vercel.json`,WEB_VERCEL_JSON_SCHEMA=`https://openapi.vercel.sh/vercel.json`,WEB_COMPETING_NEXT_CONFIG_PATHS=[`next.config.js`,`next.config.mjs`,WEB_NEXT_CONFIG_PATH,`next.config.mts`].filter(e=>e!==WEB_NEXT_CONFIG_PATH),WEB_DEFAULT_VERCEL_SERVICES={web:{entrypoint:`.`,framework:`nextjs`,routePrefix:`/`},ash:{buildCommand:`ash build`,entrypoint:`.`,framework:`ash`,routePrefix:`/_ash_internal/ash`}};function toSlackConnectorSlug(e){return e}function isJsonObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function readDependencyVersion(e,t){let n=JSON.parse(await readFile(e,`utf8`));if(!isJsonObject(n)||!isJsonObject(n.dependencies))return;let r=n.dependencies[t];return typeof r==`string`?r:void 0}function packageJsonHasDependency(e,t){for(let n of PACKAGE_DEPENDENCY_FIELDS){let r=e[n];if(isJsonObject(r)&&typeof r[t]==`string`)return!0}return!1}async function hasPackageDependency(e,t){if(!await pathExists(e))return!1;let r=JSON.parse(await readFile(e,`utf8`));return isJsonObject(r)&&packageJsonHasDependency(r,t)}async function ensurePackageDependency(e,t,r){return!await pathExists(e)||await readDependencyVersion(e,t)===r?[]:(await patchPackageJson(e,{dependencies:{[t]:r}}),[{path:e,dependencies:[t],devDependencies:[],scripts:[]}])}function resolveWebPackageVersions(e){return{ashPackageVersion:e?.ashPackageVersion??`0.61.0`,aiPackageVersion:e?.aiPackageVersion??`7.0.0-canary.159`,nextPackageVersion:e?.nextPackageVersion??`16.2.6`,reactPackageVersion:e?.reactPackageVersion??`19.2.6`,reactDomPackageVersion:e?.reactDomPackageVersion??`19.2.6`,streamdownPackageVersion:e?.streamdownPackageVersion??`2.5.0`,zodPackageVersion:e?.zodPackageVersion??`4.4.3`,tsgoPackageVersion:e?.tsgoPackageVersion??`7.0.0-dev.20260523.1`,typesNodePackageVersion:e?.typesNodePackageVersion??`25.9.1`,typesReactPackageVersion:e?.typesReactPackageVersion??`19.2.15`,typesReactDomPackageVersion:e?.typesReactDomPackageVersion??`19.2.3`}}function formatAshDependencySpecifier(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z-.]+)?$/.test(e)?`^${e}`:e}async function patchWebPackageJson(e,t){if(!await pathExists(e))return[];assertStampedVersion(`ashPackageVersion`,t.ashPackageVersion),assertStampedVersion(`aiPackageVersion`,t.aiPackageVersion),assertStampedVersion(`nextPackageVersion`,t.nextPackageVersion),assertStampedVersion(`reactPackageVersion`,t.reactPackageVersion),assertStampedVersion(`reactDomPackageVersion`,t.reactDomPackageVersion),assertStampedVersion(`streamdownPackageVersion`,t.streamdownPackageVersion),assertStampedVersion(`zodPackageVersion`,t.zodPackageVersion),assertStampedVersion(`tsgoPackageVersion`,t.tsgoPackageVersion),assertStampedVersion(`typesNodePackageVersion`,t.typesNodePackageVersion),assertStampedVersion(`typesReactPackageVersion`,t.typesReactPackageVersion),assertStampedVersion(`typesReactDomPackageVersion`,t.typesReactDomPackageVersion);let r={...WEB_APP_TEMPLATE_PACKAGE_JSON.dependencies,ai:t.aiPackageVersion,"experimental-ash":formatAshDependencySpecifier(t.ashPackageVersion),next:t.nextPackageVersion,react:t.reactPackageVersion,"react-dom":t.reactDomPackageVersion,streamdown:t.streamdownPackageVersion,zod:t.zodPackageVersion},i={...WEB_APP_TEMPLATE_PACKAGE_JSON.devDependencies,"@types/node":t.typesNodePackageVersion,"@types/react":t.typesReactPackageVersion,"@types/react-dom":t.typesReactDomPackageVersion,"@typescript/native-preview":t.tsgoPackageVersion},a=WEB_APP_TEMPLATE_PACKAGE_JSON.scripts;return await patchPackageJson(e,{dependencies:r,devDependencies:i,scripts:a}),[{path:e,dependencies:Object.keys(r),devDependencies:Object.keys(i),scripts:Object.keys(a)}]}function normalizeSlackConnectorSlug(e){return toSlackConnectorSlug((e.trim().replace(/^@/,``).split(`/`).at(-1)??``).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^[^a-z0-9]+/,``).replace(/[^a-z0-9]+$/,``).slice(0,100).replace(/[^a-z0-9]+$/,``)||`my-agent`)}async function deriveSlackConnectorSlug(e,t){if(t!==void 0&&t.length>0&&t!==`.`)return normalizeSlackConnectorSlug(t);try{let t=await readFile(join(e,`package.json`),`utf8`),n=JSON.parse(t);if(typeof n.name==`string`&&n.name.length>0)return normalizeSlackConnectorSlug(n.name)}catch{}return normalizeSlackConnectorSlug(basename(resolve(e))||`my-agent`)}function buildSlackTemplate(e){return`import { connectSlackCredentials } from "@vercel/connect/ash";
|
|
2
2
|
import { slackChannel } from "experimental-ash/channels/slack";
|
|
3
3
|
|
|
4
4
|
export default slackChannel({
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { defineChannel, GET, POST, PUT, PATCH, DELETE, type Channel, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, } from "#public/definitions/defineChannel.js";
|
|
1
|
+
export { defineChannel, GET, POST, PUT, PATCH, DELETE, WS, type Channel, type ChannelDefinition, type ChannelSessionOps, type ChannelEvents, type InferChannelMetadata, type Session, type SessionHandle, type RouteDefinition, type RouteHandlerArgs, type SendFn, type SendOptions, type SendPayload, type GetSessionFn, type HttpRouteDefinition, type WebSocketMessage, type WebSocketPeer, type WebSocketRouteDefinition, type WebSocketRouteHandler, type WebSocketRouteHooks, type WebSocketUpgradeRequest, type WebSocketUpgradeResult, } from "#public/definitions/defineChannel.js";
|
|
2
2
|
import type { Channel } from "#public/definitions/defineChannel.js";
|
|
3
3
|
/**
|
|
4
4
|
* Base channel metadata shape used by framework channel kinds.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{DELETE,GET,PATCH,POST,PUT,defineChannel}from"#public/definitions/defineChannel.js";function isChannel(e,t){return e.kind===getChannelInstrumentationKind(t)}export{DELETE,GET,PATCH,POST,PUT,defineChannel,isChannel};
|
|
1
|
+
import{getChannelInstrumentationKind}from"#channel/compiled-channel.js";import{DELETE,GET,PATCH,POST,PUT,WS,defineChannel}from"#public/definitions/defineChannel.js";function isChannel(e,t){return e.kind===getChannelInstrumentationKind(t)}export{DELETE,GET,PATCH,POST,PUT,WS,defineChannel,isChannel};
|
|
@@ -7,6 +7,13 @@ export type { GetEventStreamOptions } from "#channel/types.js";
|
|
|
7
7
|
* long-poll endpoint or an event-stream reader.
|
|
8
8
|
*/
|
|
9
9
|
export type ChannelMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
10
|
+
/**
|
|
11
|
+
* Method-like discriminator used by compiled channel route entries.
|
|
12
|
+
*
|
|
13
|
+
* WebSocket routes are not HTTP methods, but they still need a stable
|
|
14
|
+
* route key in the compiler manifest and runtime route table.
|
|
15
|
+
*/
|
|
16
|
+
export type ChannelRouteMethod = ChannelMethod | "WEBSOCKET";
|
|
10
17
|
/**
|
|
11
18
|
* Per-request surface exposed to a route's `fetch` handler. The
|
|
12
19
|
* framework constructs this per request and passes it as the second
|
|
@@ -8,8 +8,8 @@ import type { RouteDefinition, SendFn } from "#channel/routes.js";
|
|
|
8
8
|
import type { Session, SessionHandle } from "#channel/session.js";
|
|
9
9
|
declare const CHANNEL_METADATA_TYPE: unique symbol;
|
|
10
10
|
export type { Session, SessionHandle } from "#channel/session.js";
|
|
11
|
-
export { GET, POST, PUT, PATCH, DELETE } from "#channel/routes.js";
|
|
12
|
-
export type { RouteDefinition, RouteHandlerArgs, SendFn, SendOptions, SendPayload, GetSessionFn, } from "#channel/routes.js";
|
|
11
|
+
export { GET, POST, PUT, PATCH, DELETE, WS } from "#channel/routes.js";
|
|
12
|
+
export type { HttpRouteDefinition, RouteDefinition, RouteHandlerArgs, SendFn, SendOptions, SendPayload, GetSessionFn, WebSocketMessage, WebSocketPeer, WebSocketRouteDefinition, WebSocketRouteHandler, WebSocketRouteHooks, WebSocketUpgradeRequest, WebSocketUpgradeResult, } from "#channel/routes.js";
|
|
13
13
|
type EventData<T extends HandleMessageStreamEvent["type"]> = Extract<HandleMessageStreamEvent, {
|
|
14
14
|
type: T;
|
|
15
15
|
}> extends {
|
|
@@ -111,10 +111,7 @@ export interface ChannelDefinition<TState = undefined, TCtx = void, TReceiveTarg
|
|
|
111
111
|
export interface Channel<TState = undefined, TReceiveTarget = Record<string, unknown>, TMetadata extends Record<string, unknown> = Record<string, unknown>> extends TypedReceiveTarget<TReceiveTarget> {
|
|
112
112
|
readonly __kind: typeof CHANNEL_SENTINEL;
|
|
113
113
|
readonly [CHANNEL_METADATA_TYPE]?: TMetadata;
|
|
114
|
-
readonly routes: readonly
|
|
115
|
-
method: string;
|
|
116
|
-
path: string;
|
|
117
|
-
}[];
|
|
114
|
+
readonly routes: readonly RouteDefinition<TState>[];
|
|
118
115
|
readonly receive?: (input: ReceiveInput<TReceiveTarget>, args: {
|
|
119
116
|
send: SendFn<TState>;
|
|
120
117
|
}) => Promise<Session>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{DELETE,GET,PATCH,POST,PUT}from"#channel/routes.js";function defineChannel(t){let n=buildAdapter(t);return{__kind:CHANNEL_SENTINEL,routes:t.routes,adapter:n,receive:t.receive}}function buildAdapter(e){let i=e.state!=null,a=e.context!=null,o=e.fetchFile!==void 0,s=e.metadata,c=i||a||s!==void 0,l={},u=!1,d=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`authorization.required`,`authorization.completed`],f=e.events;for(let e of d){let t=f?.[e];t&&(u=!0,l[e]=(r,i)=>{let a={...i,continuationToken:i.session?.continuationToken??``,setContinuationToken:e=>i.session?.setContinuationToken(e)};return e===`session.failed`?t(r,a):t(r,a,buildCallbackContext())})}return!c&&!u&&!o?{kind:e.kindHint??HTTP_ADAPTER_KIND}:{kind:e.kindHint??`defineChannel`,state:i?{...e.state}:{},fetchFile:e.fetchFile,instrumentation:s===void 0?void 0:{metadata(e){return s(e)}},createAdapterContext(t){let n=t.state,r=t.session;return{...a?e.context(n,r):{},state:n,ctx:t.ctx,session:r}},deliver(e){return defaultDeliverResult(e)},...l}}export{DELETE,GET,PATCH,POST,PUT,defineChannel};
|
|
1
|
+
import{CHANNEL_SENTINEL}from"#channel/compiled-channel.js";import{defaultDeliverResult}from"#channel/adapter.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{HTTP_ADAPTER_KIND}from"#channel/http.js";import{DELETE,GET,PATCH,POST,PUT,WS}from"#channel/routes.js";function defineChannel(t){let n=buildAdapter(t);return{__kind:CHANNEL_SENTINEL,routes:t.routes,adapter:n,receive:t.receive}}function buildAdapter(e){let i=e.state!=null,a=e.context!=null,o=e.fetchFile!==void 0,s=e.metadata,c=i||a||s!==void 0,l={},u=!1,d=[`turn.started`,`actions.requested`,`action.result`,`message.completed`,`message.appended`,`input.requested`,`turn.failed`,`turn.completed`,`session.failed`,`session.completed`,`session.waiting`,`authorization.required`,`authorization.completed`],f=e.events;for(let e of d){let t=f?.[e];t&&(u=!0,l[e]=(r,i)=>{let a={...i,continuationToken:i.session?.continuationToken??``,setContinuationToken:e=>i.session?.setContinuationToken(e)};return e===`session.failed`?t(r,a):t(r,a,buildCallbackContext())})}return!c&&!u&&!o?{kind:e.kindHint??HTTP_ADAPTER_KIND}:{kind:e.kindHint??`defineChannel`,state:i?{...e.state}:{},fetchFile:e.fetchFile,instrumentation:s===void 0?void 0:{metadata(e){return s(e)}},createAdapterContext(t){let n=t.state,r=t.session;return{...a?e.context(n,r):{},state:n,ctx:t.ctx,session:r}},deliver(e){return defaultDeliverResult(e)},...l}}export{DELETE,GET,PATCH,POST,PUT,WS,defineChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{localDev,vercelOidc}from"#public/channels/auth.js";import{ashChannel}from"#public/channels/ash.js";import{getConnectionCallbackChannelDefinitions,getConnectionCallbackChannelNames}from"#runtime/connections/callback-route.js";import{getSessionCallbackChannelDefinitions,getSessionCallbackChannelNames}from"#runtime/session-callback-route.js";function getFrameworkChannelDefinitions(){let r=ashChannel({auth:[localDev(),vercelOidc()]}),i=[];for(let e of r.routes)i.push({name:`ash`,method:e.method.toUpperCase(),urlPath:e.path,fetch:async(t,n)=>e.handler(t,n),handler:e.handler,adapter:r.adapter,logicalPath:`framework://channels/${e.path}`,sourceId:`ash:framework:${e.method.toLowerCase()}-${e.path}`,sourceKind:`module`});return i.push(...getConnectionCallbackChannelDefinitions(),...getSessionCallbackChannelDefinitions()),i}function getAllFrameworkChannelNames(){return new Set([`ash`,...getConnectionCallbackChannelNames(),...getSessionCallbackChannelNames()])}export{getAllFrameworkChannelNames,getFrameworkChannelDefinitions};
|
|
1
|
+
import{localDev,vercelOidc}from"#public/channels/auth.js";import{isHttpRouteDefinition}from"#channel/routes.js";import{ashChannel}from"#public/channels/ash.js";import{getConnectionCallbackChannelDefinitions,getConnectionCallbackChannelNames}from"#runtime/connections/callback-route.js";import{getSessionCallbackChannelDefinitions,getSessionCallbackChannelNames}from"#runtime/session-callback-route.js";function getFrameworkChannelDefinitions(){let r=ashChannel({auth:[localDev(),vercelOidc()]}),i=[];for(let e of r.routes)isHttpRouteDefinition(e)&&i.push({name:`ash`,method:e.method.toUpperCase(),urlPath:e.path,fetch:async(t,n)=>e.handler(t,n),handler:e.handler,adapter:r.adapter,logicalPath:`framework://channels/${e.path}`,sourceId:`ash:framework:${e.method.toLowerCase()}-${e.path}`,sourceKind:`module`});return i.push(...getConnectionCallbackChannelDefinitions(),...getSessionCallbackChannelDefinitions()),i}function getAllFrameworkChannelNames(){return new Set([`ash`,...getConnectionCallbackChannelNames(),...getSessionCallbackChannelNames()])}export{getAllFrameworkChannelNames,getFrameworkChannelDefinitions};
|