experimental-ash 0.42.0 → 0.44.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 (184) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/bin/ash.js +1 -0
  3. package/dist/docs/internals/mechanical-invariants.md +16 -0
  4. package/dist/docs/public/README.md +8 -8
  5. package/dist/docs/public/advanced/{auth-and-route-protection.md → auth-and-route-protection.mdx} +11 -0
  6. package/dist/docs/public/advanced/context-control.md +4 -4
  7. package/dist/docs/public/advanced/{evals.md → evals.mdx} +11 -1
  8. package/dist/docs/public/advanced/{hooks.md → hooks.mdx} +28 -40
  9. package/dist/docs/public/advanced/instrumentation.md +142 -3
  10. package/dist/docs/public/advanced/project-layout.md +5 -5
  11. package/dist/docs/public/advanced/runs-and-streaming.md +8 -2
  12. package/dist/docs/public/advanced/session-context.md +1 -1
  13. package/dist/docs/public/advanced/typescript-api.md +50 -7
  14. package/dist/docs/public/advanced/vercel-deployment.md +1 -1
  15. package/dist/docs/public/agent-ts.md +5 -5
  16. package/dist/docs/public/channels/{discord.md → discord.mdx} +11 -0
  17. package/dist/docs/public/channels/index.md +10 -10
  18. package/dist/docs/public/channels/{slack.md → slack.mdx} +11 -0
  19. package/dist/docs/public/channels/{teams.md → teams.mdx} +12 -0
  20. package/dist/docs/public/channels/{telegram.md → telegram.mdx} +11 -0
  21. package/dist/docs/public/channels/{twilio.md → twilio.mdx} +11 -0
  22. package/dist/docs/public/{connections.md → connections.mdx} +18 -6
  23. package/dist/docs/public/frontend/README.md +16 -0
  24. package/dist/docs/public/frontend/meta.json +3 -0
  25. package/dist/docs/public/frontend/nextjs.md +192 -0
  26. package/dist/docs/public/frontend/use-ash-agent.md +332 -0
  27. package/dist/docs/public/{getting-started.md → getting-started.mdx} +12 -1
  28. package/dist/docs/public/{human-in-the-loop.md → human-in-the-loop.mdx} +12 -1
  29. package/dist/docs/public/meta.json +1 -0
  30. package/dist/docs/public/sandbox.md +39 -1
  31. package/dist/docs/public/{schedules.md → schedules.mdx} +9 -0
  32. package/dist/docs/public/skills.md +2 -2
  33. package/dist/docs/public/{subagents.md → subagents.mdx} +10 -0
  34. package/dist/docs/public/{tools.md → tools.mdx} +41 -26
  35. package/dist/src/channel/adapter.d.ts +13 -0
  36. package/dist/src/channel/compiled-channel.d.ts +4 -1
  37. package/dist/src/channel/compiled-channel.js +1 -1
  38. package/dist/src/channel/instrumentation.d.ts +10 -0
  39. package/dist/src/channel/instrumentation.js +1 -0
  40. package/dist/src/channel/routes.d.ts +8 -10
  41. package/dist/src/channel/send.js +1 -1
  42. package/dist/src/channel/types.d.ts +16 -0
  43. package/dist/src/cli/commands/channels.d.ts +2 -1
  44. package/dist/src/cli/commands/channels.js +1 -1
  45. package/dist/src/compiled/.vendor-stamp.json +1 -1
  46. package/dist/src/compiled/@vercel/sandbox/index.d.ts +12 -19
  47. package/dist/src/compiled/@vercel/sandbox/network-policy.d.ts +161 -0
  48. package/dist/src/compiled/just-bash/index.d.ts +15 -2
  49. package/dist/src/compiled/just-bash/network/types.d.ts +155 -0
  50. package/dist/src/compiler/artifacts.d.ts +1 -0
  51. package/dist/src/compiler/artifacts.js +1 -1
  52. package/dist/src/compiler/channel-instrumentation-types.d.ts +8 -0
  53. package/dist/src/compiler/channel-instrumentation-types.js +2 -0
  54. package/dist/src/compiler/manifest.d.ts +13 -1
  55. package/dist/src/compiler/manifest.js +1 -1
  56. package/dist/src/compiler/module-map.js +1 -1
  57. package/dist/src/compiler/normalize-manifest.js +1 -1
  58. package/dist/src/compiler/normalize-skill.d.ts +15 -2
  59. package/dist/src/compiler/normalize-skill.js +1 -1
  60. package/dist/src/compiler/normalize-tool.js +1 -1
  61. package/dist/src/context/dynamic-skill-lifecycle.d.ts +23 -0
  62. package/dist/src/context/dynamic-skill-lifecycle.js +1 -0
  63. package/dist/src/context/dynamic-tool-lifecycle.d.ts +2 -0
  64. package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
  65. package/dist/src/context/hook-lifecycle.d.ts +4 -6
  66. package/dist/src/context/hook-lifecycle.js +1 -1
  67. package/dist/src/context/keys.d.ts +6 -4
  68. package/dist/src/context/keys.js +1 -1
  69. package/dist/src/context/providers/connection.d.ts +9 -0
  70. package/dist/src/context/providers/connection.js +1 -1
  71. package/dist/src/context/providers/sandbox.js +1 -1
  72. package/dist/src/execution/ash-workflow-attributes.d.ts +118 -0
  73. package/dist/src/execution/ash-workflow-attributes.js +1 -0
  74. package/dist/src/execution/channel-context.d.ts +5 -0
  75. package/dist/src/execution/channel-context.js +1 -0
  76. package/dist/src/execution/create-session-step.d.ts +28 -1
  77. package/dist/src/execution/create-session-step.js +1 -1
  78. package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
  79. package/dist/src/execution/durable-session-store.d.ts +7 -0
  80. package/dist/src/execution/runtime-context.js +1 -1
  81. package/dist/src/execution/sandbox/bindings/local.js +1 -1
  82. package/dist/src/execution/sandbox/bindings/vercel.js +1 -1
  83. package/dist/src/execution/sandbox/prewarm.js +1 -1
  84. package/dist/src/execution/sandbox/session.d.ts +6 -1
  85. package/dist/src/execution/sandbox/session.js +1 -1
  86. package/dist/src/execution/session.d.ts +6 -0
  87. package/dist/src/execution/session.js +2 -2
  88. package/dist/src/execution/skills/instructions.d.ts +3 -2
  89. package/dist/src/execution/subagent-tool.js +1 -1
  90. package/dist/src/execution/workflow-entry.js +1 -1
  91. package/dist/src/execution/workflow-steps.js +1 -1
  92. package/dist/src/harness/attachment-staging.js +1 -1
  93. package/dist/src/harness/code-mode.d.ts +0 -5
  94. package/dist/src/harness/code-mode.js +1 -1
  95. package/dist/src/harness/emission.d.ts +1 -1
  96. package/dist/src/harness/emission.js +1 -1
  97. package/dist/src/harness/instrumentation-config.d.ts +1 -1
  98. package/dist/src/harness/instrumentation-metadata.d.ts +23 -0
  99. package/dist/src/harness/instrumentation-metadata.js +1 -0
  100. package/dist/src/harness/otel-integration.d.ts +2 -2
  101. package/dist/src/harness/otel-integration.js +1 -1
  102. package/dist/src/harness/step-hooks.js +1 -1
  103. package/dist/src/harness/tool-loop.js +1 -1
  104. package/dist/src/harness/turn-tag-state.d.ts +50 -0
  105. package/dist/src/harness/turn-tag-state.js +1 -0
  106. package/dist/src/harness/types.d.ts +11 -2
  107. package/dist/src/internal/application/package.js +1 -1
  108. package/dist/src/internal/authored-definition/schema-backed.d.ts +0 -1
  109. package/dist/src/internal/authored-definition/schema-backed.js +1 -1
  110. package/dist/src/internal/instrumentation.d.ts +39 -0
  111. package/dist/src/internal/instrumentation.js +1 -0
  112. package/dist/src/internal/workflow/builtins.d.ts +32 -0
  113. package/dist/src/internal/workflow/builtins.js +1 -1
  114. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.d.ts +1 -1
  115. package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +1 -1
  116. package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +34 -0
  117. package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
  118. package/dist/src/internal/workflow-bundle/workflow-transformer.js +1 -1
  119. package/dist/src/packages/ash-scaffold/src/channels.js +1 -1
  120. package/dist/src/packages/ash-scaffold/src/steps/run-add-to-agent.js +2 -2
  121. package/dist/src/packages/ash-scaffold/src/web-template.js +1 -0
  122. package/dist/src/public/channels/discord/discordChannel.d.ts +5 -2
  123. package/dist/src/public/channels/index.d.ts +1 -1
  124. package/dist/src/public/channels/slack/attachments.js +1 -1
  125. package/dist/src/public/channels/slack/index.d.ts +1 -1
  126. package/dist/src/public/channels/slack/slackChannel.d.ts +12 -8
  127. package/dist/src/public/channels/slack/slackChannel.js +1 -1
  128. package/dist/src/public/channels/teams/teamsChannel.d.ts +5 -2
  129. package/dist/src/public/channels/telegram/telegramChannel.d.ts +5 -2
  130. package/dist/src/public/channels/telegram/telegramChannel.js +1 -1
  131. package/dist/src/public/channels/twilio/index.d.ts +1 -1
  132. package/dist/src/public/channels/twilio/twilioChannel.d.ts +12 -3
  133. package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
  134. package/dist/src/public/definitions/defineChannel.d.ts +17 -4
  135. package/dist/src/public/definitions/defineChannel.js +1 -1
  136. package/dist/src/public/definitions/hook.d.ts +3 -11
  137. package/dist/src/public/definitions/instrumentation.d.ts +1 -66
  138. package/dist/src/public/definitions/instrumentation.js +1 -1
  139. package/dist/src/public/definitions/skill.d.ts +5 -0
  140. package/dist/src/public/definitions/tool.d.ts +25 -66
  141. package/dist/src/public/definitions/tool.js +1 -1
  142. package/dist/src/public/instrumentation/index.d.ts +175 -1
  143. package/dist/src/public/instrumentation/index.js +1 -1
  144. package/dist/src/public/sandbox/index.d.ts +1 -0
  145. package/dist/src/public/skills/index.d.ts +2 -0
  146. package/dist/src/public/skills/index.js +1 -1
  147. package/dist/src/public/tools/index.d.ts +2 -2
  148. package/dist/src/public/tools/index.js +1 -1
  149. package/dist/src/runtime/agent/mock-model-adapter.js +4 -7
  150. package/dist/src/runtime/agent/mock-model-skill-selection.d.ts +9 -0
  151. package/dist/src/runtime/agent/mock-model-skill-selection.js +4 -0
  152. package/dist/src/runtime/attributes/emit.d.ts +73 -0
  153. package/dist/src/runtime/attributes/emit.js +1 -0
  154. package/dist/src/runtime/channels/registry.js +1 -1
  155. package/dist/src/runtime/connections/mcp-client.js +1 -1
  156. package/dist/src/runtime/framework-tools/code-mode-connection-auth.d.ts +2 -0
  157. package/dist/src/runtime/framework-tools/connection-search-dynamic.d.ts +34 -0
  158. package/dist/src/runtime/framework-tools/connection-search-dynamic.js +1 -0
  159. package/dist/src/runtime/framework-tools/index.d.ts +7 -5
  160. package/dist/src/runtime/framework-tools/index.js +1 -1
  161. package/dist/src/runtime/prompt/connections.js +1 -1
  162. package/dist/src/runtime/resolve-agent-graph.js +1 -1
  163. package/dist/src/runtime/resolve-agent.js +1 -1
  164. package/dist/src/runtime/resolve-channel.js +1 -1
  165. package/dist/src/runtime/resolve-dynamic-skill.d.ts +8 -0
  166. package/dist/src/runtime/resolve-dynamic-skill.js +1 -0
  167. package/dist/src/runtime/resolve-dynamic-tool.js +1 -1
  168. package/dist/src/runtime/sessions/compiled-agent-cache.js +1 -1
  169. package/dist/src/runtime/sessions/runtime-context-keys.js +1 -1
  170. package/dist/src/runtime/types.d.ts +13 -4
  171. package/dist/src/shared/dynamic-tool-definition.d.ts +51 -76
  172. package/dist/src/shared/dynamic-tool-definition.js +1 -1
  173. package/dist/src/shared/guards.d.ts +14 -0
  174. package/dist/src/shared/guards.js +1 -1
  175. package/dist/src/shared/sandbox-network-policy.d.ts +23 -0
  176. package/dist/src/shared/sandbox-network-policy.js +1 -0
  177. package/dist/src/shared/sandbox-session.d.ts +15 -0
  178. package/dist/src/shared/skill-definition.d.ts +5 -4
  179. package/dist/src/shared/tool-definition.d.ts +12 -0
  180. package/package.json +2 -1
  181. package/dist/src/runtime/framework-tools/connection-search.d.ts +0 -57
  182. package/dist/src/runtime/framework-tools/connection-search.js +0 -1
  183. package/dist/src/runtime/framework-tools/connection-tools.d.ts +0 -55
  184. package/dist/src/runtime/framework-tools/connection-tools.js +0 -1
@@ -107,7 +107,15 @@ export type CompiledToolDefinition = InternalToolDefinition & ModuleSourceRef;
107
107
  */
108
108
  export interface CompiledDynamicToolDefinition extends ModuleSourceRef {
109
109
  readonly slug: string;
110
- readonly identity: "single" | "multi";
110
+ readonly eventNames: readonly string[];
111
+ }
112
+ /**
113
+ * Compiled dynamic skill resolver entry. Mirrors
114
+ * {@link CompiledDynamicToolDefinition} — the resolver produces skill
115
+ * packages at runtime rather than tool definitions.
116
+ */
117
+ export interface CompiledDynamicSkillDefinition extends ModuleSourceRef {
118
+ readonly slug: string;
111
119
  readonly eventNames: readonly string[];
112
120
  }
113
121
  /**
@@ -223,6 +231,7 @@ declare const compiledAgentNodeManifestSchema: z.ZodObject<{
223
231
  warnings: z.ZodNumber;
224
232
  }, z.core.$strict>;
225
233
  disabledFrameworkTools: z.ZodReadonly<z.ZodArray<z.ZodString>>;
234
+ dynamicSkills: z.ZodDefault<z.ZodArray<z.ZodType<CompiledDynamicSkillDefinition, unknown, z.core.$ZodTypeInternals<CompiledDynamicSkillDefinition, unknown>>>>;
226
235
  dynamicTools: z.ZodDefault<z.ZodArray<z.ZodType<CompiledDynamicToolDefinition, unknown, z.core.$ZodTypeInternals<CompiledDynamicToolDefinition, unknown>>>>;
227
236
  hooks: z.ZodArray<z.ZodType<CompiledHookDefinition, unknown, z.core.$ZodTypeInternals<CompiledHookDefinition, unknown>>>;
228
237
  sandbox: z.ZodNullable<z.ZodObject<{
@@ -309,6 +318,7 @@ export declare const compiledAgentManifestSchema: z.ZodObject<{
309
318
  warnings: z.ZodNumber;
310
319
  }, z.core.$strict>;
311
320
  disabledFrameworkTools: z.ZodReadonly<z.ZodArray<z.ZodString>>;
321
+ dynamicSkills: z.ZodDefault<z.ZodArray<z.ZodType<CompiledDynamicSkillDefinition, unknown, z.core.$ZodTypeInternals<CompiledDynamicSkillDefinition, unknown>>>>;
312
322
  dynamicTools: z.ZodDefault<z.ZodArray<z.ZodType<CompiledDynamicToolDefinition, unknown, z.core.$ZodTypeInternals<CompiledDynamicToolDefinition, unknown>>>>;
313
323
  hooks: z.ZodArray<z.ZodType<CompiledHookDefinition, unknown, z.core.$ZodTypeInternals<CompiledHookDefinition, unknown>>>;
314
324
  kind: z.ZodLiteral<"ash-agent-compiled-manifest">;
@@ -397,6 +407,7 @@ export declare function createCompiledAgentNodeManifest(input: {
397
407
  readonly connections?: readonly CompiledConnectionDefinition[];
398
408
  readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;
399
409
  readonly disabledFrameworkTools?: readonly string[];
410
+ readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];
400
411
  readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];
401
412
  readonly hooks?: readonly CompiledHookDefinition[];
402
413
  readonly remoteAgents?: readonly CompiledRemoteAgentNode[];
@@ -436,6 +447,7 @@ export declare function createCompiledAgentManifest(input: {
436
447
  readonly connections?: readonly CompiledConnectionDefinition[];
437
448
  readonly diagnosticsSummary?: DiscoverDiagnosticsSummary;
438
449
  readonly disabledFrameworkTools?: readonly string[];
450
+ readonly dynamicSkills?: readonly CompiledDynamicSkillDefinition[];
439
451
  readonly dynamicTools?: readonly CompiledDynamicToolDefinition[];
440
452
  readonly hooks?: readonly CompiledHookDefinition[];
441
453
  readonly remoteAgents?: readonly CompiledRemoteAgentNode[];
@@ -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=25,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(),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(),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({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(),sourceId:z.string(),sourceKind:z.literal(`module`)}).strict(),compiledDynamicToolDefinitionSchema=z.object({eventNames:z.array(z.string()).readonly(),exportName:z.string().optional(),identity:z.enum([`single`,`multi`]),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(),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(),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(25),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,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],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:25}}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=25,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(),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(),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({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(),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(),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(),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(),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(25),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,source:e.config.source===void 0?void 0:{...e.config.source}},diagnosticsSummary:e.diagnosticsSummary??{errors:0,warnings:0},disabledFrameworkTools:[...e.disabledFrameworkTools??[]],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:25}}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,5 +1,5 @@
1
1
  import{z}from"#compiled/zod/index.js";import{ROOT_COMPILED_AGENT_NODE_ID}from"#compiler/manifest.js";import{normalizeEsmImportSpecifier}from"#internal/application/import-specifier.js";const compiledModuleNodeScopeSchema=z.object({modules:z.record(z.string(),z.object({}).passthrough())}).strict(),compiledModuleMapSchema=z.object({nodes:z.record(z.string(),compiledModuleNodeScopeSchema)}).strict();function createCompiledModuleMapSource(e){let n=dirnameFilesystemPath(e.moduleMapPath),r=e.importSpecifierStyle??`relative`,i=0,a=[collectModuleNodeScope({agentRoot:e.manifest.agentRoot,importSpecifierStyle:r,manifest:e.manifest,moduleMapDirectory:n,nextBindingName(){return`module_${i++}`},nodeId:ROOT_COMPILED_AGENT_NODE_ID}),...[...e.manifest.subagents].sort((e,t)=>e.nodeId.localeCompare(t.nodeId)).map(e=>collectModuleNodeScope({agentRoot:e.agent.agentRoot,importSpecifierStyle:r,manifest:e.agent,moduleMapDirectory:n,nextBindingName(){return`module_${i++}`},nodeId:e.nodeId}))],o=a.flatMap(e=>e.modules.map(e=>`import * as ${e.bindingName} from ${JSON.stringify(e.importSpecifier)};`));return[`// Generated by Ash. Do not edit by hand.`,``,...o,...o.length>0?[``]:[],`export const moduleMap = ${renderModuleMap(a)};`,``,`export default moduleMap;`,``].join(`
2
- `)}function collectModuleNodeScope(e){return{modules:collectModuleRefsForManifest(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:createImportSpecifier({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:joinFilesystemPath(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function collectModuleRefsForManifest(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.dynamicTools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.remoteAgents)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.schedules)n.sourceKind!==`module`||!n.hasRun||t.set(n.sourceId,{sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function createImportSpecifier(e){if(e.importSpecifierStyle===`absolute`)return normalizeEsmImportSpecifier(normalizeFilesystemPath(e.targetPath));let t=relativeFilesystemPath(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function renderModuleMap(e){return renderFrozenObject([{key:`nodes`,value:renderFrozenObject(e.map(e=>({key:e.nodeId,value:renderFrozenObject([{key:`modules`,value:renderFrozenObject(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function renderFrozenObject(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
2
+ `)}function collectModuleNodeScope(e){return{modules:collectModuleRefsForManifest(e.manifest).sort((e,t)=>e.sourceId.localeCompare(t.sourceId)).map(t=>({bindingName:e.nextBindingName(),importSpecifier:createImportSpecifier({fromDirectory:e.moduleMapDirectory,importSpecifierStyle:e.importSpecifierStyle,targetPath:joinFilesystemPath(e.agentRoot,t.logicalPath)}),sourceId:t.sourceId})),nodeId:e.nodeId}}function collectModuleRefsForManifest(e){let t=new Map;e.config.source!==void 0&&t.set(e.config.source.sourceId,e.config.source),e.config.model.source!==void 0&&t.set(e.config.model.source.sourceId,e.config.model.source);for(let n of e.channels)n.kind!==`disabled`&&t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.connections)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.tools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.dynamicSkills)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.dynamicTools)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.remoteAgents)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.hooks)t.set(n.sourceId,{exportName:n.exportName,sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});for(let n of e.schedules)n.sourceKind!==`module`||!n.hasRun||t.set(n.sourceId,{sourceKind:`module`,logicalPath:n.logicalPath,sourceId:n.sourceId});return e.sandbox!==null&&t.set(e.sandbox.sourceId,{exportName:e.sandbox.exportName,sourceKind:`module`,logicalPath:e.sandbox.logicalPath,sourceId:e.sandbox.sourceId}),[...t.values()]}function createImportSpecifier(e){if(e.importSpecifierStyle===`absolute`)return normalizeEsmImportSpecifier(normalizeFilesystemPath(e.targetPath));let t=relativeFilesystemPath(e.fromDirectory,e.targetPath);return t.startsWith(`.`)?t:`./${t}`}function renderModuleMap(e){return renderFrozenObject([{key:`nodes`,value:renderFrozenObject(e.map(e=>({key:e.nodeId,value:renderFrozenObject([{key:`modules`,value:renderFrozenObject(e.modules.map(e=>({key:e.sourceId,value:e.bindingName})))}],3)})))}],0)}function renderFrozenObject(e,t=1){if(e.length===0)return`Object.freeze({})`;let n=` `.repeat(t),r=` `.repeat(t+1);return[`Object.freeze({`,e.map(e=>`${r}${JSON.stringify(e.key)}: ${e.value.replaceAll(`
3
3
  `,`\n${r}`)}`).join(`,
4
4
  `),`${n}})`].join(`
5
5
  `)}function dirnameFilesystemPath(e){let t=splitFilesystemPath(e);return t.segments.length===0?t.root.length===0?`.`:t.root:createFilesystemPath(t.root,t.segments.slice(0,-1))}function joinFilesystemPath(e,t){let n=splitFilesystemPath(e),r=splitFilesystemPath(t);return r.root.length>0?createFilesystemPath(r.root,r.segments):createFilesystemPath(n.root,[...n.segments,...r.segments])}function relativeFilesystemPath(e,t){let n=splitFilesystemPath(e),r=splitFilesystemPath(t);if(n.root!==r.root)return normalizeFilesystemPath(t);let i=0;for(;i<n.segments.length&&i<r.segments.length&&n.segments[i]===r.segments[i];)i+=1;let a=[...Array.from({length:n.segments.length-i},()=>`..`),...r.segments.slice(i)];return a.length===0?`.`:a.join(`/`)}function normalizeFilesystemPath(e){let t=splitFilesystemPath(e);return createFilesystemPath(t.root,t.segments)}function splitFilesystemPath(e){let t=e.replaceAll(`\\`,`/`),n=``,r=t,i=t.match(/^[A-Za-z]:/);i===null?t.startsWith(`/`)&&(n=`/`,r=t.slice(1)):(n=i[0],r=t.slice(n.length),r.startsWith(`/`)&&(n=`${n}/`,r=r.slice(1)));let a=[];for(let e of r.split(`/`))if(!(e.length===0||e===`.`)){if(e===`..`){if(a.length>0&&a[a.length-1]!==`..`){a.pop();continue}n.length===0&&a.push(e);continue}a.push(e)}return{root:n,segments:a}}function createFilesystemPath(e,t){return e===`/`?t.length===0?`/`:`/${t.join(`/`)}`:e.endsWith(`/`)?t.length===0?e:`${e}${t.join(`/`)}`:e.length>0?t.length===0?e:`${e}/${t.join(`/`)}`:t.length===0?`.`:t.join(`/`)}export{collectModuleRefsForManifest,compiledModuleMapSchema,createCompiledModuleMapSource};
@@ -1 +1 @@
1
- import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest}from"#compiler/manifest.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileInstructions}from"#compiler/normalize-instructions.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileSubagentGraph}from"#compiler/normalize-subagent.js";import{compileToolEntry}from"#compiler/normalize-tool.js";async function compileAgentManifest(e){let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot)},[a,o]=await Promise.all([compileAgentNodeManifest(e,r),compileSubagentGraph({appRoot:e.appRoot,compileAgentNodeManifest,context:r,parentNodeId:ROOT_COMPILED_AGENT_NODE_ID,subagents:e.subagents})]);return createCompiledAgentManifest({...a,remoteAgents:o.remoteAgents,subagentEdges:o.edges,subagents:o.nodes})}async function compileAgentNodeManifest(t,n){let i=await Promise.all(t.tools.map(e=>compileToolEntry(t.agentRoot,e))),s=[],c=[],l=[];for(let e of i)e.kind===`tool`?s.push(e.definition):e.kind===`dynamic-tool`?c.push(e.definition):l.push(e.name);let u=(await Promise.all(t.channels.map(n=>compileChannelDefinition(t.agentRoot,n)))).flat();return createCompiledAgentNodeManifest({agentRoot:t.agentRoot,appRoot:t.appRoot,channels:u,config:await compileAgentConfig(t,n),connections:await Promise.all(t.connections.map(e=>compileConnectionDefinition(t.agentRoot,e))),diagnosticsSummary:t.diagnosticsSummary,disabledFrameworkTools:l,dynamicTools:c,hooks:t.hooks.map(e=>compileHookEntry(e)),sandbox:t.sandbox===null?null:await compileSandboxDefinition(t.agentRoot,t.sandbox),sandboxWorkspaces:t.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:await Promise.all(t.schedules.map(e=>compileScheduleDefinition(t.agentRoot,e))),skills:await Promise.all(t.skills.map(e=>compileSkillSource(t.agentRoot,e))),instructions:t.instructions===void 0?void 0:await compileInstructions(t.agentRoot,t.instructions),tools:s})}export{compileAgentManifest};
1
+ import{compileChannelDefinition}from"#compiler/normalize-channel.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest,createCompiledAgentNodeManifest}from"#compiler/manifest.js";import{createCompiledRuntimeModelCatalogLoader}from"#compiler/model-catalog.js";import{compileAgentConfig}from"#compiler/normalize-agent-config.js";import{compileConnectionDefinition}from"#compiler/normalize-connection.js";import{compileHookEntry}from"#compiler/normalize-hook.js";import{compileSandboxDefinition}from"#compiler/normalize-sandbox.js";import{compileInstructions}from"#compiler/normalize-instructions.js";import{compileScheduleDefinition}from"#compiler/normalize-schedule.js";import{compileSkillSource}from"#compiler/normalize-skill.js";import{compileSubagentGraph}from"#compiler/normalize-subagent.js";import{compileToolEntry}from"#compiler/normalize-tool.js";async function compileAgentManifest(e){let r={modelCatalog:createCompiledRuntimeModelCatalogLoader(e.appRoot)},[a,o]=await Promise.all([compileAgentNodeManifest(e,r),compileSubagentGraph({appRoot:e.appRoot,compileAgentNodeManifest,context:r,parentNodeId:ROOT_COMPILED_AGENT_NODE_ID,subagents:e.subagents})]);return createCompiledAgentManifest({...a,remoteAgents:o.remoteAgents,subagentEdges:o.edges,subagents:o.nodes})}async function compileAgentNodeManifest(t,n){let i=await Promise.all(t.tools.map(e=>compileToolEntry(t.agentRoot,e))),s=[],c=[],l=[];for(let e of i)e.kind===`tool`?s.push(e.definition):e.kind===`dynamic-tool`?c.push(e.definition):l.push(e.name);let u=(await Promise.all(t.channels.map(n=>compileChannelDefinition(t.agentRoot,n)))).flat(),d=await Promise.all(t.skills.map(e=>compileSkillSource(t.agentRoot,e))),f=[],p=[];for(let e of d)e.kind===`skill`?f.push(e.definition):p.push(e.definition);return createCompiledAgentNodeManifest({agentRoot:t.agentRoot,appRoot:t.appRoot,channels:u,config:await compileAgentConfig(t,n),connections:await Promise.all(t.connections.map(e=>compileConnectionDefinition(t.agentRoot,e))),diagnosticsSummary:t.diagnosticsSummary,disabledFrameworkTools:l,dynamicSkills:p,dynamicTools:c,hooks:t.hooks.map(e=>compileHookEntry(e)),sandbox:t.sandbox===null?null:await compileSandboxDefinition(t.agentRoot,t.sandbox),sandboxWorkspaces:t.sandboxWorkspaces.map(e=>({logicalPath:e.logicalPath,rootEntries:[...e.rootEntries],sourceId:e.sourceId,sourcePath:e.sourcePath})),schedules:await Promise.all(t.schedules.map(e=>compileScheduleDefinition(t.agentRoot,e))),skills:f,instructions:t.instructions===void 0?void 0:await compileInstructions(t.agentRoot,t.instructions),tools:s})}export{compileAgentManifest};
@@ -1,8 +1,21 @@
1
1
  import type { SkillSourceRef } from "#discover/manifest.js";
2
- import type { CompiledSkillDefinition } from "#compiler/manifest.js";
2
+ import type { CompiledDynamicSkillDefinition, CompiledSkillDefinition } from "#compiler/manifest.js";
3
+ /**
4
+ * Compiled skill entry produced from one authored `skills/*` file.
5
+ *
6
+ * Either a real skill definition or a dynamic skill resolver that
7
+ * produces skills at runtime.
8
+ */
9
+ export type CompiledSkillEntry = {
10
+ readonly kind: "skill";
11
+ readonly definition: CompiledSkillDefinition;
12
+ } | {
13
+ readonly kind: "dynamic-skill";
14
+ readonly definition: CompiledDynamicSkillDefinition;
15
+ };
3
16
  /**
4
17
  * Compiles one authored skill source (markdown, module, or skill
5
18
  * package directory) into the normalized shape stored on the compiled
6
19
  * agent manifest.
7
20
  */
8
- export declare function compileSkillSource(agentRoot: string, source: SkillSourceRef): Promise<CompiledSkillDefinition>;
21
+ export declare function compileSkillSource(agentRoot: string, source: SkillSourceRef): Promise<CompiledSkillEntry>;
@@ -1 +1 @@
1
- import{stripLogicalPathExtension}from"#discover/filesystem.js";import{normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";async function compileSkillSource(t,n){if(n.sourceKind===`skill-package`)return compileSkillPackageSource(n);let r=n.sourceKind===`markdown`?normalizeSkillDefinition(n.definition,`Expected the compiled skill definition at "${n.logicalPath}" to match the public Ash shape.`):normalizeSkillDefinition(await loadModuleBackedDefinition({agentRoot:t,kind:`skill`,source:n}),`Expected the skill export "${n.exportName??`default`}" from "${n.logicalPath}" to match the public Ash shape.`);return{description:r.description,files:r.files,license:r.license,logicalPath:n.logicalPath,markdown:r.markdown,metadata:r.metadata===void 0?void 0:{...r.metadata},name:stripLogicalPathExtension(n.logicalPath).replace(/^skills\//,``),sourceId:n.sourceId,sourceKind:n.sourceKind}}function compileSkillPackageSource(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:e.logicalPath,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillId:e.skillId,skillFilePath:e.skillFilePath,sourceId:e.sourceId,sourceKind:`skill-package`}}export{compileSkillSource};
1
+ import{stripLogicalPathExtension}from"#discover/filesystem.js";import{normalizeSkillDefinition}from"#internal/authored-definition/core.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{isDynamicSentinel}from"#shared/dynamic-tool-definition.js";async function compileSkillSource(r,i){if(i.sourceKind===`skill-package`)return{kind:`skill`,definition:compileSkillPackageSource(i)};if(i.sourceKind===`markdown`){let n=normalizeSkillDefinition(i.definition,`Expected the compiled skill definition at "${i.logicalPath}" to match the public Ash shape.`);return{kind:`skill`,definition:{description:n.description,files:n.files,license:n.license,logicalPath:i.logicalPath,markdown:n.markdown,metadata:n.metadata===void 0?void 0:{...n.metadata},name:stripLogicalPathExtension(i.logicalPath).replace(/^skills\//,``),sourceId:i.sourceId,sourceKind:i.sourceKind}}}let a=await loadModuleBackedDefinition({agentRoot:r,kind:`skill`,source:i});if(isDynamicSentinel(a)){let t=stripLogicalPathExtension(i.logicalPath).replace(/^skills\//,``);return{kind:`dynamic-skill`,definition:{eventNames:Object.keys(a.events),exportName:i.exportName,logicalPath:i.logicalPath,slug:t,sourceId:i.sourceId,sourceKind:`module`}}}let o=normalizeSkillDefinition(a,`Expected the skill export "${i.exportName??`default`}" from "${i.logicalPath}" to match the public Ash shape.`);return{kind:`skill`,definition:{description:o.description,files:o.files,license:o.license,logicalPath:i.logicalPath,markdown:o.markdown,metadata:o.metadata===void 0?void 0:{...o.metadata},name:stripLogicalPathExtension(i.logicalPath).replace(/^skills\//,``),sourceId:i.sourceId,sourceKind:i.sourceKind}}}function compileSkillPackageSource(e){return{assetsPath:e.assetsPath,description:e.description,license:e.license,logicalPath:e.logicalPath,markdown:e.markdown,metadata:e.metadata===void 0?void 0:{...e.metadata},name:e.name,referencesPath:e.referencesPath,rootPath:e.rootPath,scriptsPath:e.scriptsPath,skillId:e.skillId,skillFilePath:e.skillFilePath,sourceId:e.sourceId,sourceKind:`skill-package`}}export{compileSkillSource};
@@ -1 +1 @@
1
- import{stripLogicalPathExtension}from"#discover/filesystem.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeToolDefinition}from"#internal/authored-definition/schema-backed.js";async function compileToolEntry(e,t){let n=normalizeToolDefinition(await loadModuleBackedDefinition({agentRoot:e,kind:`tool`,source:t}),`Expected the tool export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r=stripLogicalPathExtension(t.logicalPath).replace(/^tools\//,``).replaceAll(`/`,`-`);return n.kind===`disabled`?{kind:`disabled`,name:r}:n.kind===`dynamic-tool`?{kind:`dynamic-tool`,definition:{eventNames:[...n.eventNames],exportName:t.exportName,identity:n.identity,logicalPath:t.logicalPath,slug:r,sourceId:t.sourceId,sourceKind:`module`}}:{kind:`tool`,definition:{description:n.definition.description,exportName:t.exportName,inputSchema:n.definition.inputSchema??null,logicalPath:t.logicalPath,name:r,sourceId:t.sourceId,sourceKind:`module`}}}export{compileToolEntry};
1
+ import{stripLogicalPathExtension}from"#discover/filesystem.js";import{loadModuleBackedDefinition}from"#compiler/normalize-helpers.js";import{normalizeToolDefinition}from"#internal/authored-definition/schema-backed.js";async function compileToolEntry(e,t){let n=normalizeToolDefinition(await loadModuleBackedDefinition({agentRoot:e,kind:`tool`,source:t}),`Expected the tool export "${t.exportName??`default`}" from "${t.logicalPath}" to match the public Ash shape.`),r=stripLogicalPathExtension(t.logicalPath).replace(/^tools\//,``).replaceAll(`/`,`-`);return n.kind===`disabled`?{kind:`disabled`,name:r}:n.kind===`dynamic-tool`?{kind:`dynamic-tool`,definition:{eventNames:[...n.eventNames],exportName:t.exportName,logicalPath:t.logicalPath,slug:r,sourceId:t.sourceId,sourceKind:`module`}}:{kind:`tool`,definition:{description:n.definition.description,exportName:t.exportName,inputSchema:n.definition.inputSchema??null,logicalPath:t.logicalPath,name:r,sourceId:t.sourceId,sourceKind:`module`}}}export{compileToolEntry};
@@ -0,0 +1,23 @@
1
+ import type { ModelMessage } from "ai";
2
+ import type { HandleMessageStreamEvent } from "#protocol/message.js";
3
+ import type { ResolvedDynamicSkillResolver } from "#runtime/types.js";
4
+ import type { ContextContainer } from "#context/container.js";
5
+ import { ContextKey } from "#context/key.js";
6
+ /**
7
+ * Virtual (non-serialized) pending skill announcement text. Set by
8
+ * {@link dispatchDynamicSkillEvent} when skills are materialized. Read
9
+ * by the tool-loop to inject the announcement into model context.
10
+ */
11
+ export declare const PendingSkillAnnouncementKey: ContextKey<string>;
12
+ /**
13
+ * Dispatches a stream event to dynamic skill resolvers. On a matching
14
+ * event: runs handlers, materializes resolved skills to the sandbox,
15
+ * cleans up removed skills, and stores a pending announcement for the
16
+ * tool-loop to inject.
17
+ */
18
+ export declare function dispatchDynamicSkillEvent(input: {
19
+ readonly ctx: ContextContainer;
20
+ readonly resolvers: readonly ResolvedDynamicSkillResolver[];
21
+ readonly event: HandleMessageStreamEvent;
22
+ readonly messages: readonly ModelMessage[];
23
+ }): Promise<void>;
@@ -0,0 +1 @@
1
+ import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ContinuationTokenKey,DynamicSkillManifestKey,InitiatorAuthKey,SandboxKey,SessionIdKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS}from"#shared/dynamic-tool-definition.js";import{normalizeSkillPackage,writeSkillPackageToSandbox}from"#shared/skill-package.js";import{ContextKey}from"#context/key.js";import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";const log=createLogger(`dynamic-skills`),WORKSPACE_SKILLS_PREFIX=`/workspace/skills/`;function buildResolveContext(e,i){let o=e.get(SessionIdKey)??``,c=e.get(AuthKey)??null,l=e.get(InitiatorAuthKey)??null,u=e.get(ChannelKey),d=e.get(ContinuationTokenKey);return{session:{id:o,auth:{current:c,initiator:l}},channel:{kind:u===void 0?void 0:getAdapterKind(u),continuationToken:d},messages:i}}function qualifyDynamicSkillNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t||r.length===1)return i.push({name:e,entryKey:r[0],entry:n[r[0]]}),i;for(let t of r)i.push({name:`${e}__${t}`,entryKey:t,entry:n[t]});return i}function isSkillEntry(e){return typeof e==`object`&&!!e&&typeof e.markdown==`string`&&typeof e.description==`string`}const PendingSkillAnnouncementKey=new ContextKey(`ash.pendingSkillAnnouncement`);async function dispatchDynamicSkillEvent(e){let{ctx:t,resolvers:n,event:r,messages:a}=e;if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(r.type))return;let s=n.filter(e=>e.eventNames.includes(r.type));if(s.length===0)return;let f=buildResolveContext(t,a),p=new Set(t.require(BundleKey).resolvedAgent.skills.map(e=>e.name)),m=t.get(DynamicSkillManifestKey)??{},h={...m},g=[],_=await Promise.allSettled(s.map(async e=>{let t=e.events[r.type];if(t===void 0)return null;let n=await t(r,f);if(n==null)return{resolver:e,entries:null};let i,a;return isSkillEntry(n)?(i={_single:n},a=!0):(i=n,a=!1),{resolver:e,entries:i,isSingle:a}})),v=await t.require(SandboxKey).get();for(let e of _){if(e.status===`rejected`){log.error(`Dynamic skill resolver (${r.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,entries:n,isSingle:i}=e.value,a=m[t.slug]??[];if(n===null){if(a.length>0&&v!==null)for(let e of a)await v.run({command:`rm -rf ${WORKSPACE_SKILLS_PREFIX}${e}`});h[t.slug]=[];continue}let o=qualifyDynamicSkillNames(t.slug,i,n),s=new Set(o.map(e=>e.name));for(let{name:e}of o)if(p.has(e))throw Error(`Dynamic skill "${e}" from resolver "${t.slug}" conflicts with an authored skill.`);if(v!==null)for(let e of a)s.has(e)||await v.run({command:`rm -rf ${WORKSPACE_SKILLS_PREFIX}${e}`});if(v!==null)for(let{name:e,entry:t}of o){let n=normalizeSkillPackage({...t,name:e});await writeSkillPackageToSandbox({sandbox:v,skill:n}),g.push(n)}h[t.slug]=[...s]}if(t.set(DynamicSkillManifestKey,h),g.length>0){let e=formatAvailableSkillsSection(g);e!==null&&t.set(PendingSkillAnnouncementKey,e)}}export{PendingSkillAnnouncementKey,dispatchDynamicSkillEvent};
@@ -1,3 +1,4 @@
1
+ import { type ModelMessage } from "ai";
1
2
  import type { HarnessToolDefinition } from "#harness/execute-tool.js";
2
3
  import type { HandleMessageStreamEvent } from "#protocol/message.js";
3
4
  import type { ResolvedDynamicToolResolver } from "#runtime/types.js";
@@ -26,4 +27,5 @@ export declare function dispatchDynamicToolEvent(input: {
26
27
  readonly ctx: ContextContainer;
27
28
  readonly resolvers: readonly ResolvedDynamicToolResolver[];
28
29
  readonly event: HandleMessageStreamEvent;
30
+ readonly messages: readonly ModelMessage[];
29
31
  }): Promise<void>;
@@ -1 +1 @@
1
- import{createLogger}from"#internal/logging.js";import{AuthKey,ContinuationTokenKey,DynamicSessionToolMetadataKey,DynamicToolResolverCacheKey,DynamicToolsKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{jsonSchema,zodSchema}from"ai";import{ALLOWED_DYNAMIC_TOOL_EVENTS}from"#shared/dynamic-tool-definition.js";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getAdapterKind}from"#channel/adapter.js";const log=createLogger(`dynamic-tools`);function buildResolveContext(e,r,a){let c=e.get(SessionIdKey)??``,l=e.get(AuthKey)??null,u=e.get(InitiatorAuthKey)??null,d=e.get(ChannelKey),f=e.get(ContinuationTokenKey);return{session:{id:c,auth:{current:l,initiator:u}},channel:{kind:d===void 0?void 0:getAdapterKind(d),continuationToken:f},async __cache(t,n){let o=`${r}:${t}`,s=e.get(DynamicToolResolverCacheKey)??{};if(o in s)return s[o];let c=await n();if(a){let e={...s,[o]:c};a.set(DynamicToolResolverCacheKey,e)}return c}}}function toHarnessToolDefinition(e,t){return{description:t.description,execute:e=>t.execute(e,buildCallbackContext()),inputSchema:convertInputSchema(t.inputSchema),name:e}}function convertInputSchema(e){return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t===`single`)return i.push({name:e,entryKey:r[0],entry:n[r[0]]}),i;for(let t of r)i.push({name:`${e}__${t}`,entryKey:t,entry:n[t]});return i}function replayDynamicSessionTools(e,t){let n=[];for(let t of e){if(!t.executeStepFnName||!t.closureVars){log.warn(`Dynamic tool "${t.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(t.executeStepFnName);if(!e){log.warn(`Dynamic tool "${t.name}" references step function "${t.executeStepFnName}" which is not registered — skipping on this step.`);continue}n.push({description:t.description,execute:n=>e(t.closureVars,n,buildCallbackContext()),inputSchema:jsonSchema(t.inputSchema),name:t.name})}return n}function lookupStepFunction(e){try{let t=globalThis[Symbol.for(`@workflow/core//registeredSteps`)];return t===void 0?null:t.get(e)||null}catch{return null}}function safeSerialize(e){try{return JSON.parse(JSON.stringify(e))}catch{return{}}}function matchesAnySlug(e,t){for(let n of t)if(e===n||e.startsWith(`${n}__`))return!0;return!1}async function resolveToolsFromEvent(e,t,n){let i=await Promise.allSettled(t.map(async t=>{let r=t.events[n.type];if(r===void 0)return null;let i=await r(n,buildResolveContext(e,t.slug,e));return i==null?null:{resolver:t,result:i}})),a=[],o=[];for(let e of i){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,result:r}=e.value,i=qualifyDynamicToolNames(t.slug,t.identity,r);for(let{name:e,entryKey:n,entry:r}of i){a.push(toHarnessToolDefinition(e,r));let i=`__executeStepFn`in r?r.__executeStepFn:void 0,s=`__closureVars`in r?r.__closureVars:void 0;o.push({name:e,description:r.description,inputSchema:normalizeJsonSchemaDefinition(r.inputSchema),resolverSlug:t.slug,entryKey:n,executeStepFnName:i?.stepId,closureVars:s===void 0?void 0:safeSerialize(s)})}}if(o.length>0){let t=e.get(DynamicSessionToolMetadataKey)??[],n=new Set(o.map(e=>e.resolverSlug)),i=t.filter(e=>!n.has(e.resolverSlug));e.set(DynamicSessionToolMetadataKey,[...i,...o])}return a}async function dispatchDynamicToolEvent(e){let{ctx:t,resolvers:n,event:i}=e;if(t.get(DynamicToolsKey)===void 0){let e=t.get(DynamicSessionToolMetadataKey);if(e!==void 0&&e.length>0){let r=replayDynamicSessionTools(e,n);r.length>0&&t.setVirtualContext(DynamicToolsKey,[...r])}}if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(i.type))return;let o=n.filter(e=>e.eventNames.includes(i.type));if(o.length===0)return;let s=await resolveToolsFromEvent(t,o,i);if(s.length===0)return;let c=new Set(o.map(e=>e.slug)),l=(t.get(DynamicToolsKey)??[]).filter(e=>!matchesAnySlug(e.name,c));t.setVirtualContext(DynamicToolsKey,[...l,...s])}export{dispatchDynamicToolEvent,replayDynamicSessionTools};
1
+ import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{AuthKey,ContinuationTokenKey,DynamicSessionToolMetadataKey,DynamicToolsKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{toErrorMessage}from"#shared/errors.js";import{ALLOWED_DYNAMIC_TOOL_EVENTS,isBrandedToolEntry}from"#shared/dynamic-tool-definition.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{jsonSchema,zodSchema}from"ai";import{normalizeJsonSchemaDefinition}from"#internal/json-schema.js";import{buildCallbackContext}from"#context/build-callback-context.js";const log=createLogger(`dynamic-tools`);function buildResolveContext(e,i){let a=e.get(SessionIdKey)??``,c=e.get(AuthKey)??null,l=e.get(InitiatorAuthKey)??null,u=e.get(ChannelKey),f=e.get(ContinuationTokenKey);return{session:{id:a,auth:{current:c,initiator:l}},channel:{kind:u===void 0?void 0:getAdapterKind(u),continuationToken:f},messages:i}}function toHarnessToolDefinition(e,t){return{description:t.description,execute:e=>t.execute(e,buildCallbackContext()),inputSchema:convertInputSchema(t.inputSchema),name:e,...t.toModelOutput===void 0?{}:{toModelOutput:t.toModelOutput}}}function convertInputSchema(e){return typeof e==`object`&&e&&`~standard`in e?zodSchema(e):jsonSchema(e)}function qualifyDynamicToolNames(e,t,n){let r=Object.keys(n),i=[];if(r.length===0)return i;if(t)return i.push({name:e,entryKey:r[0],entry:n[r[0]]}),i;for(let t of r)i.push({name:`${e}__${t}`,entryKey:t,entry:n[t]});return i}function replayDynamicSessionTools(e,t){let n=[];for(let t of e){if(!t.executeStepFnName||!t.closureVars){log.warn(`Dynamic tool "${t.name}" has no registered step function — skipping on this step. The bundler transform may not have processed this tool file.`);continue}let e=lookupStepFunction(t.executeStepFnName);if(!e){log.warn(`Dynamic tool "${t.name}" references step function "${t.executeStepFnName}" which is not registered — skipping on this step.`);continue}n.push({description:t.description,execute:n=>e(t.closureVars,n,buildCallbackContext()),inputSchema:jsonSchema(t.inputSchema),name:t.name})}return n}function lookupStepFunction(e){try{let t=globalThis[Symbol.for(`@workflow/core//registeredSteps`)];return t===void 0?null:t.get(e)||null}catch{return null}}function safeSerialize(e){try{return JSON.parse(JSON.stringify(e))}catch{return{}}}function matchesAnySlug(e,t){for(let n of t)if(e===n||e.startsWith(`${n}__`))return!0;return!1}async function resolveToolsFromEvent(e,t,n,r){let a=await Promise.allSettled(t.map(async t=>{let i=t.events[n.type];if(i===void 0)return null;let a=await i(n,buildResolveContext(e,r));if(a==null)return null;let o,s;return isBrandedToolEntry(a)?(o={_single:a},s=!0):(o=a,s=!1),{resolver:t,entries:o,isSingle:s}})),o=[],s=[];for(let e of a){if(e.status===`rejected`){log.error(`Dynamic tool resolver (${n.type}) threw — skipping.`,{error:toErrorMessage(e.reason)});continue}if(e.value===null)continue;let{resolver:t,entries:r,isSingle:i}=e.value,a=qualifyDynamicToolNames(t.slug,i,r);for(let{name:e,entryKey:n,entry:r}of a){o.push(toHarnessToolDefinition(e,r));let i=`__executeStepFn`in r?r.__executeStepFn:void 0,a=`__closureVars`in r?r.__closureVars:void 0;s.push({name:e,description:r.description,inputSchema:normalizeJsonSchemaDefinition(r.inputSchema),resolverSlug:t.slug,entryKey:n,executeStepFnName:i?.stepId,closureVars:a===void 0?void 0:safeSerialize(a)})}}if(s.length>0){let t=e.get(DynamicSessionToolMetadataKey)??[],n=new Set(s.map(e=>e.resolverSlug)),r=t.filter(e=>!n.has(e.resolverSlug));e.set(DynamicSessionToolMetadataKey,[...r,...s])}return o}async function dispatchDynamicToolEvent(e){let{ctx:t,resolvers:n,event:r,messages:o}=e;if(t.get(DynamicToolsKey)===void 0){let e=t.get(DynamicSessionToolMetadataKey);if(e!==void 0&&e.length>0){let r=replayDynamicSessionTools(e,n);r.length>0&&t.setVirtualContext(DynamicToolsKey,[...r])}}if(!ALLOWED_DYNAMIC_TOOL_EVENTS.has(r.type))return;let s=n.filter(e=>e.eventNames.includes(r.type));if(s.length===0)return;let c=await resolveToolsFromEvent(t,s,r,o);if(c.length===0)return;let u=new Set(s.map(e=>e.slug)),d=(t.get(DynamicToolsKey)??[]).filter(e=>!matchesAnySlug(e.name,u));t.setVirtualContext(DynamicToolsKey,[...d,...c])}export{dispatchDynamicToolEvent,replayDynamicSessionTools};
@@ -5,8 +5,7 @@ import type { RuntimeHookRegistry } from "#runtime/hooks/registry.js";
5
5
  import type { ContextContainer } from "./container.js";
6
6
  /**
7
7
  * Outcome of {@link dispatchHookLifecycle}. `proceed` carries the
8
- * input augmented with merged `modelContext` and any hook-contributed
9
- * skill announcements on the session. `turn-failed` means a
8
+ * input augmented with merged `modelContext`. `turn-failed` means a
10
9
  * `lifecycle.turn` hook threw; the recoverable `turn.failed` cascade
11
10
  * has already been emitted.
12
11
  */
@@ -36,10 +35,9 @@ export interface DispatchHookLifecycleInput {
36
35
  * runs so a thrown hook does not retry. A throw re-propagates and
37
36
  * the runtime escalates to terminal `session.failed`.
38
37
  * - `lifecycle.turn` runs once per fresh delivery. Each hook may
39
- * return `{ modelContext, skills }`; model-context contributions
40
- * are concatenated in registry order, skills are materialized into
41
- * the sandbox. A thrown hook emits the recoverable `turn.failed`
42
- * cascade and returns `kind: "turn-failed"`.
38
+ * return `{ modelContext }`; model-context contributions are
39
+ * concatenated in registry order. A thrown hook emits the recoverable
40
+ * `turn.failed` cascade and returns `kind: "turn-failed"`.
43
41
  */
44
42
  export declare function dispatchHookLifecycle(input: DispatchHookLifecycleInput): Promise<HookLifecycleOutcome>;
45
43
  /**
@@ -1 +1 @@
1
- import{ContinuationTokenKey,SandboxKey,SessionPreparedKey}from"./keys.js";import{createLogger}from"#internal/logging.js";import{toErrorMessage}from"#shared/errors.js";import{normalizeSkillPackage,writeSkillPackageToSandbox}from"#shared/skill-package.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getAdapterKind}from"#channel/adapter.js";import{emitRecoverableFailedTurn,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";import{formatAvailableSkillsSection}from"#execution/skills/instructions.js";const log=createLogger(`hooks.lifecycle`);async function dispatchHookLifecycle(e){let{ctx:t,registry:r,emit:a}=e,o=getHarnessEmissionState(e.session.state),s=buildHookContext(t),c=[],l=e.session;if(r.session.length>0&&t.get(SessionPreparedKey)!==!0){t.set(SessionPreparedKey,!0);let e=[];for(let n of r.session){let r=await n.handler(s);r?.modelContext!==void 0&&r.modelContext.length>0&&c.push(...r.modelContext),e.push(...normalizeLifecycleSkillResults(t,r))}l=await materializeLifecycleSkills(t,l,e)}let u=!1,d=o;try{let e=[];for(let n of r.turn){let r=await n.handler(s);r?.modelContext!==void 0&&r.modelContext.length>0&&c.push(...r.modelContext),e.push(...normalizeLifecycleSkillResults(t,r))}l=await materializeLifecycleSkills(t,l,e)}catch(t){let n=toErrorMessage(t);try{u||=(d=await emitTurnPreamble(a,{message:e.input.message},o,e.runtimeIdentity),!0);let t=await emitRecoverableFailedTurn(a,d,{code:`HOOK_TURN_FAILED`,message:n});return{kind:`turn-failed`,message:n,nextSession:setHarnessEmissionState(l,t)}}catch(e){throw log.error(`Event hook threw while emitting the turn.failed cascade for a lifecycle.turn failure — escalating to session.failed.`,{error:toErrorMessage(e)}),e}}let f=e.input.modelContext??[],p=f.length===0?c:[...f,...c];return{kind:`proceed`,input:p.length>0?{...e.input,modelContext:p}:e.input,nextSession:l}}function normalizeLifecycleSkillResults(e,t){if(t?.skills===void 0||t.skills.length===0)return[];let n=new Set(e.require(BundleKey).resolvedAgent.skills.map(e=>e.name)),r=new Map;for(let e of t.skills){let t=normalizeSkillPackage(e);if(n.has(t.name))throw Error(`Hook-contributed skill "${t.name}" conflicts with an authored skill.`);r.set(t.name,t)}return[...r.values()]}async function materializeLifecycleSkills(e,n,r){if(r.length===0)return n;let i=new Map(r.map(e=>[e.name,e])),a=await e.require(SandboxKey).get();if(a===null)throw Error(`Dynamic skills require a sandbox for the current agent.`);for(let e of i.values())await writeSkillPackageToSandbox({sandbox:a,skill:e});let s=formatAvailableSkillsSection([...i.values()]);return s===null?n:{...n,history:[...n.history,{role:`system`,content:s}]}}async function dispatchStreamEventHooks(e){let t=e.registry.streamEventsByType.get(e.event.type)??[],n=e.registry.streamEventsWildcard;if(t.length===0&&n.length===0)return;let r=buildHookContext(e.ctx);for(let n of t)await n.handler(e.event,r);for(let t of n)await t.handler(e.event,r)}function buildHookContext(t){let n=t.require(BundleKey),r=t.get(ChannelKey),i=t.get(ContinuationTokenKey),a=r===void 0?void 0:getAdapterKind(r);return{...buildCallbackContext(),agent:{name:n.resolvedAgent.config.name??`agent`,nodeId:n.nodeId},channel:{kind:a,continuationToken:i}}}async function runHookLifecycleStep(e,t){let n=await dispatchHookLifecycle(e);return n.kind===`turn-failed`?{next:e.mode===`conversation`?null:{done:!0,output:n.message},session:n.nextSession}:t(n.nextSession,n.input)}export{dispatchHookLifecycle,dispatchStreamEventHooks,runHookLifecycleStep};
1
+ import{ContinuationTokenKey,SessionPreparedKey}from"./keys.js";import{createLogger}from"#internal/logging.js";import{getAdapterKind}from"#channel/adapter.js";import{toErrorMessage}from"#shared/errors.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildCallbackContext}from"#context/build-callback-context.js";import{emitRecoverableFailedTurn,emitTurnPreamble,getHarnessEmissionState,setHarnessEmissionState}from"#harness/emission.js";const log=createLogger(`hooks.lifecycle`);async function dispatchHookLifecycle(e){let{ctx:n,registry:r,emit:a}=e,o=getHarnessEmissionState(e.session.state),s=buildHookContext(n),u=[],d=e.session;if(r.session.length>0&&n.get(SessionPreparedKey)!==!0){n.set(SessionPreparedKey,!0);for(let e of r.session){let t=await e.handler(s);t?.modelContext!==void 0&&t.modelContext.length>0&&u.push(...t.modelContext)}}let f=!1,p=o;try{for(let e of r.turn){let t=await e.handler(s);t?.modelContext!==void 0&&t.modelContext.length>0&&u.push(...t.modelContext)}}catch(t){let n=toErrorMessage(t);try{return f||=(p=await emitTurnPreamble(a,{message:e.input.message},o,e.runtimeIdentity),!0),{kind:`turn-failed`,message:n,nextSession:setHarnessEmissionState(d,await emitRecoverableFailedTurn(a,p,{code:`HOOK_TURN_FAILED`,message:n}))}}catch(e){throw log.error(`Event hook threw while emitting the turn.failed cascade for a lifecycle.turn failure — escalating to session.failed.`,{error:toErrorMessage(e)}),e}}let m=e.input.modelContext??[],h=m.length===0?u:[...m,...u];return{kind:`proceed`,input:h.length>0?{...e.input,modelContext:h}:e.input,nextSession:d}}async function dispatchStreamEventHooks(e){let t=e.registry.streamEventsByType.get(e.event.type)??[],n=e.registry.streamEventsWildcard;if(t.length===0&&n.length===0)return;let r=buildHookContext(e.ctx);for(let n of t)await n.handler(e.event,r);for(let t of n)await t.handler(e.event,r)}function buildHookContext(t){let n=t.require(BundleKey),i=t.get(ChannelKey),c=t.get(ContinuationTokenKey),l=i===void 0?void 0:getAdapterKind(i);return{...buildCallbackContext(),agent:{name:n.resolvedAgent.config.name??`agent`,nodeId:n.nodeId},channel:{kind:l,continuationToken:c}}}async function runHookLifecycleStep(e,t){let n=await dispatchHookLifecycle(e);return n.kind===`turn-failed`?{next:e.mode===`conversation`?null:{done:!0,output:n.message},session:n.nextSession}:t(n.nextSession,n.input)}export{dispatchHookLifecycle,dispatchStreamEventHooks,runHookLifecycleStep};
@@ -3,7 +3,7 @@
3
3
  * tier. Codec-carrying keys (`ChannelKey`, `BundleKey`) live in
4
4
  * `#runtime/sessions/runtime-context-keys.ts`.
5
5
  */
6
- import type { SessionAuthContext, SessionCallback, SessionCapabilities, SessionParent, SessionTurn } from "#channel/types.js";
6
+ import type { ChannelInstrumentationProjection, SessionAuthContext, SessionCallback, SessionCapabilities, SessionParent, SessionTurn } from "#channel/types.js";
7
7
  import { ContextKey } from "#context/key.js";
8
8
  import type { SandboxAccess } from "#sandbox/state.js";
9
9
  import type { RunMode } from "#shared/run-mode.js";
@@ -32,6 +32,7 @@ export declare const AuthKey: ContextKey<SessionAuthContext | null>;
32
32
  export declare const InitiatorAuthKey: ContextKey<SessionAuthContext | null>;
33
33
  export declare const SessionIdKey: ContextKey<string>;
34
34
  export declare const ContinuationTokenKey: ContextKey<string>;
35
+ export declare const ChannelInstrumentationKey: ContextKey<ChannelInstrumentationProjection>;
35
36
  export declare const ModeKey: ContextKey<RunMode>;
36
37
  export declare const ParentSessionKey: ContextKey<SessionParent>;
37
38
  /**
@@ -87,7 +88,8 @@ export interface DurableDynamicToolMetadata {
87
88
  }
88
89
  export declare const DynamicSessionToolMetadataKey: ContextKey<readonly DurableDynamicToolMetadata[]>;
89
90
  /**
90
- * Durable cache for resolver I/O results. Keyed by resolver slug +
91
- * await index. Populated on first resolver run, read on replay.
91
+ * Durable map from resolver slug to the qualified skill names it last
92
+ * produced. Used to diff on re-resolution and clean up removed skills
93
+ * from the sandbox.
92
94
  */
93
- export declare const DynamicToolResolverCacheKey: ContextKey<Record<string, unknown>>;
95
+ export declare const DynamicSkillManifestKey: ContextKey<Record<string, readonly string[]>>;
@@ -1 +1 @@
1
- import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`ash.auth`),InitiatorAuthKey=new ContextKey(`ash.initiatorAuth`),SessionIdKey=new ContextKey(`ash.sessionId`),ContinuationTokenKey=new ContextKey(`ash.continuationToken`),ModeKey=new ContextKey(`ash.mode`),ParentSessionKey=new ContextKey(`ash.parentSession`),CapabilitiesKey=new ContextKey(`ash.capabilities`),SessionCallbackKey=new ContextKey(`ash.sessionCallback`),SessionPreparedKey=new ContextKey(`ash.sessionPrepared`),SessionKey=new ContextKey(`ash.session`),SandboxKey=new ContextKey(`ash.sandbox`),DynamicToolsKey=new ContextKey(`ash.dynamicTools`),DynamicSessionToolMetadataKey=new ContextKey(`ash.dynamicSessionToolMetadata`),DynamicToolResolverCacheKey=new ContextKey(`ash.dynamicToolResolverCache`);export{AuthKey,CapabilitiesKey,ContinuationTokenKey,DynamicSessionToolMetadataKey,DynamicToolResolverCacheKey,DynamicToolsKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SandboxKey,SessionCallbackKey,SessionIdKey,SessionKey,SessionPreparedKey};
1
+ import{ContextKey}from"#context/key.js";const AuthKey=new ContextKey(`ash.auth`),InitiatorAuthKey=new ContextKey(`ash.initiatorAuth`),SessionIdKey=new ContextKey(`ash.sessionId`),ContinuationTokenKey=new ContextKey(`ash.continuationToken`),ChannelInstrumentationKey=new ContextKey(`ash.channelInstrumentation`),ModeKey=new ContextKey(`ash.mode`),ParentSessionKey=new ContextKey(`ash.parentSession`),CapabilitiesKey=new ContextKey(`ash.capabilities`),SessionCallbackKey=new ContextKey(`ash.sessionCallback`),SessionPreparedKey=new ContextKey(`ash.sessionPrepared`),SessionKey=new ContextKey(`ash.session`),SandboxKey=new ContextKey(`ash.sandbox`),DynamicToolsKey=new ContextKey(`ash.dynamicTools`),DynamicSessionToolMetadataKey=new ContextKey(`ash.dynamicSessionToolMetadata`),DynamicSkillManifestKey=new ContextKey(`ash.dynamicSkillManifest`);export{AuthKey,CapabilitiesKey,ChannelInstrumentationKey,ContinuationTokenKey,DynamicSessionToolMetadataKey,DynamicSkillManifestKey,DynamicToolsKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SandboxKey,SessionCallbackKey,SessionIdKey,SessionKey,SessionPreparedKey};
@@ -1,3 +1,12 @@
1
+ import { ContextKey } from "#context/key.js";
1
2
  import type { ConnectionRegistry } from "#runtime/connections/types.js";
2
3
  import type { FrameworkContextProvider } from "#context/provider.js";
4
+ /**
5
+ * Context key for the per-session connection registry.
6
+ *
7
+ * Created as a derived key (no codec) because the registry holds live
8
+ * client instances that cannot be serialized across step boundaries.
9
+ * The `connectionProvider` reconstructs it each step.
10
+ */
11
+ export declare const ConnectionRegistryKey: ContextKey<ConnectionRegistry>;
3
12
  export declare const connectionProvider: FrameworkContextProvider<ConnectionRegistry>;
@@ -1 +1 @@
1
- import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{ConnectionRegistryImpl}from"#runtime/connections/registry.js";import{ConnectionRegistryKey}from"#runtime/framework-tools/connection-search.js";import{getActiveRuntimeNode}from"#context/node.js";const connectionProvider={key:ConnectionRegistryKey,create(e,t){if(e.get(BundleKey)===void 0)return;let n=getActiveRuntimeNode(e).agent?.connections;if(!(!n||n.length===0))return{value:new ConnectionRegistryImpl(n)}}};export{connectionProvider};
1
+ import{ContextKey}from"#context/key.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{ConnectionRegistryImpl}from"#runtime/connections/registry.js";import{getActiveRuntimeNode}from"#context/node.js";const ConnectionRegistryKey=new ContextKey(`ash.connectionRegistry`),connectionProvider={key:ConnectionRegistryKey,create(e,t){if(e.get(BundleKey)===void 0)return;let n=getActiveRuntimeNode(e).agent?.connections;if(!(!n||n.length===0))return{value:new ConnectionRegistryImpl(n)}}};export{ConnectionRegistryKey,connectionProvider};
@@ -1 +1 @@
1
- import{SandboxKey,SessionIdKey}from"#context/keys.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getAdapterKind}from"#channel/adapter.js";import{getActiveRuntimeNode}from"#context/node.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";const sandboxProvider={key:SandboxKey,async create(e,r){let i=e.get(BundleKey);if(i===void 0)return;let a=getActiveRuntimeNode(e),o=a.sandboxRegistry,s=e.require(SessionIdKey);return{value:await ensureSandboxAccess({compiledArtifactsSource:i.compiledArtifactsSource,nodeId:a.nodeId,registry:o,runOnSession:async t=>await contextStorage.run(e,t),sessionId:s,state:r.sandboxState??null,tags:{agent:resolveTagAgentName({bundle:i,node:a}),channel:resolveTagChannelKind(e.get(ChannelKey)),sessionId:s}})}},async commit(e,t){let n=await e.captureState();return{...t,sandboxState:n}}};function resolveTagAgentName(e){let t=e.node,n=e.bundle;return t.agent?.config?.name??n.resolvedAgent?.config?.name??t.nodeId??`unknown`}function resolveTagChannelKind(e){return e===void 0?`unknown`:getAdapterKind(e)}export{sandboxProvider};
1
+ import{getAdapterKind}from"#channel/adapter.js";import{SandboxKey,SessionIdKey}from"#context/keys.js";import{contextStorage}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getActiveRuntimeNode}from"#context/node.js";import{ensureSandboxAccess}from"#execution/sandbox/ensure.js";const sandboxProvider={key:SandboxKey,async create(e,t){let r=e.get(BundleKey);if(r===void 0)return;let i=getActiveRuntimeNode(e),a=i.sandboxRegistry,o=e.require(SessionIdKey);return{value:await ensureSandboxAccess({compiledArtifactsSource:r.compiledArtifactsSource,nodeId:i.nodeId,registry:a,runOnSession:async t=>await contextStorage.run(e,t),sessionId:o,state:t.sandboxState??null,tags:{agent:resolveTagAgentName({bundle:r,node:i}),channel:resolveTagChannelKind(e.get(ChannelKey)),sessionId:o}})}},async commit(e,t){let n=await e.captureState();return{...t,sandboxState:n}}};function resolveTagAgentName(e){let t=e.node,n=e.bundle;return t.agent?.config?.name??n.resolvedAgent?.config?.name??t.nodeId??`unknown`}function resolveTagChannelKind(t){return t===void 0?`unknown`:getAdapterKind(t)}export{sandboxProvider};
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Builders for the framework's reserved `$ash.*` workflow attributes.
3
+ *
4
+ * Each builder returns a plain `Record<string, string | number | undefined>`
5
+ * suitable for `setAshAttributes` from
6
+ * {@link "#runtime/attributes/emit.js" }. Builders are intentionally
7
+ * pure data → data transforms: they hold zero dependencies on the
8
+ * workflow runtime so the workflow body, step bodies, and tests can
9
+ * all call them identically.
10
+ *
11
+ * `$ash.*` is the framework-owned attribute namespace. Authored code
12
+ * never emits these tags directly — they describe the structural shape
13
+ * of a session/turn/subagent run so dashboards can stitch a tree of
14
+ * workflow runs back together without inspecting their bodies.
15
+ *
16
+ * Tag inventory (recap):
17
+ * - `$ash.type` — `"session" | "turn" | "subagent"`
18
+ * - `$ash.parent` — sessionId of the **immediate** parent
19
+ * - `$ash.root` — sessionId of the **root** session in the chain
20
+ * - `$ash.subagent` — active compiled graph node id (subagent rows only)
21
+ * - `$ash.trigger` — channel adapter kind (session/subagent rows)
22
+ * - `$ash.title` — truncated session title from the first user message
23
+ */
24
+ import type { AshAttributeValue } from "#runtime/attributes/emit.js";
25
+ /**
26
+ * Active compiled graph node id for the session's agent. Returned by
27
+ * `createSessionStep` so workflow bodies don't have to load the bundle
28
+ * themselves. Equal to the framework root sentinel (`"__root__"`) for
29
+ * the root agent; equal to the subagent's compiled node id for
30
+ * delegated child runs. Tag emitters use this to populate
31
+ * `$ash.subagent`.
32
+ */
33
+ export interface SessionIdentitySummary {
34
+ readonly nodeId: string;
35
+ }
36
+ /**
37
+ * Reads the active channel kind from a deserialized context map.
38
+ * Returns `undefined` when the channel slot is missing or malformed —
39
+ * tag emission silently drops undefined values.
40
+ */
41
+ export declare function readChannelKind(serializedContext: Record<string, unknown>): string | undefined;
42
+ /**
43
+ * Reads the immediate parent session id from a deserialized context map.
44
+ * Returns `undefined` when the run is a top-level session.
45
+ */
46
+ export declare function readParentSessionId(serializedContext: Record<string, unknown>): string | undefined;
47
+ /**
48
+ * Reads the **root** session id from a deserialized context map.
49
+ *
50
+ * `ash.parentSession.rootSessionId` is denormalized at every dispatch
51
+ * site (see {@link "#channel/types.js".SessionParent}) so a subagent
52
+ * five levels deep can still attribute itself to the top user-facing
53
+ * session without walking the chain. Returns `undefined` for top-level
54
+ * runs, which carry no `ash.parentSession`.
55
+ */
56
+ export declare function readRootSessionId(serializedContext: Record<string, unknown>): string | undefined;
57
+ /**
58
+ * Maximum visible length (in code points) of a derived `$ash.title`.
59
+ *
60
+ * The runtime separately caps every tag value to a byte budget
61
+ * (`ASH_ATTRIBUTE_VALUE_MAX_BYTES`), but titles render as the first
62
+ * column of the dashboard's run table, so they get a tighter,
63
+ * display-oriented cap here. Kept well under the byte budget so the
64
+ * value never reaches the runtime truncator.
65
+ */
66
+ export declare const ASH_SESSION_TITLE_MAX_CHARS = 80;
67
+ /**
68
+ * Derives the `$ash.title` value from the first user message of a
69
+ * top-level session.
70
+ *
71
+ * Returns `undefined` when no plain-text content is available; the
72
+ * attribute emitter strips undefined values. Multimodal messages
73
+ * (image/file parts) contribute only their text parts to keep the
74
+ * title human-readable. Long prompts are truncated to
75
+ * {@link ASH_SESSION_TITLE_MAX_CHARS} code points with a trailing
76
+ * ellipsis so the dashboard's title column stays readable.
77
+ */
78
+ export declare function deriveSessionTitle(message: unknown): string | undefined;
79
+ /**
80
+ * Builds the `$ash.*` attribute payload for a top-level session run
81
+ * (`workflowEntry` invoked without an `ash.parentSession`).
82
+ *
83
+ * `$ash.root` is intentionally omitted — the session row IS the root,
84
+ * so its own `workflowRunId` already identifies the chain root.
85
+ */
86
+ export declare function buildSessionAttributes(input: {
87
+ readonly inputMessage: unknown;
88
+ readonly serializedContext: Record<string, unknown>;
89
+ }): Record<string, AshAttributeValue>;
90
+ /**
91
+ * Builds the `$ash.*` attribute payload for a delegated subagent root
92
+ * run (`workflowEntry` invoked with an `ash.parentSession`).
93
+ *
94
+ * `$ash.root` carries the **root** session id so the dashboard can
95
+ * group every descendant under one query: `search($ash.root=<root>)`
96
+ * returns all turns and nested subagents under that user-facing
97
+ * session in a single round trip.
98
+ */
99
+ export declare function buildSubagentRootAttributes(input: {
100
+ readonly identity: SessionIdentitySummary;
101
+ readonly parentSessionId: string;
102
+ readonly rootSessionId: string;
103
+ readonly serializedContext: Record<string, unknown>;
104
+ }): Record<string, AshAttributeValue>;
105
+ /**
106
+ * Builds the `$ash.*` attribute payload for one turn workflow run.
107
+ *
108
+ * Turns live one level below their session: `$ash.parent` always points
109
+ * to the parent's sessionId (which is the session-row's
110
+ * `workflowRunId`), and `$ash.root` denormalizes the chain root (equal
111
+ * to `$ash.parent` for turns of top-level sessions). Turn ordering is
112
+ * recovered from each run's `createdAt`, so no explicit sequence tag is
113
+ * emitted.
114
+ */
115
+ export declare function buildTurnAttributes(input: {
116
+ readonly parentSessionId: string;
117
+ readonly rootSessionId: string;
118
+ }): Record<string, AshAttributeValue>;
@@ -0,0 +1 @@
1
+ function readChannelKind(e){let t=e[`ash.channel`]?.kind;return typeof t==`string`&&t.length>0?t:void 0}function readParentSessionId(e){let t=e[`ash.parentSession`]?.sessionId;return typeof t==`string`&&t.length>0?t:void 0}function readRootSessionId(e){let t=e[`ash.parentSession`]?.rootSessionId;return typeof t==`string`&&t.length>0?t:void 0}const ASH_SESSION_TITLE_MAX_CHARS=80;function deriveSessionTitle(e){let t=collectMessageText(e);if(t===void 0||t.length===0)return;let n=t.replace(/\s+/gu,` `).trim();if(n.length===0)return;let r=Array.from(n);return r.length<=80?n:`${r.slice(0,79).join(``)}…`}function collectMessageText(e){if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=[];for(let n of e)n&&typeof n==`object`&&n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.length>0?t.join(` `):void 0}function buildSessionAttributes(e){return{"$ash.type":`session`,"$ash.trigger":readChannelKind(e.serializedContext),"$ash.title":deriveSessionTitle(e.inputMessage)}}function buildSubagentRootAttributes(e){return{"$ash.type":`subagent`,"$ash.parent":e.parentSessionId,"$ash.root":e.rootSessionId,"$ash.subagent":e.identity.nodeId,"$ash.trigger":readChannelKind(e.serializedContext)}}function buildTurnAttributes(e){return{"$ash.type":`turn`,"$ash.parent":e.parentSessionId,"$ash.root":e.rootSessionId}}export{ASH_SESSION_TITLE_MAX_CHARS,buildSessionAttributes,buildSubagentRootAttributes,buildTurnAttributes,deriveSessionTitle,readChannelKind,readParentSessionId,readRootSessionId};
@@ -0,0 +1,5 @@
1
+ import type { ChannelAdapter } from "#channel/adapter.js";
2
+ import type { ContextContainer } from "#context/container.js";
3
+ export declare function setChannelContext(ctx: ContextContainer, adapter: ChannelAdapter, options?: {
4
+ readonly channelName?: string;
5
+ }): void;
@@ -0,0 +1 @@
1
+ import{ChannelInstrumentationKey}from"#context/keys.js";import{ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{buildChannelInstrumentationProjection}from"#channel/instrumentation.js";function setChannelContext(e,t,n={}){e.set(ChannelKey,t),e.set(ChannelInstrumentationKey,buildChannelInstrumentationProjection({adapter:t,channelName:n.channelName,existingKind:e.get(ChannelInstrumentationKey)?.kind}))}export{setChannelContext};
@@ -1,15 +1,42 @@
1
1
  import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
2
2
  import { type DurableSessionSnapshot, type DurableSessionState } from "#execution/durable-session-store.js";
3
+ /**
4
+ * Result returned by {@link createSessionStep}.
5
+ *
6
+ * Exposes the projected {@link DurableSessionState} the driver needs to
7
+ * drive the turn loop.
8
+ */
9
+ export interface CreateSessionStepResult {
10
+ readonly state: DurableSessionState;
11
+ }
3
12
  /**
4
13
  * Creates the durable session and writes the initial snapshot to the
5
14
  * `ash.session` stream before the workflow enters its turn loop.
6
15
  * `nodeId` targets a subagent node in the compiled graph; omitted for
7
16
  * the root agent.
17
+ *
18
+ * Emits the session/subagent-root `$ash.*` tags from inside this step
19
+ * (so the attribute write folds into a step the session already runs)
20
+ * and returns the durable state value the driver consumes.
8
21
  */
9
22
  export declare function createSessionStep(input: {
10
23
  readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
11
24
  readonly continuationToken: string;
25
+ /**
26
+ * First user message of the run, used to derive `$ash.title` for
27
+ * top-level sessions. Threaded in so the session/subagent-root tags
28
+ * can be emitted from inside this step (see the tag write below)
29
+ * instead of the workflow body, where each `setAshAttributes` call
30
+ * spends a standalone `__builtin_set_attributes` step.
31
+ */
32
+ readonly inputMessage: unknown;
12
33
  readonly nodeId?: string;
34
+ readonly rootSessionId?: string;
35
+ /**
36
+ * Shared serialized context, read for `$ash.trigger` (channel kind)
37
+ * and to detect whether this run is a delegated subagent root.
38
+ */
39
+ readonly serializedContext: Record<string, unknown>;
13
40
  readonly sessionId: string;
14
41
  readonly sessionWritable: WritableStream<DurableSessionSnapshot>;
15
- }): Promise<DurableSessionState>;
42
+ }): Promise<CreateSessionStepResult>;
@@ -1 +1 @@
1
- import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{writeDurableSession}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId});return await writeDurableSession({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,sessionId:e.sessionId,turnAgent:t.turnAgent}),writable:e.sessionWritable})}export{createSessionStep};
1
+ import{ROOT_RUNTIME_AGENT_NODE_ID}from"#runtime/graph.js";import{getCompiledRuntimeAgentBundle}from"#runtime/sessions/compiled-agent-cache.js";import{writeDurableSession}from"#execution/durable-session-store.js";import{createSession}from"#execution/session.js";import{buildSessionAttributes,buildSubagentRootAttributes,readParentSessionId}from"#execution/ash-workflow-attributes.js";import{setAshAttributes}from"#runtime/attributes/emit.js";async function createSessionStep(e){"use step";let t=await getCompiledRuntimeAgentBundle({compiledArtifactsSource:e.compiledArtifactsSource,nodeId:e.nodeId}),n=await writeDurableSession({session:createSession({compactionOverrides:{thresholdPercent:t.resolvedAgent.config.compaction?.thresholdPercent},continuationToken:e.continuationToken,rootSessionId:e.rootSessionId,sessionId:e.sessionId,turnAgent:t.turnAgent}),writable:e.sessionWritable}),r={nodeId:t.nodeId??ROOT_RUNTIME_AGENT_NODE_ID},i=readParentSessionId(e.serializedContext);return i===void 0?await setAshAttributes(buildSessionAttributes({inputMessage:e.inputMessage,serializedContext:e.serializedContext})):await setAshAttributes(buildSubagentRootAttributes({identity:r,parentSessionId:i,rootSessionId:e.rootSessionId??i,serializedContext:e.serializedContext})),{state:n}}export{createSessionStep};
@@ -1 +1 @@
1
- import{createLogger,logError}from"#internal/logging.js";import{AuthKey,CapabilitiesKey,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{callAdapterEventHandler}from"#channel/adapter.js";import{readDurableSession,writeDurableSession}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),u=getPendingRuntimeActionBatch(s.state);if(u===void 0||u.actions.length===0)return{results:[],sessionState:e.sessionState};let d=await deserializeContext(e.serializedContext),f=d.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:f.turnAgent}),m=d.require(ChannelKey),h=d.get(AuthKey)??null,g=d.get(CapabilitiesKey),_=d.get(InitiatorAuthKey)??null,v=e.parentWritable.getWriter(),y=buildAdapterContext(m,d),b=p,x=[];try{for(let n of u.actions){let r,i,s,c;switch(n.kind){case`subagent-call`:{let e=createWorkflowRuntime({compiledArtifactsSource:f.compiledArtifactsSource,nodeId:n.nodeId}),{childContinuationToken:t,runInput:a}=buildSubagentRunInput({action:n,auth:h,batchEvent:u.event,capabilities:g,initiatorAuth:_,session:p}),o=await e.run(a);b=recordPendingSubagentChildToken({callId:n.callId,childContinuationToken:t,session:b}),r=o.sessionId,i=n.name,c=n.subagentName;break}case`remote-agent-call`:{let a;try{a=resolveRemoteAgentForAction({nodeId:n.nodeId,remoteAgentName:n.remoteAgentName,registry:f.subagentRegistry.subagentsByNodeId}),r=await startRemoteAgentSession({action:n,callbackBaseUrl:e.callbackBaseUrl,remote:a,session:p})}catch(e){logError(log,`remote agent start failed`,e,{remoteAgentName:n.remoteAgentName,nodeId:n.nodeId,callId:n.callId}),x.push(createRemoteAgentStartFailureResult({action:n,error:e}));continue}i=n.name,s={url:a.url},c=n.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${n.kind}" in workflow runtime.`)}let l=await callAdapterEventHandler(m,createSubagentCalledEvent({callId:n.callId,childSessionId:r,name:i,remote:s,sequence:u.event.sequence,sessionId:p.sessionId,toolName:c,turnId:u.event.turnId,workflowId:workflowEntryReference.workflowId}),y);await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(l)))}}finally{v.releaseLock()}return{results:x,sessionState:b===p?e.sessionState:await writeDurableSession({session:b,writable:e.sessionWritable})}}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,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{readDurableSession,writeDurableSession}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),u=getPendingRuntimeActionBatch(s.state);if(u===void 0||u.actions.length===0)return{results:[],sessionState:e.sessionState};let d=await deserializeContext(e.serializedContext),f=d.require(BundleKey),p=hydrateDurableSession({compactionOverrides:{thresholdPercent:f.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:f.turnAgent}),m=d.require(ChannelKey),h=d.get(AuthKey)??null,g=d.get(CapabilitiesKey),_=d.get(InitiatorAuthKey)??null,v=e.parentWritable.getWriter(),y=buildAdapterContext(m,d),b=p,x=[];try{for(let r of u.actions){let i,a,s,c;switch(r.kind){case`subagent-call`:{let e=createWorkflowRuntime({compiledArtifactsSource:f.compiledArtifactsSource,nodeId:r.nodeId}),{childContinuationToken:t,runInput:n}=buildSubagentRunInput({action:r,auth:h,batchEvent:u.event,capabilities:g,initiatorAuth:_,session:p}),o=await e.run(n);b=recordPendingSubagentChildToken({callId:r.callId,childContinuationToken:t,session:b}),i=o.sessionId,a=r.name,c=r.subagentName;break}case`remote-agent-call`:{let n;try{n=resolveRemoteAgentForAction({nodeId:r.nodeId,remoteAgentName:r.remoteAgentName,registry:f.subagentRegistry.subagentsByNodeId}),i=await startRemoteAgentSession({action:r,callbackBaseUrl:e.callbackBaseUrl,remote:n,session:p})}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,s={url:n.url},c=r.remoteAgentName;break}default:throw Error(`Unsupported runtime action kind "${r.kind}" in workflow runtime.`)}let l=await callAdapterEventHandler(m,createSubagentCalledEvent({callId:r.callId,childSessionId:i,name:a,remote:s,sequence:u.event.sequence,sessionId:p.sessionId,toolName:c,turnId:u.event.turnId,workflowId:workflowEntryReference.workflowId}),y);await v.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(l)))}}finally{v.releaseLock()}return{results:x,sessionState:b===p?e.sessionState:await writeDurableSession({session:b,writable:e.sessionWritable})}}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};
@@ -56,6 +56,13 @@ export interface DurableSessionState {
56
56
  */
57
57
  export interface DurableSession {
58
58
  readonly sessionId: string;
59
+ /**
60
+ * Top user-facing session id in the dispatch chain. Optional because
61
+ * a top-level session is its own root. Persisted so a rehydrated
62
+ * subagent session still knows its root after a workflow step
63
+ * boundary.
64
+ */
65
+ readonly rootSessionId?: string;
59
66
  readonly continuationToken: string;
60
67
  readonly history: ModelMessage[];
61
68
  readonly state?: SessionStateMap;
@@ -1 +1 @@
1
- import{AuthKey,CapabilitiesKey,ContinuationTokenKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionCallbackKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";function buildRunContext(e){let{bundle:t,run:n}=e,r=new ContextContainer,i=n.auth;return r.set(BundleKey,t),r.set(ChannelKey,n.adapter),r.set(ContinuationTokenKey,n.continuationToken??``),r.set(ModeKey,n.mode),r.set(AuthKey,i),r.set(InitiatorAuthKey,n.initiatorAuth??i),n.capabilities!==void 0&&r.set(CapabilitiesKey,n.capabilities),n.callback!==void 0&&r.set(SessionCallbackKey,n.callback),n.parent!==void 0&&r.set(ParentSessionKey,n.parent),r}export{buildRunContext};
1
+ import{AuthKey,CapabilitiesKey,ContinuationTokenKey,InitiatorAuthKey,ModeKey,ParentSessionKey,SessionCallbackKey}from"#context/keys.js";import{ContextContainer}from"#context/container.js";import{BundleKey}from"#runtime/sessions/runtime-context-keys.js";import{setChannelContext}from"#execution/channel-context.js";function buildRunContext(e){let{bundle:t,run:n}=e,r=new ContextContainer,i=n.auth;return r.set(BundleKey,t),setChannelContext(r,n.adapter,{channelName:n.channelName}),r.set(ContinuationTokenKey,n.continuationToken??``),r.set(ModeKey,n.mode),r.set(AuthKey,i),r.set(InitiatorAuthKey,n.initiatorAuth??i),n.capabilities!==void 0&&r.set(CapabilitiesKey,n.capabilities),n.callback!==void 0&&r.set(SessionCallbackKey,n.callback),n.parent!==void 0&&r.set(ParentSessionKey,n.parent),r}export{buildRunContext};