experimental-ash 0.59.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.
Files changed (57) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/docs/public/advanced/auth-and-route-protection.mdx +8 -6
  3. package/dist/docs/public/agent-ts.md +17 -47
  4. package/dist/docs/public/channels/README.md +60 -0
  5. package/dist/docs/public/channels/ash.mdx +103 -0
  6. package/dist/docs/public/channels/custom.mdx +288 -0
  7. package/dist/docs/public/channels/discord.mdx +1 -3
  8. package/dist/docs/public/channels/github.md +1 -1
  9. package/dist/docs/public/channels/meta.json +3 -0
  10. package/dist/docs/public/channels/slack.mdx +29 -1
  11. package/dist/docs/public/channels/teams.mdx +1 -3
  12. package/dist/docs/public/channels/telegram.mdx +1 -3
  13. package/dist/docs/public/channels/twilio.mdx +1 -3
  14. package/dist/docs/public/frontend/nextjs.md +24 -8
  15. package/dist/docs/public/onboarding.md +4 -3
  16. package/dist/docs/public/schedules.mdx +4 -4
  17. package/dist/docs/public/tools.mdx +1 -1
  18. package/dist/src/channel/compiled-channel.d.ts +2 -6
  19. package/dist/src/channel/routes.d.ts +75 -7
  20. package/dist/src/channel/routes.js +1 -1
  21. package/dist/src/compiler/manifest.d.ts +4 -4
  22. package/dist/src/compiler/manifest.js +1 -1
  23. package/dist/src/execution/dispatch-code-mode-runtime-actions-step.d.ts +21 -0
  24. package/dist/src/execution/dispatch-code-mode-runtime-actions-step.js +1 -0
  25. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  26. package/dist/src/execution/next-driver-action.d.ts +5 -0
  27. package/dist/src/execution/node-step.js +1 -1
  28. package/dist/src/execution/turn-workflow.js +1 -1
  29. package/dist/src/execution/workflow-entry.js +1 -1
  30. package/dist/src/execution/workflow-steps.d.ts +5 -0
  31. package/dist/src/execution/workflow-steps.js +1 -1
  32. package/dist/src/harness/code-mode-runtime-action-state.d.ts +6 -0
  33. package/dist/src/harness/code-mode-runtime-action-state.js +1 -0
  34. package/dist/src/harness/code-mode.js +1 -1
  35. package/dist/src/harness/runtime-actions.d.ts +1 -0
  36. package/dist/src/harness/runtime-actions.js +1 -1
  37. package/dist/src/harness/tool-loop.js +1 -1
  38. package/dist/src/internal/application/package.js +1 -1
  39. package/dist/src/internal/nitro/host/channel-routes.d.ts +2 -2
  40. package/dist/src/internal/nitro/host/channel-routes.js +2 -1
  41. package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
  42. package/dist/src/internal/nitro/routes/channel-dispatch.d.ts +2 -0
  43. package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
  44. package/dist/src/internal/vercel-agent-summary.d.ts +2 -2
  45. package/dist/src/internal/vercel-agent-summary.js +1 -1
  46. package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
  47. package/dist/src/public/channels/index.d.ts +1 -1
  48. package/dist/src/public/channels/index.js +1 -1
  49. package/dist/src/public/definitions/channel.d.ts +7 -0
  50. package/dist/src/public/definitions/defineChannel.d.ts +3 -6
  51. package/dist/src/public/definitions/defineChannel.js +1 -1
  52. package/dist/src/runtime/framework-channels/index.js +1 -1
  53. package/dist/src/runtime/resolve-channel.js +1 -1
  54. package/dist/src/runtime/types.d.ts +8 -3
  55. package/package.json +1 -1
  56. package/dist/docs/public/channels/attachments.md +0 -71
  57. package/dist/docs/public/channels/index.md +0 -661
@@ -1,10 +1,8 @@
1
1
  ---
2
- title: "Twilio channel setup"
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
- Skip this section if the framework default channel works for you. `withAsh()`
40
- already wires Ash up without it.
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
- Create `agent/channels/ash.ts` when you want to choose the route auth policy
43
- explicitly:
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 { none } from "experimental-ash/channels/auth";
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: none(),
66
+ auth: [localDev(), vercelOidc(), productionAuth],
52
67
  });
53
68
  ```
54
69
 
55
- For protected apps, replace `none()` with a channel auth helper such as
56
- `vercelOidc()`, `oidc(...)`, or `httpBasic(...)`.
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 (non-interactive)
34
+ ## Step 1 — Scaffold Headlessly
35
35
 
36
- Run the create CLI in headless mode. 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).
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 `--json` / headless flags (an older version), fall back to the interactive wizard `pnpm create experimental-ash-agent` and walk the user through the same decisions above.
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`](./channels/README.md#cross-channel-hand-off). Hands the work off to a channel's authored `receive` hook.
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](./channels/README.md#slack-thread-anchoring) on the first agent post:
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](./channels/README.md) instead.
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](./channels/README.md)
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 { RouteHandler, SendFn } from "#channel/routes.js";
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 RouteDefinition<TState = undefined> {
61
- readonly method: string;
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 declare function GET<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
66
- export declare function POST<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
67
- export declare function PUT<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
68
- export declare function PATCH<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
69
- export declare function DELETE<TState = undefined>(path: string, handler: RouteHandler<TState>): RouteDefinition<TState>;
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 { ChannelMethod } from "#public/definitions/channel.js";
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 = 27;
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: ChannelMethod;
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<27>;
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};
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Dispatches runtime actions originating from code mode.
3
+ *
4
+ * Reads the pending code mode runtime action from session state,
5
+ * builds a runtime action request from the interrupt payload, stores
6
+ * it as a temporary PendingRuntimeActionBatch, and delegates to the
7
+ * standard dispatch step. The batch is only needed for dispatch —
8
+ * the harness never sees it because results flow through
9
+ * continuePendingCodeModeRuntimeAction, not resolvePendingRuntimeActions.
10
+ */
11
+ import type { RuntimeSubagentResultActionResult } from "#runtime/actions/types.js";
12
+ import { type DurableSessionState } from "#execution/durable-session-store.js";
13
+ export declare function dispatchCodeModeRuntimeActionsStep(input: {
14
+ readonly callbackBaseUrl?: string;
15
+ readonly parentWritable: WritableStream<Uint8Array>;
16
+ readonly serializedContext: Record<string, unknown>;
17
+ readonly sessionState: DurableSessionState;
18
+ }): Promise<{
19
+ readonly results: readonly RuntimeSubagentResultActionResult[];
20
+ readonly sessionState: DurableSessionState;
21
+ }>;
@@ -0,0 +1 @@
1
+ import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildRuntimeActionFromInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{setPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";async function dispatchCodeModeRuntimeActionsStep(e){"use step";let t=await readDurableSession(e.sessionState),n=getPendingCodeModeInterrupt(t.state);if(n===void 0)return{results:[],sessionState:e.sessionState};let r=buildRuntimeActionFromInterrupt(n.interrupt),i=(await deserializeContext(e.serializedContext)).require(BundleKey),a=hydrateDurableSession({compactionOverrides:{thresholdPercent:i.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:i.turnAgent}),o=createDurableSessionState({session:setPendingRuntimeActionBatch({actions:[r],event:{sequence:0,stepIndex:0,turnId:`code-mode-dispatch`},responseMessages:[],session:a})});return dispatchRuntimeActionsStep({callbackBaseUrl:e.callbackBaseUrl,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:o})}export{dispatchCodeModeRuntimeActionsStep};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{toErrorMessage}from"#shared/errors.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),l=getPendingRuntimeActionBatch(s.state);if(l===void 0||l.actions.length===0)return{results:[],sessionState:e.sessionState};let u=await deserializeContext(e.serializedContext),d=u.require(BundleKey),f=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:d.turnAgent}),p=u.require(ChannelKey),m=u.get(AuthKey)??null,h=u.get(CapabilitiesKey),g=u.get(ChannelInstrumentationKey),_=u.get(InitiatorAuthKey)??null,v=e.parentWritable.getWriter(),y=buildAdapterContext(p,u),b=f,x=[];try{for(let r of l.actions){let i,a,o,s;switch(r.kind){case`subagent-call`:{let e=createWorkflowRuntime({compiledArtifactsSource:d.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:t,runInput:n}=buildSubagentRunInput({action:r,auth:m,batchEvent:l.event,capabilities:h,channelMetadata:g,initiatorAuth:_,session:f}),o=await e.run(n);b=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:t,session:b}),i=o.sessionId,a=r.name,s=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:d.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,remote:n,session:f})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),x.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},s=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let c=await callAdapterEventHandler(p,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:l.event.sequence,sessionId:f.sessionId,toolName:s,turnId:l.event.turnId,workflowId:workflowEntryReference.workflowId}),y);await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(c)))}}finally{v.releaseLock()}return{results:x,sessionState:b===f?e.sessionState:createDurableSessionState({session:b})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
1
+ import{createLogger,logError}from"#internal/logging.js";import{callAdapterEventHandler}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,InitiatorAuthKey}from"#context/keys.js";import{createSubagentCalledEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{toErrorMessage}from"#shared/errors.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession}from"#execution/session.js";import{deserializeContext}from"#context/serialize.js";import{getPendingRuntimeActionBatch,recordPendingSubagentChildToken}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{resolveRemoteAgentForAction,startRemoteAgentSession}from"#execution/remote-agent-dispatch.js";import{buildSubagentRunInput}from"#execution/subagent-tool.js";import{createWorkflowRuntime,workflowEntryReference}from"#execution/workflow-runtime.js";const log=createLogger(`execution.dispatch-runtime-actions`);async function dispatchRuntimeActionsStep(e){"use step";let s=await readDurableSession(e.sessionState),l=getPendingRuntimeActionBatch(s.state);if(l===void 0||l.actions.length===0)return{results:[],sessionState:e.sessionState};let u=await deserializeContext(e.serializedContext),d=u.require(BundleKey),f=hydrateDurableSession({compactionOverrides:{thresholdPercent:d.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:d.turnAgent}),p=u.require(ChannelKey),m=u.get(AuthKey)??null,h=u.get(CapabilitiesKey),g=u.get(ChannelInstrumentationKey),_=u.get(InitiatorAuthKey)??null,v=e.parentWritable.getWriter(),y=buildAdapterContext(p,u),b=f,x=[];try{for(let r of l.actions){let i,a,o,s;switch(r.kind){case`subagent-call`:{let e=createWorkflowRuntime({compiledArtifactsSource:d.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:t,runInput:n}=buildSubagentRunInput({action:r,auth:m,batchEvent:l.event,capabilities:h,channelMetadata:g,initiatorAuth:_,session:f}),o=await e.run(n);b=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:t,session:b}),i=o.sessionId,a=r.name,s=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:d.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,remote:n,session:f})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:r.remoteAgentName,nodeId:r.nodeId,callId:r.callId}),x.push(createRemoteAgentStartFailureResult({action:r,error:e}));continue}a=r.name,o={url:n.url},s=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let c=await callAdapterEventHandler(p,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:o,sequence:l.event.sequence,sessionId:f.sessionId,toolName:s,turnId:l.event.turnId,workflowId:workflowEntryReference.workflowId}),y);await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(c)))}}finally{v.releaseLock()}return{results:x,sessionState:b===f?e.sessionState:createDurableSessionState({session:b})}}function createRemoteAgentStartFailureResult(e){return{callId:e.action.callId,isError:!0,kind:`subagent-result`,output:{code:`REMOTE_AGENT_START_FAILED`,message:toErrorMessage(e.error)},subagentName:e.action.remoteAgentName}}export{dispatchRuntimeActionsStep};
@@ -29,4 +29,9 @@ export type NextDriverAction = {
29
29
  readonly pendingActionKeys: readonly string[];
30
30
  readonly sessionState: DurableSessionState;
31
31
  readonly serializedContext: Record<string, unknown>;
32
+ } | {
33
+ readonly kind: "dispatch-code-mode-runtime-actions";
34
+ readonly pendingActionKeys: readonly string[];
35
+ readonly sessionState: DurableSessionState;
36
+ readonly serializedContext: Record<string, unknown>;
32
37
  };
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{jsonSchema}from"ai";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{createToolCompactionHandler}from"#execution/tool-compaction.js";import{buildUnauthorizedToolContext,createAuthorizedToolExecute}from"#execution/tool-auth.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.compiledArtifactsSource),n=createNodeHarnessTools({node:e.node}),a=createToolCompactionHandler(collectResolvedTools(e.node));return createToolLoopHarness({capabilities:e.capabilities,codeMode:resolveCodeModeEnabled(e.node.agent.config?.experimental?.codeMode),handleEvent:e.handleEvent,mode:e.mode,onCompaction:a,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:n})}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,ashVersion:t.version,modelId:e.turnAgent.model.id},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,{compiledArtifactsSource:e})}function collectResolvedTools(e){return[...e.toolRegistry.toolsByName.values()].map(e=>e.definition)}function createNodeHarnessTools(e){let n=new Map;for(let t of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:t});r!==null&&n.set(t.name,r)}return n.has(`agent`)||n.set(`agent`,{description:`Run a copy of this agent as a subagent with a focused task. The child agent has the same tools and instructions but a fresh conversation history.`,inputSchema:jsonSchema(SUBAGENT_TOOL_INPUT_SCHEMA),name:`agent`,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:`agent`}}),n}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`subagent-call`,nodeId:e.tool.nodeId,subagentName:e.tool.name}};if(e.tool.kind===`remote`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`remote-agent-call`,nodeId:e.tool.nodeId,remoteAgentName:e.tool.name,subagentName:e.tool.name}};let n=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(n===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=n.definition,i=r.sourceId.startsWith(`ash:`),a=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({auth:r.auth,isFrameworkTool:i,rawExecute:a,scope:r.name}),inputSchema:r.inputStandardSchema??jsonSchema(r.inputSchema??{}),name:r.name,needsApproval:r.needsApproval,outputSchema:r.outputStandardSchema??maybeJsonSchema(r.outputSchema),toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{auth:t,isFrameworkTool:n,rawExecute:r,scope:i}=e;if(r===void 0)return;if(n)return r;let a=r;return t===void 0?e=>a(e,buildUnauthorizedToolContext(i)):createAuthorizedToolExecute({auth:t,execute:a,scope:i})}function maybeJsonSchema(e){return e===void 0?void 0:jsonSchema(e)}export{createExecutionNodeStep,createNodeHarnessTools};
1
+ import{createLogger}from"#internal/logging.js";import{jsonSchema}from"ai";import{resolveInstalledPackageInfo}from"#internal/application/package.js";import{createToolLoopHarness}from"#harness/tool-loop.js";import{resolveCodeModeEnabled}from"#shared/code-mode.js";import{resolveRuntimeModelReference}from"#runtime/agent/resolve-model.js";import{findRegisteredRuntimeTool}from"#runtime/tools/registry.js";import{SUBAGENT_TOOL_INPUT_SCHEMA}from"#runtime/subagents/registry.js";import{createToolCompactionHandler}from"#execution/tool-compaction.js";import{buildUnauthorizedToolContext,createAuthorizedToolExecute}from"#execution/tool-auth.js";const log=createLogger(`execution.node-step`);function createExecutionNodeStep(e){let t=createRuntimeModelResolver(e.compiledArtifactsSource),n=createNodeHarnessTools({node:e.node}),a=createToolCompactionHandler(collectResolvedTools(e.node));return createToolLoopHarness({capabilities:e.capabilities,codeMode:resolveCodeModeEnabled(e.node.agent.config?.experimental?.codeMode),handleEvent:e.handleEvent,mode:e.mode,onCompaction:a,resolveModel:t,runtimeIdentity:buildRuntimeIdentity(e.node),tools:n})}function buildRuntimeIdentity(e){let t=resolveInstalledPackageInfo(),r={agentId:e.turnAgent.id,agentName:e.agent.config?.name,ashVersion:t.version,modelId:e.turnAgent.model.id},i=process.env.VERCEL_GIT_COMMIT_SHA?.trim(),a=process.env.VERCEL_GIT_COMMIT_REF?.trim(),o=process.env.VERCEL_DEPLOYMENT_CREATED_AT?.trim();return i||a||o?{...r,build:{deployedAt:o||void 0,gitBranch:a||void 0,gitSha:i||void 0}}:r}function createRuntimeModelResolver(e){return t=>resolveRuntimeModelReference(t,{compiledArtifactsSource:e})}function collectResolvedTools(e){return[...e.toolRegistry.toolsByName.values()].map(e=>e.definition)}function createNodeHarnessTools(e){let n=new Map;for(let t of e.node.turnAgent.tools){let r=resolveHarnessToolDefinition({node:e.node,tool:t});r!==null&&n.set(t.name,r)}return n.has(`agent`)||n.set(`agent`,{description:`Launch a new agent to handle a complex, multi-step subtask.`,inputSchema:jsonSchema(SUBAGENT_TOOL_INPUT_SCHEMA),name:`agent`,runtimeAction:{kind:`subagent-call`,nodeId:e.node.nodeId,subagentName:`agent`}}),n}function resolveHarnessToolDefinition(e){if(e.tool.kind===`subagent`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`subagent-call`,nodeId:e.tool.nodeId,subagentName:e.tool.name}};if(e.tool.kind===`remote`)return{description:e.tool.description??``,inputSchema:jsonSchema(e.tool.inputSchema??{}),name:e.tool.name,outputSchema:e.tool.outputSchema===void 0?void 0:jsonSchema(e.tool.outputSchema),runtimeAction:{kind:`remote-agent-call`,nodeId:e.tool.nodeId,remoteAgentName:e.tool.name,subagentName:e.tool.name}};let n=findRegisteredRuntimeTool(e.node.toolRegistry,e.tool.name);if(n===null)return log.warn(`declared tool is not registered — omitting from toolset`,{toolName:e.tool.name,nodeId:e.node.nodeId}),null;let r=n.definition,i=r.sourceId.startsWith(`ash:`),a=r.execute;return{approvalKey:r.approvalKey,description:r.description,execute:resolveAuthoredExecute({auth:r.auth,isFrameworkTool:i,rawExecute:a,scope:r.name}),inputSchema:r.inputStandardSchema??jsonSchema(r.inputSchema??{}),name:r.name,needsApproval:r.needsApproval,outputSchema:r.outputStandardSchema??maybeJsonSchema(r.outputSchema),toModelOutput:r.toModelOutput}}function resolveAuthoredExecute(e){let{auth:t,isFrameworkTool:n,rawExecute:r,scope:i}=e;if(r===void 0)return;if(n)return r;let a=r;return t===void 0?e=>a(e,buildUnauthorizedToolContext(i)):createAuthorizedToolExecute({auth:t,execute:a,scope:i})}function maybeJsonSchema(e){return e===void 0?void 0:jsonSchema(e)}export{createExecutionNodeStep,createNodeHarnessTools};
@@ -1 +1 @@
1
- import{normalizeSerializableError}from"#execution/workflow-errors.js";import{turnStep}from"#execution/workflow-steps.js";async function turnWorkflow(n){"use workflow";let r=n.sessionState,i=n.serializedContext,a=n.delivery,o=n.parentWritable;try{for(;;){let e=await turnStep({input:a,parentWritable:o,serializedContext:i,sessionState:r});if(r=e.sessionState,i=e.serializedContext,e.action===`done`){await notifyDriverStep({completionToken:n.completionToken,payload:{action:{kind:`done`,output:e.output??``,isError:e.isError,serializedContext:i,sessionState:r},kind:`turn-result`}});return}if(e.action===`park`){let t=e.pendingRuntimeActionKeys;if(!(t!==void 0||e.hasPendingAuthorization||e.hasPendingInputBatch&&n.capabilities?.requestInput===!0||n.mode===`conversation`))throw Error("Task mode cannot wait for follow-up input (`next: null`).");let a=t===void 0?{kind:`park`,serializedContext:i,sessionState:r,authorizationNames:e.authorizationNames}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:i,sessionState:r};await notifyDriverStep({completionToken:n.completionToken,payload:{action:a,kind:`turn-result`}});return}a=void 0}}catch(t){throw await notifyDriverStep({completionToken:n.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}async function notifyDriverStep(e){"use step";let{resumeHook:t}=await import(`#compiled/@workflow/core/runtime.js`);await t(e.completionToken,e.payload)}export{notifyDriverStep,turnWorkflow};
1
+ import{normalizeSerializableError}from"#execution/workflow-errors.js";import{turnStep}from"#execution/workflow-steps.js";async function turnWorkflow(n){"use workflow";let r=n.sessionState,i=n.serializedContext,a=n.delivery,o=n.parentWritable;try{for(;;){let e=await turnStep({input:a,parentWritable:o,serializedContext:i,sessionState:r});if(r=e.sessionState,i=e.serializedContext,e.action===`done`){await notifyDriverStep({completionToken:n.completionToken,payload:{action:{kind:`done`,output:e.output??``,isError:e.isError,serializedContext:i,sessionState:r},kind:`turn-result`}});return}if(e.action===`dispatch-code-mode-runtime-actions`){await notifyDriverStep({completionToken:n.completionToken,payload:{action:{kind:`dispatch-code-mode-runtime-actions`,pendingActionKeys:e.pendingRuntimeActionKeys,serializedContext:i,sessionState:r},kind:`turn-result`}});return}if(e.action===`park`){let t=e.pendingRuntimeActionKeys;if(!(t!==void 0||e.hasPendingAuthorization||e.hasPendingInputBatch&&n.capabilities?.requestInput===!0||n.mode===`conversation`))throw Error("Task mode cannot wait for follow-up input (`next: null`).");let a=t===void 0?{kind:`park`,serializedContext:i,sessionState:r,authorizationNames:e.authorizationNames}:{kind:`dispatch-runtime-actions`,pendingActionKeys:t,serializedContext:i,sessionState:r};await notifyDriverStep({completionToken:n.completionToken,payload:{action:a,kind:`turn-result`}});return}a=void 0}}catch(t){throw await notifyDriverStep({completionToken:n.completionToken,payload:{error:normalizeSerializableError(t),kind:`turn-error`}}),t}}async function notifyDriverStep(e){"use step";let{resumeHook:t}=await import(`#compiled/@workflow/core/runtime.js`);await t(e.completionToken,e.payload)}export{notifyDriverStep,turnWorkflow};
@@ -1 +1 @@
1
- import{readRootSessionId}from"#execution/ash-workflow-attributes.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),i=t.serializedContext[`ash.continuationToken`]||``,a=t.serializedContext[`ash.mode`],s=t.serializedContext[`ash.capabilities`],c=t.serializedContext[`ash.bundle`];t.serializedContext[`ash.sessionId`]=n;let l=getWritable();try{let r=readRootSessionId(t.serializedContext),{state:o}=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:i,inputMessage:t.input.message,nodeId:c.nodeId,outputSchema:t.input.outputSchema,rootSessionId:r,serializedContext:t.serializedContext,sessionId:n});return await runDriverLoop({capabilities:s,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,context:t.input.context,outputSchema:t.input.outputSchema}]},mode:a,serializedContext:t.serializedContext,sessionState:o})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),r=t[Symbol.asyncIterator](),i=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(i++)}`,a=e.sessionState.continuationToken,o=createHook({token:a}),s=o[Symbol.asyncIterator](),c=null,u=[],getNextPromise=()=>(c??=s.next(),c),consumeNext=()=>{c=null},rekeyHook=async e=>{e===a||!e||(await closeHookIterator(s),await disposeHook(o),a=e,o=createHook({token:a}),s=o[Symbol.asyncIterator](),c=null)},d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});if(d.kind===`done`)return await closeHookIterator(r),await disposeHook(t),await closeHookIterator(s),await disposeHook(o),await finalizeDone({action:d,driverWritable:e.driverWritable});if(!d.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");await rekeyHook(d.sessionState.continuationToken);try{for(;;)switch(d.kind){case`done`:return await finalizeDone({action:d,driverWritable:e.driverWritable});case`dispatch-runtime-actions`:{let t=await dispatchRuntimeActionsStep({callbackBaseUrl:resolveVercelProductionCallbackBaseUrl()??getWorkflowMetadata().url,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),r=await waitForPendingRuntimeActionResults({bufferedDeliveries:u,consumeNext,getNextPromise,initialResults:t.results,parentWritable:e.driverWritable,pendingActionKeys:d.pendingActionKeys,rekeyHook,serializedContext:d.serializedContext,sessionState:t.sessionState});if(r===null)return{output:``};d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`runtime-action-result`,results:r.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:r.serializedContext,sessionState:r.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}case`park`:{if(d.authorizationNames&&d.authorizationNames.length>0){let t=d.authorizationNames.length,n=[];for(;n.length<t;){let e=await r.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`deliver`,payloads:n},mode:e.mode,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}let t=await waitForNextDeliver({bufferedDeliveries:u,consumeNext,getNextPromise});if(t===null)return{output:``};let n=await routeDeliverForChildren({auth:t.auth,parentWritable:e.driverWritable,payloads:t.payloads,sessionState:d.sessionState});if(n===void 0)continue;d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{auth:t.auth,kind:`deliver`,payloads:[n]},mode:e.mode,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}}}finally{await closeHookIterator(s),await disposeHook(o),await closeHookIterator(r),await disposeHook(t)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function dispatchAndAwaitTurn(e){let t=createHook({token:e.completionToken}),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(e){let n=e.sessionState,r=e.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:e.bufferedDeliveries,async getNext(){for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;let i=t.value;if(i.kind===`deliver`){let t=await routeDeliverForChildren({auth:i.auth,parentWritable:e.parentWritable,payloads:i.payloads,sessionState:n});if(t===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[t]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:e.parentWritable,serializedContext:r,sessionState:n});n=a.sessionState,r=a.serializedContext,await e.rekeyHook(n.continuationToken)}},initialResults:e.initialResults,pendingActionKeys:e.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}async function closeHookIterator(e){typeof e.return==`function`&&await e.return(void 0)}async function disposeHook(e){let t=e.dispose;if(typeof t==`function`){await t.call(e);return}let n=e[Symbol.dispose];typeof n==`function`&&await n.call(e)}export{workflowEntry};
1
+ import{readRootSessionId}from"#execution/ash-workflow-attributes.js";import{accumulateRuntimeActionResults}from"#harness/runtime-actions.js";import{dispatchRuntimeActionsStep}from"#execution/dispatch-runtime-actions-step.js";import{resolveVercelProductionCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{normalizeSerializableError,rebuildSerializableError}from"#execution/workflow-errors.js";import{dispatchTurnStep,emitTerminalSessionFailureStep,routeProxiedDeliverStep,runProxyInputRequestStep}from"#execution/workflow-steps.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{coalesceDeliveries}from"#harness/messages.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{createSessionStep}from"#execution/create-session-step.js";import{dispatchCodeModeRuntimeActionsStep}from"#execution/dispatch-code-mode-runtime-actions-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";async function workflowEntry(t){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),r=t.serializedContext[`ash.continuationToken`]||``,a=t.serializedContext[`ash.mode`],o=t.serializedContext[`ash.capabilities`],c=t.serializedContext[`ash.bundle`];t.serializedContext[`ash.sessionId`]=n;let l=getWritable();try{let i=readRootSessionId(t.serializedContext),{state:s}=await createSessionStep({compiledArtifactsSource:c.source,continuationToken:r,inputMessage:t.input.message,nodeId:c.nodeId,outputSchema:t.input.outputSchema,rootSessionId:i,serializedContext:t.serializedContext,sessionId:n});return await runDriverLoop({capabilities:o,driverWritable:l,initialInput:{kind:`deliver`,payloads:[{message:t.input.message,context:t.input.context,outputSchema:t.input.outputSchema}]},mode:a,serializedContext:t.serializedContext,sessionState:s})}catch(e){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(e),parentWritable:l,serializedContext:t.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(e),serializedContext:t.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(t.serializedContext,e),serializedContext:t.serializedContext}),e}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),i=t[Symbol.asyncIterator](),a=0,nextTurnCompletionToken=()=>`${e.sessionState.sessionId}:turn-completion:${String(a++)}`,o=e.sessionState.continuationToken,s=createHook({token:o}),c=s[Symbol.asyncIterator](),l=null,u=[],getNextPromise=()=>(l??=c.next(),l),consumeNext=()=>{l=null},rekeyHook=async e=>{e===o||!e||(await closeHookIterator(c),await disposeHook(s),o=e,s=createHook({token:o}),c=s[Symbol.asyncIterator](),l=null)},d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:e.initialInput,mode:e.mode,parentWritable:e.driverWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});if(d.kind===`done`)return await closeHookIterator(i),await disposeHook(t),await closeHookIterator(c),await disposeHook(s),await finalizeDone({action:d,driverWritable:e.driverWritable});if(!d.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");await rekeyHook(d.sessionState.continuationToken);try{for(;;)switch(d.kind){case`done`:return await finalizeDone({action:d,driverWritable:e.driverWritable});case`dispatch-code-mode-runtime-actions`:case`dispatch-runtime-actions`:{let t=await(d.kind===`dispatch-code-mode-runtime-actions`?dispatchCodeModeRuntimeActionsStep:dispatchRuntimeActionsStep)({callbackBaseUrl:resolveVercelProductionCallbackBaseUrl()??getWorkflowMetadata().url,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),i=await waitForPendingRuntimeActionResults({bufferedDeliveries:u,consumeNext,getNextPromise,initialResults:t.results,parentWritable:e.driverWritable,pendingActionKeys:d.pendingActionKeys,rekeyHook,serializedContext:d.serializedContext,sessionState:t.sessionState});if(i===null)return{output:``};d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`runtime-action-result`,results:i.results},mode:e.mode,parentWritable:e.driverWritable,serializedContext:i.serializedContext,sessionState:i.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}case`park`:{if(d.authorizationNames&&d.authorizationNames.length>0){let t=d.authorizationNames.length,n=[];for(;n.length<t;){let e=await i.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{kind:`deliver`,payloads:n},mode:e.mode,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}let t=await waitForNextDeliver({bufferedDeliveries:u,consumeNext,getNextPromise});if(t===null)return{output:``};let n=await routeDeliverForChildren({auth:t.auth,parentWritable:e.driverWritable,payloads:t.payloads,sessionState:d.sessionState});if(n===void 0)continue;d=await dispatchAndAwaitTurn({capabilities:e.capabilities,completionToken:nextTurnCompletionToken(),delivery:{auth:t.auth,kind:`deliver`,payloads:[n]},mode:e.mode,parentWritable:e.driverWritable,serializedContext:d.serializedContext,sessionState:d.sessionState}),await rekeyHook(d.sessionState.continuationToken);break}}}finally{await closeHookIterator(c),await disposeHook(s),await closeHookIterator(i),await disposeHook(t)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n}),{output:t}}async function dispatchAndAwaitTurn(e){let t=createHook({token:e.completionToken}),n=t.token;try{await dispatchTurnStep({capabilities:e.capabilities,completionToken:n,delivery:e.delivery,mode:e.mode,parentWritable:e.parentWritable,serializedContext:e.serializedContext,sessionState:e.sessionState});let r=await awaitHookPayload(t);if(r.kind===`turn-error`)throw rebuildSerializableError(r.error);return r.action}finally{await disposeHook(t)}}async function awaitHookPayload(e){for await(let t of e)return t;throw Error(`Turn completion hook closed before delivering a result.`)}async function waitForPendingRuntimeActionResults(e){let n=e.sessionState,r=e.serializedContext,i=await accumulateRuntimeActionResults({bufferedDeliveries:e.bufferedDeliveries,async getNext(){for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;let i=t.value;if(i.kind===`deliver`){let t=await routeDeliverForChildren({auth:i.auth,parentWritable:e.parentWritable,payloads:i.payloads,sessionState:n});if(t===void 0)continue;return{kind:`deliver`,value:{...i,payloads:[t]}}}if(i.kind===`runtime-action-result`)return{kind:`runtime-action-result`,results:i.results};let a=await runProxyInputRequestStep({hookPayload:i,parentWritable:e.parentWritable,serializedContext:r,sessionState:n});n=a.sessionState,r=a.serializedContext,await e.rekeyHook(n.continuationToken)}},initialResults:e.initialResults,pendingActionKeys:e.pendingActionKeys});return i===null?null:{results:i,serializedContext:r,sessionState:n}}async function routeDeliverForChildren(e){let t=coalescePayloads(e.payloads);return e.sessionState.hasProxyInputRequests?(await routeProxiedDeliverStep({auth:e.auth,parentWritable:e.parentWritable,payload:t,sessionState:e.sessionState})).remainder:t}async function waitForNextDeliver(e){if(e.bufferedDeliveries.length>0)return coalesceDeliveries(e.bufferedDeliveries.splice(0));for(;;){let t=await e.getNextPromise();if(e.consumeNext(),t.done)return null;if(t.value.kind!==`deliver`)continue;let n=t.value;for(;;){let t=await takeReadyPayload(e.getNextPromise());if(t===NO_READY_MESSAGE||(e.consumeNext(),t.done))break;t.value.kind===`deliver`&&(n=coalesceDeliveries([n,t.value]))}return n}}function coalescePayloads(e){if(e.length===0)return{};if(e.length===1)return e[0]??{};let t={},n=[];for(let r of e){for(let[e,n]of Object.entries(r))e!==`inputResponses`&&n!==void 0&&(t[e]=n);r.inputResponses!==void 0&&n.push(...r.inputResponses)}return n.length>0&&(t.inputResponses=n),t}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}async function closeHookIterator(e){typeof e.return==`function`&&await e.return(void 0)}async function disposeHook(e){let t=e.dispose;if(typeof t==`function`){await t.call(e);return}let n=e[Symbol.dispose];typeof n==`function`&&await n.call(e)}export{workflowEntry};
@@ -27,6 +27,11 @@ export type DurableStepResult = {
27
27
  readonly pendingRuntimeActionKeys?: readonly string[];
28
28
  readonly serializedContext: Record<string, unknown>;
29
29
  readonly sessionState: DurableSessionState;
30
+ } | {
31
+ readonly action: "dispatch-code-mode-runtime-actions";
32
+ readonly pendingRuntimeActionKeys: readonly string[];
33
+ readonly serializedContext: Record<string, unknown>;
34
+ readonly sessionState: DurableSessionState;
30
35
  };
31
36
  /** Input for one atomic harness step inside a durable `"use step"`. */
32
37
  export interface TurnStepInput {
@@ -1 +1 @@
1
- import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{buildTurnAttributes,readRootSessionId}from"#execution/ash-workflow-attributes.js";import{setAshAttributes}from"#runtime/attributes/emit.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{getHarnessEmissionState}from"#harness/emission.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";await setAshAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}));let t=await readDurableSession(e.sessionState),o=await deserializeContext(e.serializedContext),l=o.require(ChannelKey),f=o.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:f.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(t.state),h;if(m&&e.input?.kind===`deliver`){let t=[],n=[];for(let r of e.input.payloads){let e=r.authorizationCallback;if(e){let n=m.challenges.find(t=>t.name===e.connectionName);n&&t.push({name:n.name,state:n.state,callback:e.request,hookUrl:n.hookUrl})}else n.push(r)}t.length>0&&(o.set(PendingAuthorizationResultKey,t),h=t.map(e=>e.name),e=n.length>0?{...e,input:{...e.input,payloads:n}}:{...e,input:void 0})}e.input?.kind===`deliver`&&e.input.auth!==void 0&&o.set(AuthKey,e.input.auth??null);let g=buildAdapterContext(l,o),_;if(e.input?.kind===`deliver`){let t=[];for(let n of e.input.payloads){let e=l.deliver?await l.deliver(n,g):defaultDeliverResult(n);e!=null&&t.push(e)}_=t.length===0?void 0:t.reduce(coalesceTurnInputs)}else e.input?.kind===`runtime-action-result`&&(_={runtimeActionResults:e.input.results});if(e.input?.kind===`deliver`&&setChannelContext(o,{...l,state:{...g.state}}),e.input?.kind===`deliver`&&_===void 0){let t=reconcileSessionContinuationToken(o,p),n=serializeContext(o),r=t===p?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let v=e.parentWritable.getWriter(),y=f.hookRegistry,b=f.resolvedAgent.dynamicInstructionsResolvers??[],x=f.resolvedAgent.dynamicSkillResolvers??[],S=f.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(l,e,g);return setChannelContext(o,{...l,state:{...g.state}}),await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:o,registry:y,event:n}),await dispatchDynamicToolEvent({ctx:o,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:o,resolvers:x,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:o,resolvers:b,event:n,messages:t??[]})},C=o.require(ModeKey),w=await runStep(o,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:_,mode:C,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let t of h)await handleEvent(createAuthorizationCompletedEvent({name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=o.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},refreshSystemPrompt:shouldRefreshSystemPromptFromTurnAgent(f.compiledArtifactsSource),session:e,turnAgent:f.turnAgent});return createExecutionNodeStep({capabilities:n,compiledArtifactsSource:f.compiledArtifactsSource,createRuntime:createWorkflowRuntime,handleEvent,mode:C,node:f.graph.root})(r,t)})(t,_)}),T=reconcileSessionContinuationToken(o,w.session),E=serializeContext(o);w={...w,session:T};let D=createDurableSessionState({session:w.session});return w.next!==null&&typeof w.next==`object`&&`done`in w.next?(await v.close(),{action:`done`,output:w.next.output,isError:w.next.isError,serializedContext:E,sessionState:D}):w.next===null?(v.releaseLock(),{action:`park`,...derivePendingState(w.session),serializedContext:E,sessionState:D}):(v.releaseLock(),{action:`continue`,serializedContext:E,sessionState:D})}function shouldRefreshSystemPromptFromTurnAgent(e){return e.kind===`disk`&&e.moduleMapLoaderPath!==void 0}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`ash.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state}),{resumeHook:r}=await import(`#compiled/@workflow/core/runtime.js`);for(let t of n.forChildren)await r(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[e])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
1
+ import{createLogger,formatError}from"#internal/logging.js";import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ContinuationTokenKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,createSessionFailedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{buildTurnAttributes,readRootSessionId}from"#execution/ash-workflow-attributes.js";import{setAshAttributes}from"#runtime/attributes/emit.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt}from"#harness/code-mode-runtime-action-state.js";import{getPendingCodeModeInterrupt}from"#harness/code-mode-interrupt-state.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{createWorkflowRuntime,startWorkflowPreferLatest}from"#execution/workflow-runtime.js";import{getHarnessEmissionState}from"#harness/emission.js";import{upsertProxyInputRequests}from"#harness/proxy-input-requests.js";import{setChannelContext}from"#execution/channel-context.js";import{coalesceTurnInputs}from"#harness/messages.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{runStep,withContextScope}from"#context/run-step.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,getPendingAuthorization}from"#harness/authorization.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{emitProxiedInputRequest,routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{turnWorkflow}from"#execution/turn-workflow.js";async function turnStep(e){"use step";await setAshAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}));let t=await readDurableSession(e.sessionState),o=await deserializeContext(e.serializedContext),l=o.require(ChannelKey),f=o.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:f.turnAgent});try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&o.set(CallbackBaseUrlKey,t.url.replace(/\/$/,``))}catch{}let m=getPendingAuthorization(t.state),h;if(m&&e.input?.kind===`deliver`){let t=[],n=[];for(let r of e.input.payloads){let e=r.authorizationCallback;if(e){let n=m.challenges.find(t=>t.name===e.connectionName);n&&t.push({name:n.name,state:n.state,callback:e.request,hookUrl:n.hookUrl})}else n.push(r)}t.length>0&&(o.set(PendingAuthorizationResultKey,t),h=t.map(e=>e.name),e=n.length>0?{...e,input:{...e.input,payloads:n}}:{...e,input:void 0})}e.input?.kind===`deliver`&&e.input.auth!==void 0&&o.set(AuthKey,e.input.auth??null);let g=buildAdapterContext(l,o),_;if(e.input?.kind===`deliver`){let t=[];for(let n of e.input.payloads){let e=l.deliver?await l.deliver(n,g):defaultDeliverResult(n);e!=null&&t.push(e)}_=t.length===0?void 0:t.reduce(coalesceTurnInputs)}else e.input?.kind===`runtime-action-result`&&(_={runtimeActionResults:e.input.results});if(e.input?.kind===`deliver`&&setChannelContext(o,{...l,state:{...g.state}}),e.input?.kind===`deliver`&&_===void 0){let t=reconcileSessionContinuationToken(o,p),n=serializeContext(o),r=t===p?e.sessionState:createDurableSessionState({session:t});return{action:`park`,...derivePendingState(t),serializedContext:n,sessionState:r}}let v=e.parentWritable.getWriter(),y=f.hookRegistry,b=f.resolvedAgent.dynamicInstructionsResolvers??[],x=f.resolvedAgent.dynamicSkillResolvers??[],S=f.resolvedAgent.dynamicToolResolvers??[],emit=async e=>{let t=await callAdapterEventHandler(l,e,g);return setChannelContext(o,{...l,state:{...g.state}}),await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t))),t},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:o,registry:y,event:n}),await dispatchDynamicToolEvent({ctx:o,resolvers:S,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:o,resolvers:x,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:o,resolvers:b,event:n,messages:t??[]})},C=o.require(ModeKey),w=await runStep(o,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:f.turnAgent.outputSchema,input:_,mode:C,session:e});if(h){let e=getHarnessEmissionState(t.state);for(let t of h)await handleEvent(createAuthorizationCompletedEvent({name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=o.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},refreshSystemPrompt:shouldRefreshSystemPromptFromTurnAgent(f.compiledArtifactsSource),session:e,turnAgent:f.turnAgent});return createExecutionNodeStep({capabilities:n,compiledArtifactsSource:f.compiledArtifactsSource,createRuntime:createWorkflowRuntime,handleEvent,mode:C,node:f.graph.root})(r,t)})(t,_)}),T=reconcileSessionContinuationToken(o,w.session),E=serializeContext(o);w={...w,session:T};let D=createDurableSessionState({session:w.session});if(w.next!==null&&typeof w.next==`object`&&`done`in w.next)return await v.close(),{action:`done`,output:w.next.output,isError:w.next.isError,serializedContext:E,sessionState:D};if(w.next===null){v.releaseLock();let e=getPendingCodeModeInterrupt(w.session.state);return e!==void 0&&isCodeModeRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-code-mode-runtime-actions`,pendingRuntimeActionKeys:[getRuntimeActionKeyFromInterrupt(e.interrupt)],serializedContext:E,sessionState:D}:{action:`park`,...derivePendingState(w.session),serializedContext:E,sessionState:D}}return v.releaseLock(),{action:`continue`,serializedContext:E,sessionState:D}}function shouldRefreshSystemPromptFromTurnAgent(e){return e.kind===`disk`&&e.moduleMapLoaderPath!==void 0}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function reconcileSessionContinuationToken(e,t){let n=e.get(ContinuationTokenKey);return n===void 0||n===t.continuationToken?t:{...t,continuationToken:n}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}const log=createLogger(`execution.workflow-entry`);async function emitTerminalSessionFailureStep(e){"use step";let r=formatError(e.error),i=typeof r.name==`string`?r.name:`WORKFLOW_EXECUTION_FAILED`,a=typeof r.message==`string`?r.message:String(e.error),o=e.serializedContext[`ash.sessionId`]??``;log.error(`workflow loop threw — emitting terminal session.failed`,{sessionId:o,errorId:typeof r.errorId==`string`?r.errorId:void 0,code:i,message:a,detail:typeof r.detail==`string`?r.detail:void 0});let s=createSessionFailedEvent({code:i,details:r,message:a,sessionId:o});try{let t=await deserializeContext(e.serializedContext),r=t.get(ChannelKey);r!==void 0&&await callAdapterEventHandler(r,s,buildAdapterContext(r,t))}catch(e){log.error(`adapter failed to handle terminal session.failed event`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}try{let t=e.parentWritable.getWriter();try{await t.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(s)))}finally{t.releaseLock()}}catch(e){log.error(`failed to write terminal session.failed event to durable stream`,{errorId:typeof r.errorId==`string`?r.errorId:void 0,sessionId:o,error:e})}}async function runProxyInputRequestStep(e){"use step";let t=await readDurableSession(e.sessionState),r=await deserializeContext(e.serializedContext),i=r.require(ChannelKey),a=buildAdapterContext(i,r),o=r.require(ModeKey),c=r.require(BundleKey),l=hydrateDurableSession({compactionOverrides:{thresholdPercent:c.resolvedAgent.config.compaction?.thresholdPercent},durable:t,turnAgent:c.turnAgent}),u=e.parentWritable.getWriter(),d;try{let emit=async e=>{let t=await callAdapterEventHandler(i,e,a);await u.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(t)))};d=await withContextScope(r,l,async t=>{let n=await emitProxiedInputRequest({emit,hookPayload:e.hookPayload,mode:o,session:t});return{result:n.entries,session:n.session}})}finally{u.releaseLock()}return setChannelContext(r,{...i,state:{...a.state}}),{serializedContext:serializeContext(r),sessionState:createDurableSessionState({session:reconcileSessionContinuationToken(r,upsertProxyInputRequests({entries:d.result,forChildContinuationToken:e.hookPayload.childContinuationToken,session:d.session}))})}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state}),{resumeHook:r}=await import(`#compiled/@workflow/core/runtime.js`);for(let t of n.forChildren)await r(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflow,[e])).runId}}export{dispatchTurnStep,emitTerminalSessionFailureStep,reconcileSessionContinuationToken,resolveEffectiveOutputSchema,routeProxiedDeliverStep,runProxyInputRequestStep,turnStep};
@@ -0,0 +1,6 @@
1
+ import type { RuntimeActionRequest } from "#runtime/actions/types.js";
2
+ import type { CodeModeInterrupt } from "#shared/code-mode.js";
3
+ export declare const CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND = "ash.runtime-action";
4
+ export declare function isCodeModeRuntimeActionInterrupt(interrupt: unknown): boolean;
5
+ export declare function buildRuntimeActionFromInterrupt(interrupt: CodeModeInterrupt): RuntimeActionRequest;
6
+ export declare function getRuntimeActionKeyFromInterrupt(interrupt: CodeModeInterrupt): string;
@@ -0,0 +1 @@
1
+ import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";const CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND=`ash.runtime-action`;function isCodeModeRuntimeActionInterrupt(e){return isRecord(e)&&isRecord(e.payload)&&e.payload.kind===`ash.runtime-action`}function buildRuntimeActionFromInterrupt(e){let t=e.payload,n=t.runtimeAction,r=t.toolInput,i=t.toolName,a=sanitizeCallId(`${i}_${`interruptId`in e?String(e.interruptId):``}`);return n.kind===`remote-agent-call`?{callId:a,description:``,input:r,kind:`remote-agent-call`,name:i,nodeId:n.nodeId,remoteAgentName:n.remoteAgentName??i}:{callId:a,description:``,input:r,kind:`subagent-call`,name:i,nodeId:n.nodeId,subagentName:n.subagentName}}function getRuntimeActionKeyFromInterrupt(t){return getRuntimeActionRequestKey(buildRuntimeActionFromInterrupt(t))}function sanitizeCallId(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND,buildRuntimeActionFromInterrupt,getRuntimeActionKeyFromInterrupt,isCodeModeRuntimeActionInterrupt};
@@ -1 +1 @@
1
- import"ai";import{contextStorage}from"#context/container.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,markCodeModeToolExecutionOptions,toCodeModeConnectionAuthArgs}from"#runtime/framework-tools/code-mode-connection-auth.js";import{buildToolSet}from"#harness/tools.js";function createAshCodeModeOptions(e={}){let t={approval:{mode:`interrupt`}};return e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),t}async function applyCodeModeToToolSet(e){let r={},i={};for(let[t,n]of Object.entries(e.tools)){if(isDirectTool(n,e.harnessTools.get(t))){i[t]=n;continue}r[t]=wrapHostToolForCodeMode(n)}if(Object.keys(r).length>0){let{createCodeModeTool:a}=await loadCodeModeModule();i[CODE_MODE_TOOL_NAME]=a(r,createAshCodeModeOptions({lifecycle:e.lifecycle}))}return{hostTools:r,modelTools:i}}async function buildCodeModeHostTools(t){let n=buildToolSet({approvedTools:t.approvedTools,capabilities:t.capabilities,tools:t.tools}),r=contextStorage.getStore();if(r!==void 0){let e=buildDynamicTools(r);for(let t of e)n[t.name]??={description:t.description,inputSchema:t.inputSchema,execute:t.execute,outputSchema:t.outputSchema}}return(await applyCodeModeToToolSet({harnessTools:t.tools,tools:n})).hostTools}function isDirectTool(e,t){return e.execute===void 0||t?.runtimeAction!==void 0}function wrapHostToolForCodeMode(e){let t=e.execute;if(t===void 0)return e;let invoke=async(e,i)=>{let o=await resolveExecuteOutput(t(e,markCodeModeToolExecutionOptions(i)));if(isAuthorizationSignal(o)){let{requestCodeModeInterrupt:t}=await loadCodeModeModule(),r=o.challenges[0]?.name;r&&t({args:toCodeModeConnectionAuthArgs(e),challenges:o.challenges,connectionName:r,kind:CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,toolName:``})}return o};return{...e,execute:(e,t)=>invoke(e,t)}}async function resolveExecuteOutput(e){if(isAsyncIterable(e)){let t;for await(let n of e)t=n;return t}return await e}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}export{applyCodeModeToToolSet,buildCodeModeHostTools,createAshCodeModeOptions};
1
+ import"ai";import{contextStorage}from"#context/container.js";import{CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND}from"#harness/code-mode-runtime-action-state.js";import{CODE_MODE_TOOL_NAME,loadCodeModeModule}from"#shared/code-mode.js";import{isAuthorizationSignal}from"#harness/authorization.js";import{buildDynamicTools}from"#context/build-dynamic-tools.js";import{CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,markCodeModeToolExecutionOptions,toCodeModeConnectionAuthArgs}from"#runtime/framework-tools/code-mode-connection-auth.js";import{buildToolSet}from"#harness/tools.js";function createAshCodeModeOptions(e={}){let t={approval:{mode:`interrupt`}};return e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),t}async function applyCodeModeToToolSet(e){let t={},i={};for(let[n,r]of Object.entries(e.tools)){let a=e.harnessTools.get(n);if(isDirectTool(r,a)){i[n]=r,a?.runtimeAction!==void 0&&(t[n]=createRuntimeActionHostTool(a));continue}t[n]=wrapHostToolForCodeMode(r)}if(Object.keys(t).length>0){let{createCodeModeTool:a}=await loadCodeModeModule();i[CODE_MODE_TOOL_NAME]=a(t,createAshCodeModeOptions({lifecycle:e.lifecycle}))}return{hostTools:t,modelTools:i}}async function buildCodeModeHostTools(t){let n=buildToolSet({approvedTools:t.approvedTools,capabilities:t.capabilities,tools:t.tools}),r=contextStorage.getStore();if(r!==void 0){let e=buildDynamicTools(r);for(let t of e)n[t.name]??={description:t.description,inputSchema:t.inputSchema,execute:t.execute,outputSchema:t.outputSchema}}return(await applyCodeModeToToolSet({harnessTools:t.tools,tools:n})).hostTools}function isDirectTool(e,t){return e.execute===void 0||t?.runtimeAction!==void 0}function createRuntimeActionHostTool(e){return{description:e.description,inputSchema:e.inputSchema,execute:async(n,i)=>{let a=i?.codeModeInterrupt;if(a?.resolution!==void 0)return a.resolution;let{requestCodeModeInterrupt:o}=await loadCodeModeModule();return o({kind:CODE_MODE_RUNTIME_ACTION_INTERRUPT_KIND,runtimeAction:e.runtimeAction,toolInput:n,toolName:e.name})}}}function wrapHostToolForCodeMode(e){let t=e.execute;if(t===void 0)return e;let invoke=async(e,n)=>{let a=await resolveExecuteOutput(t(e,markCodeModeToolExecutionOptions(n)));if(isAuthorizationSignal(a)){let{requestCodeModeInterrupt:t}=await loadCodeModeModule(),n=a.challenges[0]?.name;n&&t({args:toCodeModeConnectionAuthArgs(e),challenges:a.challenges,connectionName:n,kind:CODE_MODE_CONNECTION_AUTH_INTERRUPT_KIND,toolName:``})}return a};return{...e,execute:(e,t)=>invoke(e,t)}}async function resolveExecuteOutput(e){if(isAsyncIterable(e)){let t;for await(let n of e)t=n;return t}return await e}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}export{applyCodeModeToToolSet,buildCodeModeHostTools,createAshCodeModeOptions};
@@ -40,6 +40,7 @@ export declare function getPendingRuntimeActionBatch(state: SessionStateMap | un
40
40
  * Returns true when the session is parked on a pending runtime-action batch.
41
41
  */
42
42
  export declare function hasPendingRuntimeActionBatch(state: SessionStateMap | undefined): boolean;
43
+ export declare function clearPendingRuntimeActionBatch(session: HarnessSession): HarnessSession;
43
44
  /**
44
45
  * Stores one pending runtime-action batch on the session.
45
46
  */