eve 0.18.2 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/src/compiled/.vendor-stamp.json +2 -1
- package/dist/src/compiled/@chat-adapter/slack/index.js +29 -32
- package/dist/src/compiled/@chat-adapter/twilio/LICENSE +9 -0
- package/dist/src/compiled/@chat-adapter/twilio/api.d.ts +108 -0
- package/dist/src/compiled/@chat-adapter/twilio/api.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/format.d.ts +12 -0
- package/dist/src/compiled/@chat-adapter/twilio/format.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/index.d.ts +84 -0
- package/dist/src/compiled/@chat-adapter/twilio/index.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/voice.d.ts +44 -0
- package/dist/src/compiled/@chat-adapter/twilio/voice.js +1 -0
- package/dist/src/compiled/@chat-adapter/twilio/webhook.d.ts +18 -0
- package/dist/src/compiled/@chat-adapter/twilio/webhook.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-5OX2R7AJ-CxVV-owP.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-PFJ2G64A-B79fSABi.js +1 -0
- package/dist/src/compiled/_chunks/node/chunk-QZV7YRVM-Dzw4WEBv.js +1 -0
- package/dist/src/compiled/_chunks/node/dist-RHRJZ03Q.js +4 -0
- package/dist/src/harness/action-result-helpers.d.ts +11 -1
- package/dist/src/harness/action-result-helpers.js +1 -1
- package/dist/src/harness/emission.d.ts +1 -0
- package/dist/src/harness/emission.js +1 -1
- package/dist/src/harness/step-hooks.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/nitro/dev-runtime-source-snapshot-copy.js +1 -1
- package/dist/src/internal/nitro/host/configure-nitro-routes.js +1 -1
- package/dist/src/internal/nitro/host/dev-authored-source-watcher.js +1 -1
- package/dist/src/internal/nitro/routes/index.d.ts +7 -2
- package/dist/src/internal/nitro/routes/index.js +78 -48
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.d.ts +141 -0
- package/dist/src/public/channels/chat-sdk/chatSdkChannel.js +3 -0
- package/dist/src/public/channels/chat-sdk/index.d.ts +1 -0
- package/dist/src/public/channels/chat-sdk/index.js +1 -0
- package/dist/src/public/channels/discord/discordChannel.js +1 -1
- package/dist/src/public/channels/index.d.ts +2 -0
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/twilio/api.d.ts +8 -29
- package/dist/src/public/channels/twilio/api.js +1 -1
- package/dist/src/public/channels/twilio/inbound.d.ts +10 -19
- package/dist/src/public/channels/twilio/inbound.js +2 -2
- package/dist/src/public/channels/twilio/routing.d.ts +13 -0
- package/dist/src/public/channels/twilio/routing.js +1 -0
- package/dist/src/public/channels/twilio/twilioChannel.js +1 -1
- package/dist/src/public/channels/twilio/twiml.d.ts +5 -36
- package/dist/src/public/channels/twilio/twiml.js +1 -1
- package/dist/src/public/channels/twilio/verify.d.ts +12 -33
- package/dist/src/public/channels/twilio/verify.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/package.json +7 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.
|
|
1
|
+
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";import{fileURLToPath}from"node:url";let cachedPackageInfo;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.19.0`,WORKFLOW_MODULE_ALIASES={"workflow/errors":`src/compiled/@workflow/errors/index.js`,"workflow/internal/private":`src/compiled/@workflow/core/private.js`};function resolveFallbackPackageVersion(){return BUNDLED_FALLBACK_PACKAGE_VERSION.startsWith(`__`)?`0.0.0`:BUNDLED_FALLBACK_PACKAGE_VERSION}const FALLBACK_PACKAGE_INFO={name:EVE_PACKAGE_NAME,version:resolveFallbackPackageVersion()};function resolveCurrentModulePath(){return typeof __filename==`string`?__filename:resolveCurrentModulePathFromStack()}function resolveCurrentModulePathFromStack(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(e,t)=>t;let e=Error().stack?.[0]?.getFileName();if(typeof e!=`string`||e.length===0)throw Error(`Failed to resolve the current module path from the stack trace.`);return e.startsWith(`file:`)?fileURLToPath(e):e}finally{Error.prepareStackTrace=e}}const require=createRequire(resolveCurrentModulePath());function isBuildOutputPackageRoot(e){return basename(e)===`dist`&&existsSync(join(dirname(e),`package.json`))}function resolvePackageBuildRoot(){let e=dirname(realpathSync(resolveCurrentModulePath()));for(;;){if(isBuildOutputPackageRoot(e))return e;let t=dirname(e);if(t===e)return null;e=t}}function findNearestPackageRoot(e){let n=e;for(;;){if(existsSync(join(n,`package.json`))&&!isBuildOutputPackageRoot(n))return n;let r=dirname(n);if(r===n)throw Error(`Failed to resolve package root from "${e}".`);n=r}}function resolvePackageRoot(){return findNearestPackageRoot(dirname(realpathSync(resolveCurrentModulePath())))}function tryResolvePackageRoot(){try{return resolvePackageRoot()}catch{return}}function rewriteSourceFilePathForBuild(e){return e.replace(/\.[cm]?tsx?$/,`.js`)}function resolvePackageSourceFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),e):join(t,rewriteSourceFilePathForBuild(e))}function resolvePackageSourceDirectoryPath(e){let t=resolvePackageBuildRoot();return join(t===null?resolvePackageRoot():t,e)}function resolvePackageDependencyPath(e){return require.resolve(e)}function resolvePackageCompiledFilePath(e){let t=resolvePackageBuildRoot();return t===null?join(resolvePackageRoot(),`.generated`,`compiled`,e.replace(/^src\/compiled\//,``)):join(t,e)}function normalizeInstalledPackageInfo(e){let t=e;if(!(typeof t.name!=`string`||typeof t.version!=`string`))return{name:t.name,version:t.version}}function tryReadInstalledPackageInfo(e,t){let r=normalizeInstalledPackageInfo(JSON.parse(readFileSync(e,`utf8`)));if(r?.name===t)return r}function resolveInstalledPackageInfo(){if(cachedPackageInfo)return cachedPackageInfo;let e=tryResolvePackageRoot(),t=e===void 0?void 0:tryReadInstalledPackageInfo(join(e,`package.json`),EVE_PACKAGE_NAME);if(t)return cachedPackageInfo=t,cachedPackageInfo;try{let e=tryReadInstalledPackageInfo(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),EVE_PACKAGE_NAME);if(e)return cachedPackageInfo=e,cachedPackageInfo}catch{}return cachedPackageInfo={...FALLBACK_PACKAGE_INFO},cachedPackageInfo}function readWorkflowVersionFromManifest(e){let t=e;for(let e of[t.devDependencies,t.dependencies,t.peerDependencies]){let t=e?.[`@workflow/core`];if(typeof t==`string`&&t.trim().length>0)return t}}function resolveExpectedWorkflowVersion(){let e=tryResolvePackageRoot();if(e!==void 0)try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(join(e,`package.json`),`utf8`)))}catch{}try{return readWorkflowVersionFromManifest(JSON.parse(readFileSync(require.resolve(`${EVE_PACKAGE_NAME}/package.json`),`utf8`)))}catch{return}}function resolveWorkflowModulePath(e){if(e===`workflow`)return resolvePackageSourceFilePath(`src/internal/workflow/index.ts`);if(e===`workflow/api`||e===`workflow/runtime`)return resolvePackageSourceFilePath(`src/internal/workflow/runtime.ts`);if(e===`workflow/internal/builtins`)return resolvePackageSourceFilePath(`src/internal/workflow/builtins.ts`);let t=WORKFLOW_MODULE_ALIASES[e];return t===void 0?require.resolve(e):resolvePackageCompiledFilePath(t)}export{resolveExpectedWorkflowVersion,resolveInstalledPackageInfo,resolvePackageDependencyPath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.eve`,`.git`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]);async function copyDevelopmentSourceSnapshot(
|
|
1
|
+
import{constants,existsSync}from"node:fs";import{dirname,join,relative,resolve,sep}from"node:path";import{cp,lstat,mkdir,readFile,readdir,symlink,writeFile}from"node:fs/promises";import{DevelopmentRuntimeSourceSnapshotError,toDevelopmentSourceSnapshotPath}from"#internal/nitro/dev-runtime-source-snapshot.js";import{extractTsConfigExtendsSpecifiers,isTsConfigFilePath,parseTsConfigObject,readTextFileIfExists,resolveFirstExistingTsConfigExtendsTarget,resolveTsConfigExtendsTargetPaths}from"#internal/application/tsconfig-dependencies.js";const SNAPSHOT_SKIP_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`node_modules`]),SNAPSHOT_APP_ROOT_SKIP_NAMES=new Set([`build`,`dist`]),SNAPSHOT_COPY_MODE=constants.COPYFILE_FICLONE;async function copyDevelopmentSourceSnapshot(e){await mkdir(e.snapshotSourceRoot,{recursive:!0});for(let t of e.copyRoots)await copySnapshotPath({plan:e,sourcePath:t,targetPath:toSnapshotPathForPlan(e,t)});for(let n of e.copyFiles)existsSync(n)&&await copySnapshotPath({plan:e,sourcePath:n,targetPath:toSnapshotPathForPlan(e,n)});await rewriteSnapshotTsConfigAbsoluteExtends(e),await createSnapshotSymlinks(e),await ensureRuntimePackageJson(e),await validateDevelopmentSourceSnapshot(e)}async function copySnapshotPath(e){try{if((await lstat(e.sourcePath)).isDirectory()){await copySnapshotDirectory(e);return}await mkdir(dirname(e.targetPath),{recursive:!0}),await cp(e.sourcePath,e.targetPath,{mode:SNAPSHOT_COPY_MODE,recursive:!0})}catch(t){throw new DevelopmentRuntimeSourceSnapshotError(`Failed to copy development runtime source snapshot path "${e.sourcePath}" to "${e.targetPath}": ${formatErrorMessage(t)}`)}}async function copySnapshotDirectory(e){await mkdir(e.targetPath,{recursive:!0});for(let t of await readdir(e.sourcePath,{withFileTypes:!0})){let n=join(e.sourcePath,t.name);shouldSkipSnapshotSource(e.plan,n)||await cp(n,join(e.targetPath,t.name),{filter:t=>!shouldSkipSnapshotSource(e.plan,t),mode:SNAPSHOT_COPY_MODE,recursive:!0})}}function shouldSkipSnapshotSource(e,t){let n=relative(e.sourceRoot,t);return n.length===0?!1:n.split(/[\\/]/).some(e=>SNAPSHOT_SKIP_NAMES.has(e)||e.startsWith(`.env`))?!0:isDirectAppRootSkipPath({appRoot:e.appRoot,sourcePath:t})}function isDirectAppRootSkipPath(e){if(!isPathInsideOrEqual(e.sourcePath,e.appRoot))return!1;let t=relative(e.appRoot,e.sourcePath);if(t.length===0)return!1;let n=t.split(/[\\/]/)[0];return n!==void 0&&SNAPSHOT_APP_ROOT_SKIP_NAMES.has(n)}async function rewriteSnapshotTsConfigAbsoluteExtends(e){for(let t of e.tsconfigPaths){let n=await readTextFileIfExists(t);if(n===void 0)continue;let r=rewriteTsConfigAbsoluteExtends({configPath:t,snapshotConfigPath:toSnapshotPathForPlan(e,t),snapshotSourceRoot:e.snapshotSourceRoot,source:n,sourceRoot:e.sourceRoot});r!==void 0&&await writeFile(toSnapshotPathForPlan(e,t),r)}}function rewriteTsConfigAbsoluteExtends(e){let t=parseTsConfigObject(e.source);if(t===void 0)return;let n=rewriteTsConfigExtendsValue({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:t.extends});if(n.changed===!0)return`${JSON.stringify({...t,extends:n.value},null,2)}\n`}function rewriteTsConfigExtendsValue(e){if(typeof e.value==`string`){let t=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:e.value});return t===void 0?{changed:!1,value:e.value}:{changed:!0,value:t}}if(!Array.isArray(e.value))return{changed:!1,value:e.value};let t=!1,n=e.value.map(n=>{if(typeof n!=`string`)return n;let r=rewriteTsConfigExtendsSpecifier({configPath:e.configPath,snapshotConfigPath:e.snapshotConfigPath,snapshotSourceRoot:e.snapshotSourceRoot,sourceRoot:e.sourceRoot,value:n});return r===void 0?n:(t=!0,r)});return{changed:t,value:n}}function rewriteTsConfigExtendsSpecifier(e){if(!isTsConfigFilePath(e.value)||!isAbsoluteFilePath(e.value))return;let t=resolveFirstExistingTsConfigExtendsTarget({configPath:e.configPath,extendsSpecifier:e.value});if(!(t===void 0||!isPathInsideOrEqual(t,e.sourceRoot)))return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}async function createSnapshotSymlinks(e){for(let t of e.symlinks){let r=toSnapshotPathForPlan(e,t.linkPath),i=t.targetKind===`local`?toSnapshotPathForPlan(e,t.targetPath):t.targetPath,a=t.targetKind===`local`?relative(dirname(r),i)||`.`:i;await mkdir(dirname(r),{recursive:!0}),await symlink(a,r,`junction`)}}async function ensureRuntimePackageJson(e){let n=join(e.runtimeAppRoot,`package.json`);existsSync(n)||(await mkdir(e.runtimeAppRoot,{recursive:!0}),await writeFile(n,`${JSON.stringify({private:!0,type:`module`},null,2)}\n`))}async function validateDevelopmentSourceSnapshot(e){let n=join(e.runtimeAppRoot,`package.json`);if(!existsSync(n))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing the runtime app package.json at "${n}".`);for(let n of e.tsconfigPaths){let r=toSnapshotPathForPlan(e,n);if(!existsSync(r))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot is missing tsconfig dependency "${r}".`);await validateSnapshotTsConfigExtends(r)}}async function validateSnapshotTsConfigExtends(e){let n=extractTsConfigExtendsSpecifiers(await readFile(e,`utf8`));for(let r of n)if(!(!isTsConfigFilePath(r)||resolveTsConfigExtendsTargetPaths({configPath:e,extendsSpecifier:r}).some(e=>existsSync(e))))throw new DevelopmentRuntimeSourceSnapshotError(`Development runtime source snapshot cannot resolve tsconfig extends "${r}" from "${e}".`)}function toSnapshotPathForPlan(e,t){return toDevelopmentSourceSnapshotPath({snapshotSourceRoot:e.snapshotSourceRoot,sourcePath:t,sourceRoot:e.sourceRoot})}function isPathInsideOrEqual(e,t){let n=resolve(e),r=resolve(t);return n===r||n.startsWith(`${r}${sep}`)}function isAbsoluteFilePath(e){return e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)}function formatErrorMessage(e){return e instanceof Error?e.message:String(e)}export{copyDevelopmentSourceSnapshot};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN,EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH,EVE_HEALTH_ROUTE_PATH}from"#protocol/routes.js";import{resolvePackageRoot,resolvePackageSourceFilePath,resolveWorkflowModulePath}from"#internal/application/package.js";import{dirname,join,relative}from"node:path";import{mkdir,writeFile}from"node:fs/promises";import{isVercelBuildEnvironment}from"#internal/application/paths.js";import{normalizeEsmImportSpecifier,stringifyEsmImportSpecifier}from"#internal/application/import-specifier.js";import{WorkflowBundleBuilder}from"#internal/workflow-bundle/builder.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{deriveEveWorkflowQueuePrefix}from"#internal/workflow/queue-namespace.js";import{computeChannelRouteRegistrations,registerChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";function includesApplicationRoutes(e){return e===`all`||e===`app`}function includesWorkflowBundles(e){return includesWorkflowRoute(e)}function includesWorkflowRoute(e){return e===`all`||e===`flow`}function registerHandler(e,t){let n=`#eve-route-handler/${t.method??`ALL`} ${t.route}`,r=stringifyEsmImportSpecifier(t.handlerPath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import handler from ${r};`,`export default handler;`].join(`
|
|
2
2
|
`)}function resolveNitroWorkflowBuildDirectory(e){return join(e.options.buildDir,`workflow`)}function createRelativeImportSpecifier(e,t){let n=relative(e,t).replaceAll(`\\`,`/`);return n.startsWith(`.`)?n:`./${n}`}async function addWorkflowFileHandler(e,t){let n=join(resolveNitroWorkflowBuildDirectory(e),`${t.bundleName}-handler.mjs`),r=dirname(n),i=createRelativeImportSpecifier(r,t.bundlePath),a=(t.directHandlers??[]).map(e=>{let t=createRelativeImportSpecifier(r,e.bundlePath);return{importSpecifier:t,isOwnBundle:t===i,queuePrefix:e.queuePrefix}});await mkdir(r,{recursive:!0}),await writeFile(n,buildWorkflowFileHandlerSource({bundlePath:i,directHandlers:a,runtimeImportSpecifier:t.runtimeImportSpecifier})),e.options.handlers.push({handler:n,route:t.route})}function buildWorkflowFileHandlerSource(e){let t=[`// Generated by eve. Do not edit by hand.`,`import { POST } from ${JSON.stringify(e.bundlePath)};`];if(e.directHandlers.length>0&&e.runtimeImportSpecifier!==void 0){let n=0,r=e.directHandlers.map(e=>{if(e.isOwnBundle)return{...e,binding:`POST`};let t=`__eveWorkflowDirectHandler${n}`;return n+=1,{...e,binding:t}});for(let e of r)e.isOwnBundle||t.push(`import { POST as ${e.binding} } from ${JSON.stringify(e.importSpecifier)};`);t.push(`import { getWorld as __eveGetWorkflowWorld } from ${JSON.stringify(e.runtimeImportSpecifier)};`,``,`try {`,` const __eveWorkflowWorld = await __eveGetWorkflowWorld();`,` if (typeof __eveWorkflowWorld?.registerHandler === "function") {`);for(let e of r)t.push(` __eveWorkflowWorld.registerHandler(${JSON.stringify(e.queuePrefix)}, ${e.binding});`);t.push(` }`,`} catch (err) {`,` console.warn("[eve] Failed to register direct workflow queue handlers:", err);`,`}`)}return t.push(``,`export default async ({ req }) => {`,` return await POST(req);`,`};`,``),t.join(`
|
|
3
3
|
`)}function addFrameworkVirtualHandler(e,t){let n=`#eve-route${t.route}`,r=stringifyEsmImportSpecifier(t.modulePath);e.options.handlers.push({handler:n,method:t.method,route:t.route}),e.options.virtual[n]=[`import { ${t.handlerExport} } from ${r};`,`export default async (event) => ${t.handlerExport}(${t.args}, event.req);`].join(`
|
|
4
|
-
`)}async function configureNitroRoutes(o,s,c){if(includesWorkflowBundles(c.surface)){let e=resolvePackageRoot(),t=new WorkflowBundleBuilder({agentName:s.compileResult.manifest.config.name,appRoot:s.appRoot,compiledArtifactsBootstrapPath:s.compiledArtifacts.bootstrapPath,outDir:s.workflowBuildDir,rootDir:e,watch:o.options.dev}),n=Promise.resolve(),buildWorkflowArtifacts=async()=>{await t.build({nitroStepOutfile:includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`steps.mjs`):void 0,nitroWorkflowOutfile:o.options.dev&&includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`workflows.mjs`):void 0})},syncWorkflowArtifacts=async()=>{let e=n.then(buildWorkflowArtifacts);n=e.catch(()=>{}),await e},i=!0;await syncWorkflowArtifacts(),o.hooks.hook(`build:before`,async()=>{if(i){i=!1;return}await syncWorkflowArtifacts()}),o.options.dev&&o.hooks.hook(`dev:reload`,async()=>{await syncWorkflowArtifacts()})}let l=createNitroArtifactsConfig({appRoot:s.appRoot,dev:o.options.dev});if(includesApplicationRoutes(c.surface)){
|
|
4
|
+
`)}async function configureNitroRoutes(o,s,c){if(includesWorkflowBundles(c.surface)){let e=resolvePackageRoot(),t=new WorkflowBundleBuilder({agentName:s.compileResult.manifest.config.name,appRoot:s.appRoot,compiledArtifactsBootstrapPath:s.compiledArtifacts.bootstrapPath,outDir:s.workflowBuildDir,rootDir:e,watch:o.options.dev}),n=Promise.resolve(),buildWorkflowArtifacts=async()=>{await t.build({nitroStepOutfile:includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`steps.mjs`):void 0,nitroWorkflowOutfile:o.options.dev&&includesWorkflowRoute(c.surface)?join(resolveNitroWorkflowBuildDirectory(o),`workflows.mjs`):void 0})},syncWorkflowArtifacts=async()=>{let e=n.then(buildWorkflowArtifacts);n=e.catch(()=>{}),await e},i=!0;await syncWorkflowArtifacts(),o.hooks.hook(`build:before`,async()=>{if(i){i=!1;return}await syncWorkflowArtifacts()}),o.options.dev&&o.hooks.hook(`dev:reload`,async()=>{await syncWorkflowArtifacts()})}let l=createNitroArtifactsConfig({appRoot:s.appRoot,dev:o.options.dev});if(includesApplicationRoutes(c.surface)){addFrameworkVirtualHandler(o,{args:JSON.stringify({agentName:s.compileResult.manifest.config.name}),handlerExport:`handleHomePageRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/index.ts`),route:`/`});for(let e of[`GET`,`HEAD`])registerHandler(o,{handlerPath:resolvePackageSourceFilePath(`src/internal/nitro/routes/health.ts`),method:e,route:EVE_HEALTH_ROUTE_PATH});registerChannelVirtualHandlers(o,{artifactsConfig:l,registrations:computeChannelRouteRegistrations(s)}),o.options.dev&&(addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevRuntimeArtifactsRequest`,method:`GET`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-runtime-artifacts.ts`),route:EVE_DEV_RUNTIME_ARTIFACTS_ROUTE_PATH}),addFrameworkVirtualHandler(o,{args:JSON.stringify({appRoot:l.appRoot}),handlerExport:`handleDevScheduleDispatchRequest`,method:`POST`,modulePath:resolvePackageSourceFilePath(`src/internal/nitro/routes/dev-schedule-dispatch.ts`),route:EVE_DEV_DISPATCH_SCHEDULE_ROUTE_PATTERN}))}let u=resolveNitroWorkflowBuildDirectory(o),d=includesWorkflowRoute(c.surface)?o.options.dev?join(u,`workflows.mjs`):join(s.workflowBuildDir,`workflows.mjs`):void 0,f=s.compileResult.manifest.config.experimental?.workflow?.world!==void 0,p=(o.options.dev||!isVercelBuildEnvironment()&&f)&&d!==void 0?[{bundlePath:d,queuePrefix:deriveEveWorkflowQueuePrefix(s.compileResult.manifest.config.name)}]:[],m=p.length>0?normalizeEsmImportSpecifier(resolveWorkflowModulePath(`workflow/runtime`)):void 0;d&&await addWorkflowFileHandler(o,{bundleName:`workflows`,bundlePath:d,directHandlers:p,route:`/.well-known/workflow/v1/flow`,runtimeImportSpecifier:m}),o.routing.sync()}export{configureNitroRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{clearCompiledRuntimeAgentBundleCache}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,o=!1,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),p=waitForWatcherReady(f),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t,u=hasSandboxRelatedChange(l.compileResult.project.agentRoot,o),p=hasDevelopmentEnvironmentFileChange(l.appRoot,o);r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{p&&loadDevelopmentEnvironmentFiles(l.appRoot);let n=await prepareApplicationHost(l.appRoot,{dev:e.nitro.options.dev===!0})
|
|
1
|
+
import{existsSync}from"node:fs";import{dirname,join,relative,resolve}from"node:path";import{toErrorMessage}from"#shared/errors.js";import{getDevelopmentEnvironmentFilePaths,loadDevelopmentEnvironmentFiles}from"#cli/dev/environment.js";import{startDevelopmentSandboxPrewarmInBackground}from"#execution/sandbox/development-prewarm.js";import{AUTHORED_ARTIFACTS_UPDATED_LOG_LINE,STRUCTURAL_RELOAD_LOG_LINE,formatChangeDetectedLogLine}from"#internal/nitro/host/dev-watcher-log.js";import{clearCompiledRuntimeAgentBundleCache}from"#runtime/sessions/compiled-agent-cache.js";import{resolveDevelopmentSourceSnapshotWatchPaths}from"#internal/nitro/dev-runtime-source-snapshot.js";import{resolveTsConfigDependencyPaths}from"#internal/application/tsconfig-dependencies.js";import{pruneDevelopmentRuntimeArtifactsSnapshotsInBackground}from"#internal/nitro/dev-runtime-artifacts.js";import{prepareApplicationHost}from"#internal/nitro/host/prepare-application-host.js";import{createNitroArtifactsConfig}from"#internal/nitro/host/artifacts-config.js";import{computeChannelRouteRegistrations,syncChannelVirtualHandlers}from"#internal/nitro/host/channel-routes.js";import{watch}from"#compiled/chokidar/index.js";import{resolveNitroCompiledArtifactsSource}from"#internal/nitro/routes/runtime-artifacts.js";const WATCHED_LOCKFILE_NAMES=[`pnpm-lock.yaml`,`package-lock.json`,`yarn.lock`,`bun.lock`,`bun.lockb`],WATCH_ROOT_MARKER_NAMES=[`.git`,`pnpm-workspace.yaml`],WATCHER_IGNORED_DIRECTORY_NAMES=new Set([`.generated`,`.eve`,`.git`,`.next`,`.output`,`.turbo`,`.vercel`,`.workflow-data`,`build`,`dist`,`node_modules`]);async function startAuthoredSourceWatcher(e){let t=e.preparedHost,n=!1,r=Promise.resolve(),i,o=!1,s=new Map,c=new Set,u=await resolveAuthoredWatchPaths(t),d=createWatchPathMap(u),f=watch(u,{awaitWriteFinish:{pollInterval:50,stabilityThreshold:160},followSymlinks:!1,ignoreInitial:!0,ignored:shouldIgnoreWatcherPath}),p=waitForWatcherReady(f),rebuild=async i=>{n||(r=r.then(async()=>{if(n)return;let r=[...s.values()];if(!i&&r.length===0)return;let o=[...c];s.clear(),c.clear();let l=t,u=hasSandboxRelatedChange(l.compileResult.project.agentRoot,o),p=hasDevelopmentEnvironmentFileChange(l.appRoot,o);r.length>0&&console.log(formatChangeDetectedLogLine(l.appRoot,r));try{p&&loadDevelopmentEnvironmentFiles(l.appRoot);let n=await prepareApplicationHost(l.appRoot,{dev:e.nitro.options.dev===!0});e.nitro.options.dev===!0&&pruneDevelopmentRuntimeArtifactsSnapshotsInBackground(n.appRoot);let r=createNitroArtifactsConfig({appRoot:n.appRoot,dev:e.nitro.options.dev===!0});u&&startDevelopmentSandboxPrewarmInBackground({appRoot:n.appRoot,compiledArtifactsSource:resolveNitroCompiledArtifactsSource(r),log:e=>console.log(e)});let i=syncChannelVirtualHandlers(e.nitro,{artifactsConfig:r,next:computeChannelRouteRegistrations(n),previous:computeChannelRouteRegistrations(l)});clearCompiledRuntimeAgentBundleCache(),t=n,i||p?(console.log(STRUCTURAL_RELOAD_LOG_LINE),await e.nitro.hooks.callHook(`rollup:reload`)):console.log(AUTHORED_ARTIFACTS_UPDATED_LOG_LINE),d=syncWatcherPaths({nextWatchPaths:await resolveAuthoredWatchPaths(n),previousWatchPathsByKey:d,watcher:f})}catch(e){console.error(`[eve:dev] rebuild failed: ${toErrorMessage(e)}`)}}).catch(e=>{console.error(`[eve:dev] rebuild queue error: ${toErrorMessage(e)}`)}),await r)},flush=async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!1)};return f.on(`all`,(e,t)=>{n||!o||(s.set(`${e}:${t}`,{event:e,path:t}),c.add(t),i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,flush()},120))}),await p,o=!0,{async close(){n=!0,i!==void 0&&(clearTimeout(i),i=void 0),await f.close(),await r},flush,rebuild:async()=>{i!==void 0&&(clearTimeout(i),i=void 0),await rebuild(!0)}}}async function waitForWatcherReady(e){await new Promise((t,n)=>{e.on(`ready`,()=>{t()}),e.on(`error`,e=>{n(e)})})}async function resolveAuthoredWatchPaths(e){let t=new Set([e.compileResult.project.agentRoot,join(e.appRoot,`package.json`),join(e.appRoot,`jsconfig.json`),join(e.appRoot,`tsconfig.json`),join(e.appRoot,`tsconfig.*.json`)]),r=await resolveTsConfigWatchPaths(e.appRoot),i=await resolveDevelopmentSourceSnapshotWatchPaths(e.appRoot);for(let n of getDevelopmentEnvironmentFilePaths(e.appRoot))t.add(n);for(let e of i)t.add(e);for(let e of r)t.add(e);for(let r of resolveLockfileSearchDirectories(e.appRoot))for(let e of WATCHED_LOCKFILE_NAMES)t.add(join(r,e));return[...t].sort((e,t)=>e.localeCompare(t))}function createWatchPathMap(e){let t=new Map;for(let n of e)t.set(toWatchPathKey(n),n);return t}function syncWatcherPaths(e){let t=createWatchPathMap(e.nextWatchPaths),n=[],r=[];for(let[r,i]of t)e.previousWatchPathsByKey.has(r)||n.push(i);for(let[n,i]of e.previousWatchPathsByKey)t.has(n)||r.push(i);return n.length>0&&e.watcher.add(n),r.length>0&&e.watcher.unwatch(r),t}function toWatchPathKey(e){return e.replaceAll(`\\`,`/`)}function hasDevelopmentEnvironmentFileChange(e,t){let n=new Set(getDevelopmentEnvironmentFilePaths(e).map(e=>toWatchPathKey(resolve(e))));return t.some(e=>n.has(toWatchPathKey(resolve(e))))}function hasSandboxRelatedChange(e,t){return t.some(t=>{let n=toAgentRelativePath(e,t);return n===`sandbox.ts`||n.startsWith(`sandbox/`)||n===`workspace`||n.startsWith(`workspace/`)||n===`skills`||n.startsWith(`skills/`)})}function toAgentRelativePath(e,t){let n=toWatchPathKey(relative(resolve(e),resolve(t)));return n===`..`||n.startsWith(`../`)||n===``?``:n}function resolveLockfileSearchDirectories(e){let n=resolve(e),r=[n],a=n;for(;;){if(hasWatchRootMarker(a))return r;let e=dirname(a);if(e===a)return[n];a=e,r.push(a)}}function hasWatchRootMarker(t){return WATCH_ROOT_MARKER_NAMES.some(r=>existsSync(join(t,r)))}async function resolveTsConfigWatchPaths(e){return await resolveTsConfigDependencyPaths(e)}function shouldIgnoreWatcherPath(e){return e.replaceAll(`\\`,`/`).split(`/`).filter(Boolean).some(e=>WATCHER_IGNORED_DIRECTORY_NAMES.has(e))}export{startAuthoredSourceWatcher};
|
|
@@ -4,9 +4,14 @@ import type { H3Event } from "nitro";
|
|
|
4
4
|
* for tests so callers can supply a real {@link Request}; production
|
|
5
5
|
* traffic flows through the Nitro {@link H3Event} default export.
|
|
6
6
|
*/
|
|
7
|
-
export declare function buildHomePageResponse(
|
|
7
|
+
export declare function buildHomePageResponse(input: {
|
|
8
|
+
readonly agentName: string;
|
|
9
|
+
}, request: Request): Response;
|
|
8
10
|
/**
|
|
9
11
|
* Nitro route handler for `GET /`. Adapts the Nitro event shape into
|
|
10
12
|
* {@link buildHomePageResponse}.
|
|
11
13
|
*/
|
|
12
|
-
export
|
|
14
|
+
export declare function handleHomePageRequest(input: {
|
|
15
|
+
readonly agentName: string;
|
|
16
|
+
}, request: Request): Response;
|
|
17
|
+
export default function handleStaticHomePageRequest(event: H3Event): Response;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,HOME_PAGE_HTML_TEMPLATE=`<!doctype html>
|
|
1
|
+
const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,AGENT_NAME_PLACEHOLDER=`{{AGENT_NAME}}`,HOME_PAGE_HTML_TEMPLATE=`<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
@@ -14,24 +14,20 @@ const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,HOME_PAGE_HTML_TEMPLATE=`<
|
|
|
14
14
|
--muted: #6b6b6b;
|
|
15
15
|
--faint: #999;
|
|
16
16
|
--border: rgba(0, 0, 0, 0.09);
|
|
17
|
-
--surface: rgba(0, 0, 0, 0.025);
|
|
18
17
|
--accent: #00c46a;
|
|
19
|
-
--
|
|
20
|
-
--
|
|
21
|
-
--button-fg: #fff;
|
|
18
|
+
--divider: rgba(0, 0, 0, 0.22);
|
|
19
|
+
--brand-opacity: 0.08;
|
|
22
20
|
}
|
|
23
21
|
@media (prefers-color-scheme: dark) {
|
|
24
22
|
:root {
|
|
25
|
-
--bg: #
|
|
26
|
-
--fg: #
|
|
27
|
-
--muted: #
|
|
28
|
-
--faint: #
|
|
29
|
-
--border: rgba(255, 255, 255, 0.
|
|
30
|
-
--surface: rgba(255, 255, 255, 0.035);
|
|
23
|
+
--bg: #0a0a0a;
|
|
24
|
+
--fg: #f5f5f5;
|
|
25
|
+
--muted: #a3a3a3;
|
|
26
|
+
--faint: #737373;
|
|
27
|
+
--border: rgba(255, 255, 255, 0.14);
|
|
31
28
|
--accent: #46d4a4;
|
|
32
|
-
--
|
|
33
|
-
--
|
|
34
|
-
--button-fg: #000;
|
|
29
|
+
--divider: rgba(255, 255, 255, 0.22);
|
|
30
|
+
--brand-opacity: 0.12;
|
|
35
31
|
}
|
|
36
32
|
}
|
|
37
33
|
* { box-sizing: border-box; }
|
|
@@ -58,40 +54,71 @@ const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,HOME_PAGE_HTML_TEMPLATE=`<
|
|
|
58
54
|
}
|
|
59
55
|
main {
|
|
60
56
|
width: 100%;
|
|
61
|
-
max-width:
|
|
62
|
-
text-align:
|
|
57
|
+
max-width: 28rem;
|
|
58
|
+
text-align: left;
|
|
59
|
+
display: flex;
|
|
60
|
+
flex-direction: column;
|
|
61
|
+
align-items: stretch;
|
|
62
|
+
gap: 1.5rem;
|
|
63
|
+
}
|
|
64
|
+
.brand {
|
|
65
|
+
margin: 0;
|
|
66
|
+
display: flex;
|
|
67
|
+
justify-content: flex-start;
|
|
68
|
+
color: var(--fg);
|
|
69
|
+
opacity: var(--brand-opacity);
|
|
70
|
+
}
|
|
71
|
+
.logo {
|
|
72
|
+
display: block;
|
|
73
|
+
width: 4.875rem;
|
|
74
|
+
height: auto;
|
|
75
|
+
}
|
|
76
|
+
.panel {
|
|
77
|
+
display: flex;
|
|
78
|
+
flex-direction: column;
|
|
79
|
+
gap: 0.625rem;
|
|
80
|
+
}
|
|
81
|
+
.agent-row {
|
|
82
|
+
display: flex;
|
|
83
|
+
align-items: center;
|
|
84
|
+
gap: 0.9375rem;
|
|
85
|
+
min-width: 0;
|
|
86
|
+
}
|
|
87
|
+
.agent-name {
|
|
88
|
+
color: var(--fg);
|
|
89
|
+
font-size: 0.875rem;
|
|
90
|
+
font-weight: 500;
|
|
91
|
+
line-height: 1.55;
|
|
92
|
+
overflow: hidden;
|
|
93
|
+
text-overflow: ellipsis;
|
|
94
|
+
white-space: nowrap;
|
|
63
95
|
}
|
|
64
96
|
.status {
|
|
65
97
|
display: inline-flex;
|
|
66
98
|
align-items: center;
|
|
67
99
|
gap: 0.5rem;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
font-size: 0.75rem;
|
|
73
|
-
color: var(--muted);
|
|
74
|
-
margin: 0 0 2rem;
|
|
100
|
+
font-size: inherit;
|
|
101
|
+
line-height: inherit;
|
|
102
|
+
color: var(--accent);
|
|
103
|
+
margin: 0;
|
|
75
104
|
}
|
|
76
105
|
.status-dot {
|
|
77
|
-
width:
|
|
78
|
-
height:
|
|
106
|
+
width: 5px;
|
|
107
|
+
height: 5px;
|
|
79
108
|
border-radius: 50%;
|
|
80
109
|
background: var(--accent);
|
|
81
|
-
box-shadow: 0 0 0 3px var(--accent-glow);
|
|
82
110
|
flex-shrink: 0;
|
|
83
111
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
font-size: clamp(2.5rem, 9vw, 3.25rem);
|
|
87
|
-
font-weight: 500;
|
|
88
|
-
letter-spacing: -0.05em;
|
|
89
|
-
line-height: 1;
|
|
112
|
+
.lede-divider {
|
|
113
|
+
color: var(--divider);
|
|
90
114
|
}
|
|
91
115
|
.lede {
|
|
92
|
-
|
|
116
|
+
display: flex;
|
|
117
|
+
align-items: center;
|
|
118
|
+
gap: 0.5rem;
|
|
119
|
+
margin: 0;
|
|
93
120
|
color: var(--muted);
|
|
94
|
-
font-size: 0.
|
|
121
|
+
font-size: 0.875rem;
|
|
95
122
|
}
|
|
96
123
|
.lede a {
|
|
97
124
|
color: var(--fg);
|
|
@@ -115,13 +142,12 @@ const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,HOME_PAGE_HTML_TEMPLATE=`<
|
|
|
115
142
|
gap: 0.625rem;
|
|
116
143
|
width: 100%;
|
|
117
144
|
max-width: 28rem;
|
|
118
|
-
padding: 0.
|
|
119
|
-
background: var(--surface);
|
|
145
|
+
padding: 0.8125rem 1.0625rem;
|
|
120
146
|
border: 1px solid var(--border);
|
|
121
147
|
border-radius: 0.5rem;
|
|
122
148
|
text-align: left;
|
|
123
149
|
font-size: 0.8125rem;
|
|
124
|
-
margin: 0
|
|
150
|
+
margin: 1rem 0 0;
|
|
125
151
|
overflow-x: auto;
|
|
126
152
|
white-space: nowrap;
|
|
127
153
|
}
|
|
@@ -135,17 +161,21 @@ const DEPLOYMENT_URL_PLACEHOLDER=`{{DEPLOYMENT_URL}}`,HOME_PAGE_HTML_TEMPLATE=`<
|
|
|
135
161
|
</head>
|
|
136
162
|
<body>
|
|
137
163
|
<main>
|
|
138
|
-
<
|
|
139
|
-
<
|
|
140
|
-
|
|
141
|
-
</
|
|
142
|
-
<
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
<span class="
|
|
147
|
-
|
|
164
|
+
<div class="brand" aria-label="eve"><svg aria-hidden="true" class="logo" fill="none" viewBox="0 0 169 53" xmlns="http://www.w3.org/2000/svg">
|
|
165
|
+
<path d="M169 8.47h-51.39L81.73 53H70.36L113 0H169zM169 44.51v8.47h-45.87V44.5zM45.87 52.98H0V44.5h45.87zM38.66 30.55H0v-8.47h38.66z" fill="currentColor"></path>
|
|
166
|
+
<path d="M169 30.55h-38.66v-8.47H169zM75.52 8.47H0V0h75.52z" fill="currentColor"></path>
|
|
167
|
+
</svg></div>
|
|
168
|
+
<section class="panel" aria-label="Agent status">
|
|
169
|
+
<div class="agent-row">
|
|
170
|
+
<strong class="agent-name">${AGENT_NAME_PLACEHOLDER}</strong>
|
|
171
|
+
</div>
|
|
172
|
+
<p class="lede"><span class="status"><span class="status-dot" aria-hidden="true"></span>Ready</span><span class="lede-divider" aria-hidden="true">/</span><span>Agent is up and accepting messages.</span> <a href="https://eve.dev/docs">Docs<span class="lede-arrow" aria-hidden="true"> →</span></a></p>
|
|
173
|
+
<div class="terminal mono" role="group" aria-label="Send a message from your terminal">
|
|
174
|
+
<span class="terminal-prompt" aria-hidden="true">$</span>
|
|
175
|
+
<span class="terminal-cmd">eve dev ${DEPLOYMENT_URL_PLACEHOLDER}</span>
|
|
176
|
+
</div>
|
|
177
|
+
</section>
|
|
148
178
|
</main>
|
|
149
179
|
</body>
|
|
150
180
|
</html>
|
|
151
|
-
`;function escapeHtml(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function pickFirstForwardedValue(e){if(e===null)return;let t=e.split(`,`)[0]?.trim();if(!(t===void 0||t.length===0))return t}function resolveDeploymentUrl(e){let t=e.headers,n=new URL(e.url),r=pickFirstForwardedValue(t.get(`x-forwarded-host`)),i=pickFirstForwardedValue(t.get(`x-forwarded-proto`)),a=r??t.get(`host`)??n.host;return`${i??n.protocol.replace(/:$/,``)}://${a}`}function buildHomePageResponse(
|
|
181
|
+
`;function escapeHtml(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`)}function pickFirstForwardedValue(e){if(e===null)return;let t=e.split(`,`)[0]?.trim();if(!(t===void 0||t.length===0))return t}function resolveDeploymentUrl(e){let t=e.headers,n=new URL(e.url),r=pickFirstForwardedValue(t.get(`x-forwarded-host`)),i=pickFirstForwardedValue(t.get(`x-forwarded-proto`)),a=r??t.get(`host`)??n.host;return`${i??n.protocol.replace(/:$/,``)}://${a}`}function buildHomePageResponse(r,i){let a=resolveDeploymentUrl(i),o=HOME_PAGE_HTML_TEMPLATE.replace(AGENT_NAME_PLACEHOLDER,()=>escapeHtml(r.agentName)).replace(DEPLOYMENT_URL_PLACEHOLDER,()=>escapeHtml(a));return new Response(o,{headers:{"cache-control":`no-store`,"content-type":`text/html; charset=utf-8`}})}function handleHomePageRequest(e,t){return buildHomePageResponse(e,t)}function handleStaticHomePageRequest(e){return buildHomePageResponse({agentName:`eve`},e.req)}export{buildHomePageResponse,handleStaticHomePageRequest as default,handleHomePageRequest};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
+
import type { ActionEvent, Adapter, ChatConfig, SerializedThread, Thread, WebhookOptions } from "#compiled/chat/index.js";
|
|
3
|
+
import { Chat } from "#compiled/chat/index.js";
|
|
4
|
+
import { type Channel, type ChannelEvents, type ChannelSessionOps, type SendFn, type SendOptions, type Session } from "#public/definitions/defineChannel.js";
|
|
5
|
+
type ChatSdkAdapters = Record<string, Adapter>;
|
|
6
|
+
type ChatSdkSendInput = Parameters<SendFn<ChatSdkChannelState>>[0];
|
|
7
|
+
/**
|
|
8
|
+
* Durable channel state used by `chatSdkChannel`. Stores the last Chat SDK
|
|
9
|
+
* thread for the Eve session so event handlers can post replies without
|
|
10
|
+
* depending on hidden Chat SDK subscription state.
|
|
11
|
+
*/
|
|
12
|
+
export interface ChatSdkChannelState extends Record<string, unknown> {
|
|
13
|
+
thread: SerializedThread | null;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Thread selector accepted by `chatSdkChannel().receive`. Pass a serialized
|
|
17
|
+
* Chat SDK thread when possible; `threadId` plus `adapterName` is supported for
|
|
18
|
+
* proactive sends that only have a provider-native thread id.
|
|
19
|
+
*/
|
|
20
|
+
export interface ChatSdkReceiveTarget {
|
|
21
|
+
readonly adapterName?: string;
|
|
22
|
+
readonly thread?: SerializedThread;
|
|
23
|
+
readonly threadId?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Channel-owned metadata exposed to Eve instrumentation.
|
|
27
|
+
*/
|
|
28
|
+
export interface ChatSdkInstrumentationMetadata extends Record<string, unknown> {
|
|
29
|
+
readonly adapterName: string | null;
|
|
30
|
+
readonly channelId: string | null;
|
|
31
|
+
readonly isDM: boolean | null;
|
|
32
|
+
readonly threadId: string | null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Per-session context passed to `chatSdkChannel({ events })` handlers. `thread`
|
|
36
|
+
* is rebuilt from persisted channel state using the configured Chat SDK
|
|
37
|
+
* adapter, so default handlers can post back to the originating chat thread.
|
|
38
|
+
*/
|
|
39
|
+
export interface ChatSdkChannelContext<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> {
|
|
40
|
+
readonly bot: Chat<TAdapters>;
|
|
41
|
+
readonly thread: Thread | null;
|
|
42
|
+
state: ChatSdkChannelState;
|
|
43
|
+
}
|
|
44
|
+
/** Event-handler context for `chatSdkChannel`, including Eve session helpers. */
|
|
45
|
+
export interface ChatSdkEventContext<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> extends ChatSdkChannelContext<TAdapters>, ChannelSessionOps {
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Per-event handlers for `chatSdkChannel({ events })`. Each supplied handler
|
|
49
|
+
* replaces the built-in default for that event.
|
|
50
|
+
*/
|
|
51
|
+
export type ChatSdkChannelEvents<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> = ChannelEvents<ChatSdkChannelContext<TAdapters>>;
|
|
52
|
+
/**
|
|
53
|
+
* Options for `bridge.send(...)` inside Chat SDK handlers. The `thread`
|
|
54
|
+
* determines the Eve continuation token and the persisted channel state.
|
|
55
|
+
*/
|
|
56
|
+
export interface ChatSdkSendOptions {
|
|
57
|
+
readonly auth?: SessionAuthContext | null;
|
|
58
|
+
readonly callback?: SendOptions<ChatSdkChannelState>["callback"];
|
|
59
|
+
readonly mode?: SendOptions<ChatSdkChannelState>["mode"];
|
|
60
|
+
readonly thread: SerializedThread | Thread | string;
|
|
61
|
+
readonly title?: string;
|
|
62
|
+
/**
|
|
63
|
+
* Required when `thread` is a string that does not include the Chat SDK
|
|
64
|
+
* adapter prefix. Prefer passing the `Thread` object from the Chat SDK handler
|
|
65
|
+
* when possible.
|
|
66
|
+
*/
|
|
67
|
+
readonly adapterName?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Configuration for {@link chatSdkChannel}. It accepts normal Chat SDK
|
|
71
|
+
* `ChatConfig` fields, plus Eve route and event settings.
|
|
72
|
+
*/
|
|
73
|
+
export interface ChatSdkChannelConfig<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> extends Omit<ChatConfig<TAdapters>, "adapters"> {
|
|
74
|
+
/** Map of Chat SDK adapter name to adapter instance. */
|
|
75
|
+
readonly adapters: TAdapters;
|
|
76
|
+
/**
|
|
77
|
+
* Base route for generated adapter webhooks. Defaults to `/eve/v1/chat`, so
|
|
78
|
+
* an adapter named `slack` mounts at `/eve/v1/chat/slack`.
|
|
79
|
+
*/
|
|
80
|
+
readonly route?: string;
|
|
81
|
+
/**
|
|
82
|
+
* Per-adapter route overrides. Use when a provider requires a fixed webhook
|
|
83
|
+
* URL or when migrating an existing endpoint without changing provider
|
|
84
|
+
* settings.
|
|
85
|
+
*/
|
|
86
|
+
readonly routes?: Partial<Record<Extract<keyof TAdapters, string>, string>>;
|
|
87
|
+
/** Extra Chat SDK webhook options. Eve owns `waitUntil`. */
|
|
88
|
+
readonly webhook?: Omit<WebhookOptions, "waitUntil">;
|
|
89
|
+
/** Optional Eve event handlers. Supplied handlers replace built-in defaults. */
|
|
90
|
+
readonly events?: ChatSdkChannelEvents<TAdapters>;
|
|
91
|
+
/**
|
|
92
|
+
* Prefix for default Eve HITL button action ids. Change this if your Chat SDK
|
|
93
|
+
* app already uses the `eve_input:` prefix.
|
|
94
|
+
*/
|
|
95
|
+
readonly inputActionPrefix?: string;
|
|
96
|
+
/**
|
|
97
|
+
* Auth resolver for default HITL button clicks. Defaults to `null`; provide a
|
|
98
|
+
* resolver when continued sessions should keep user or tenant auth.
|
|
99
|
+
*/
|
|
100
|
+
readonly resolveInputAuth?: (event: ActionEvent) => SessionAuthContext | null | Promise<SessionAuthContext | null>;
|
|
101
|
+
}
|
|
102
|
+
/** Concrete channel value returned on `bridge.channel`. */
|
|
103
|
+
export interface ChatSdkChannel extends Channel<ChatSdkChannelState, ChatSdkReceiveTarget, ChatSdkInstrumentationMetadata> {
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Return value of {@link chatSdkChannel}. Export `channel` from
|
|
107
|
+
* `agent/channels/<name>.ts`, then register handlers on `bot` and call `send`
|
|
108
|
+
* from those handlers to hand work to Eve.
|
|
109
|
+
*/
|
|
110
|
+
export interface ChatSdkChannelBridge<TAdapters extends ChatSdkAdapters = ChatSdkAdapters> {
|
|
111
|
+
readonly bot: Chat<TAdapters>;
|
|
112
|
+
readonly channel: ChatSdkChannel;
|
|
113
|
+
/**
|
|
114
|
+
* Starts or resumes an Eve session from inside a Chat SDK webhook handler.
|
|
115
|
+
* Use `channel.receive(...)` for proactive sends that are not handling an
|
|
116
|
+
* inbound Chat SDK webhook.
|
|
117
|
+
*/
|
|
118
|
+
send(input: ChatSdkSendInput, options: ChatSdkSendOptions): Promise<Session>;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Creates an Eve channel backed by one Chat SDK runtime and its adapters.
|
|
122
|
+
*
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* import { createSlackAdapter } from "@chat-adapter/slack";
|
|
126
|
+
* import { createMemoryState } from "@chat-adapter/state-memory";
|
|
127
|
+
* import { chatSdkChannel } from "eve/channels/chat-sdk";
|
|
128
|
+
*
|
|
129
|
+
* export const { bot, channel, send } = chatSdkChannel({
|
|
130
|
+
* userName: "acme",
|
|
131
|
+
* adapters: { slack: createSlackAdapter() },
|
|
132
|
+
* state: createMemoryState(),
|
|
133
|
+
* });
|
|
134
|
+
*
|
|
135
|
+
* bot.onNewMention(async (thread, message) => {
|
|
136
|
+
* await send(message.text, { thread });
|
|
137
|
+
* });
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
export declare function chatSdkChannel<TAdapters extends ChatSdkAdapters>(config: ChatSdkChannelConfig<TAdapters>): ChatSdkChannelBridge<TAdapters>;
|
|
141
|
+
export {};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{createLogger,extractErrorId,formatErrorHint}from"#internal/logging.js";import{ContextContainer,contextStorage}from"#context/container.js";import{ContextKey}from"#context/key.js";import{Actions,Button,Card,CardText,Chat,Message,ThreadImpl}from"#compiled/chat/index.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";const log=createLogger(`chat-sdk.channel`),ActiveWebhookKey=new ContextKey(`chat-sdk.active-webhook`);function chatSdkChannel(e){let t=new Chat(e),n=e.inputActionPrefix??`eve_input:`,a={...defaultEvents(n),...e.events};return t.onAction(async r=>{let i=decodeInputAction(r.actionId,n,r.value);if(i){if(!r.thread)throw Error(`chatSdkChannel input actions require a thread on the Chat SDK action event.`);await bridgeSend(t,{inputResponses:[i]},{auth:e.resolveInputAuth?await e.resolveInputAuth(r):null,thread:r.thread})}}),{bot:t,channel:defineChannel({kindHint:`chat-sdk`,state:initialState(),metadata:metadataFromState,context(e){return{bot:t,state:e,thread:threadFromState(t,e)}},routes:adapterNames(e.adapters).map(n=>POST(routeForAdapter(n,e),async(a,o)=>{let s=t.webhooks[n],c=new ContextContainer;return c.setVirtualContext(ActiveWebhookKey,{send:o.send}),contextStorage.run(c,()=>s(a,{...e.webhook,waitUntil(e){o.waitUntil(e)}}))})),async receive(e,{send:n}){let r=serializeReceiveTarget(t,e.target);return n(e.message,{auth:e.auth,continuationToken:r.id,state:{thread:r}})},events:a}),send(e,n){return bridgeSend(t,e,n)}}}function defaultEvents(e){return{async"turn.started"(e,t,n){await t.thread?.startTyping(`Working...`)},async"input.requested"(t,n,r){!n.thread||t.requests.length===0||await n.thread.post(renderInputRequests(t.requests,e))},async"message.completed"(e,t,n){e.finishReason===`tool-calls`||!e.message||!t.thread||await t.thread.post(e.message)},async"turn.failed"(e,t,n){await postFailure(t.thread,`I hit an error while handling your request`,e)},async"session.failed"(e,t){await postFailure(t.thread,`This session could not recover from an error`,e)}}}function renderInputRequests(e,t){return Card({children:e.flatMap(e=>renderInputRequest(e,t))})}function renderInputRequest(e,t){let n=[CardText(e.prompt)];return e.options&&e.options.length>0?(n.push(Actions(e.options.map(n=>Button({id:encodeInputAction(t,e.requestId,n.id),label:n.label,style:n.style,value:n.id})))),n):(n.push(CardText(`This request needs a freeform answer. Continue from the Eve session UI.`)),n)}async function postFailure(e,r,i){if(!e)return;let a=formatErrorHint(i),o=extractErrorId(i.details);await e.post([`${r}${a}.`,`Please try again, rephrase, or reach out if it keeps failing.`,...o?[`Error id: ${o}`]:[]].join(`
|
|
2
|
+
|
|
3
|
+
`))}async function bridgeSend(e,t,n){let r=contextStorage.getStore()?.get(ActiveWebhookKey);if(!r)throw Error(`chatSdkChannel().send can only run during a Chat SDK webhook handler for this bridge.`);let a=serializeThread(e,n.thread,n.adapterName),o={auth:n.auth??null,continuationToken:a.id,state:{thread:a}};return n.callback&&(o.callback=n.callback),n.mode&&(o.mode=n.mode),n.title&&(o.title=n.title),r.send(t,o)}function initialState(){return{thread:null}}function metadataFromState(e){return{adapterName:e.thread?.adapterName??null,channelId:e.thread?.channelId??null,isDM:e.thread?.isDM??null,threadId:e.thread?.id??null}}function threadFromState(e,t){if(!t.thread)return null;try{let n=t.thread;return new ThreadImpl({adapter:e.getAdapter(n.adapterName),channelId:n.channelId,channelVisibility:n.channelVisibility,currentMessage:n.currentMessage?Message.fromJSON(n.currentMessage):void 0,id:n.id,isDM:n.isDM,stateAdapter:e.getState()})}catch(e){return log.warn(`failed to rebuild Chat SDK thread from channel state`,{error:e}),null}}function serializeReceiveTarget(e,t){if(t.thread)return t.thread;if(!t.threadId)throw Error(`chatSdkChannel().receive requires target.thread or target.threadId.`);return serializeThread(e,t.threadId,t.adapterName)}function serializeThread(e,t,n){if(typeof t==`string`){let r=n??inferAdapterName(t),i=e.getAdapter(r);return{_type:`chat:Thread`,adapterName:r,channelId:i.channelIdFromThreadId(t),channelVisibility:i.getChannelVisibility?.(t),id:t,isDM:!1}}return isSerializedThread(t)?t:t.toJSON()}function isSerializedThread(e){return`_type`in e&&e._type===`chat:Thread`}function inferAdapterName(e){let t=e.indexOf(`:`);if(t<=0)throw Error(`chatSdkChannel string thread references require options.adapterName.`);return e.slice(0,t)}function adapterNames(e){return Object.keys(e)}function routeForAdapter(e,t){return t.routes?.[e]||`${(t.route??`/eve/v1/chat`).replace(/\/$/u,``)}/${e}`}function encodeInputAction(e,t,n){return`${e}${encodeURIComponent(t)}:${encodeURIComponent(n)}`}function decodeInputAction(e,t,n){if(!e.startsWith(t))return null;let r=e.slice(t.length),i=r.indexOf(`:`);if(i<=0)return null;try{let e=decodeURIComponent(r.slice(0,i));return{optionId:n??decodeURIComponent(r.slice(i+1)),requestId:e}}catch{return null}}export{chatSdkChannel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { chatSdkChannel, type ChatSdkChannel, type ChatSdkChannelBridge, type ChatSdkChannelConfig, type ChatSdkChannelContext, type ChatSdkChannelEvents, type ChatSdkChannelState, type ChatSdkEventContext, type ChatSdkInstrumentationMetadata, type ChatSdkReceiveTarget, type ChatSdkSendOptions, } from "#public/channels/chat-sdk/chatSdkChannel.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{chatSdkChannel}from"#public/channels/chat-sdk/chatSdkChannel.js";export{chatSdkChannel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{parseJsonObject}from"#shared/json.js";import"#public/channels/discord/verify.js";import{callDiscordApi,createDiscordFollowupMessage,discordContinuationToken,editDiscordOriginalResponse,sendDiscordChannelMessage,splitDiscordMessageContent,triggerDiscordTypingIndicator}from"#public/channels/discord/api.js";import{buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent}from"#public/channels/discord/hitl.js";import{defaultEvents,defaultOnCommand}from"#public/channels/discord/defaults.js";import{DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,commandInteractionMessage,formatDiscordContextBlock,parseDiscordInteraction}from"#public/channels/discord/inbound.js";import{discordDeferredJson,discordJson,discordJsonBody,readMessageContent}from"#public/channels/discord/responses.js";import{verifyDiscordInbound}from"#public/channels/discord/verifyInbound.js";
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{parseJsonObject}from"#shared/json.js";import{POST,defineChannel}from"#public/definitions/defineChannel.js";import"#public/channels/discord/verify.js";import{callDiscordApi,createDiscordFollowupMessage,discordContinuationToken,editDiscordOriginalResponse,sendDiscordChannelMessage,splitDiscordMessageContent,triggerDiscordTypingIndicator}from"#public/channels/discord/api.js";import{buildFreeformModalResponse,deriveComponentInputResponses,deriveModalInputResponses,isDiscordFreeformComponent}from"#public/channels/discord/hitl.js";import{defaultEvents,defaultOnCommand}from"#public/channels/discord/defaults.js";import{DISCORD_INTERACTION_RESPONSE_TYPE,DISCORD_INTERACTION_TYPE,commandInteractionMessage,formatDiscordContextBlock,parseDiscordInteraction}from"#public/channels/discord/inbound.js";import{discordDeferredJson,discordJson,discordJsonBody,readMessageContent}from"#public/channels/discord/responses.js";import{verifyDiscordInbound}from"#public/channels/discord/verifyInbound.js";const log=createLogger(`discord.channel`);function discordChannel(e={}){let t=e.onCommand??defaultOnCommand,a={...defaultEvents,...e.events};return defineChannel({kindHint:`discord`,state:initialDiscordState(),metadata:e=>({channelId:e.channelId,guildId:e.guildId}),context(t,n){return rebuildDiscordContext(t,n,e)},routes:[POST(e.route??`/eve/v1/discord`,async(r,{send:i,waitUntil:a})=>{let o=await verifyDiscordInbound(r,e.credentials);if(o===null)return new Response(`unauthorized`,{status:401});let s;try{s=parseJsonObject(JSON.parse(o))}catch(e){return log.warn(`inbound Discord body is not valid JSON`,{error:e}),discordJson({content:`invalid request`,ephemeral:!0})}if(s.type===DISCORD_INTERACTION_TYPE.PING)return discordJson({type:DISCORD_INTERACTION_RESPONSE_TYPE.PONG});let c=parseDiscordInteraction(s);return c===null?discordJson({content:`Unsupported Discord interaction.`,ephemeral:!0}):handleInteraction({config:e,interaction:c,onCommand:t,send:i,waitUntil:a})})],async receive(t,{send:n}){let r=t.target,i=readString(r.channelId);if(!i)throw Error(`discordChannel().receive requires target.channelId.`);let a=readString(r.conversationId),o=r.initialMessage;if(o!==void 0&&a!==void 0)throw Error("discordChannel().receive: `conversationId` and `initialMessage` are mutually exclusive.");let c=a??``,l=a!==void 0;if(o!==void 0){let t=await buildDiscordHandle({config:e,state:{...initialDiscordState(),channelId:i}}).sendChannelMessage(o);c=t.id,l=t.id.length>0}return n(t.message,{auth:t.auth,continuationToken:discordContinuationToken(i,c),state:{applicationId:null,channelId:i,conversationId:c||null,guildId:null,hasMessageAnchor:l,initialResponseSent:!0,interactionToken:null}})},events:a})}function rebuildDiscordContext(e,t,n){return{discord:buildDiscordHandle({config:n,session:t,state:e}),state:e}}function buildDiscordHandle(e){let n=e.config.api,r=e.state,i=mergeCredentials(e.config.credentials,r);function anchor(t){!t.id||r.hasMessageAnchor||(r.conversationId=t.id,r.hasMessageAnchor=!0,r.channelId&&e.session?.setContinuationToken(discordContinuationToken(r.channelId,t.id)))}async function sendViaChannel(e){let t=r.channelId??``;if(!t)throw Error(`discordChannel: missing channel id for outbound message.`);let a=await sendDiscordChannelMessage({apiBaseUrl:n?.apiBaseUrl,body:normalizePostInput(e),credentials:i,fetch:n?.fetch,channelId:t});return anchor(a),a}async function editOriginal(e){let t=r.interactionToken??``;if(!t)throw Error(`discordChannel: missing interaction token for original response edit.`);let a=await editDiscordOriginalResponse({apiBaseUrl:n?.apiBaseUrl,body:normalizePostInput(e),credentials:i,fetch:n?.fetch,interactionToken:t});return r.initialResponseSent=!0,anchor(a),a}async function followup(e){let t=r.interactionToken??``;if(!t)throw Error(`discordChannel: missing interaction token for followup message.`);let a=await createDiscordFollowupMessage({apiBaseUrl:n?.apiBaseUrl,body:normalizePostInput(e),credentials:i,fetch:n?.fetch,interactionToken:t});return anchor(a),a}async function startTyping(){let e=r.channelId??``;if(e)try{await triggerDiscordTypingIndicator({apiBaseUrl:n?.apiBaseUrl,credentials:i,fetch:n?.fetch,channelId:e})}catch(n){logError(log,`Discord typing indicator failed — swallowed`,n,{channelId:e})}}return{applicationId:r.applicationId??void 0,channelId:r.channelId??``,conversationId:r.conversationId??``,guildId:r.guildId??void 0,interactionToken:r.interactionToken??void 0,request(e,t,r){return callDiscordApi({apiBaseUrl:n?.apiBaseUrl,body:t,botToken:r?.botAuth===!0?i.botToken:void 0,fetch:n?.fetch,method:r?.method,path:e})},async post(e){let t=expandPostBodies(normalizePostInput(e)),n;for(let e of t){let t=await postOne({body:e,editOriginal,followup,sendViaChannel,state:r});n===void 0&&(n=t)}return n??{id:``,raw:null}},editOriginalResponse:editOriginal,followup,sendChannelMessage:sendViaChannel,startTyping}}async function postOne(e){if(e.state.interactionToken&&e.state.applicationId)try{return e.state.initialResponseSent?await e.followup(e.body):await e.editOriginal(e.body)}catch(e){log.warn(`Discord interaction-token delivery failed, falling back to channel message`,{error:e})}return e.sendViaChannel(e.body)}async function handleInteraction(e){return e.interaction.type===DISCORD_INTERACTION_TYPE.APPLICATION_COMMAND?handleCommandInteraction({config:e.config,interaction:e.interaction,onCommand:e.onCommand,send:e.send,waitUntil:e.waitUntil}):e.interaction.type===DISCORD_INTERACTION_TYPE.MESSAGE_COMPONENT?handleComponentInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil}):handleModalSubmitInteraction({interaction:e.interaction,send:e.send,waitUntil:e.waitUntil})}async function handleCommandInteraction(e){let t=stateFromInteraction(e.interaction,{conversationId:e.interaction.id,hasMessageAnchor:!1,initialResponseSent:!1}),n={discord:buildDiscordHandle({config:e.config,state:t})},r;try{r=await e.onCommand(n,e.interaction)}catch(e){return log.error(`command handler failed`,{error:e}),discordJson({content:`The Discord command handler failed.`,ephemeral:!0})}return r==null?discordJson({content:`Command ignored.`,ephemeral:!0}):(e.waitUntil(dispatchCommand({interaction:e.interaction,result:r,send:e.send,state:t})),discordDeferredJson(r.ephemeral===!0))}function handleComponentInteraction(e){if(isDiscordFreeformComponent(e.interaction.customId)){let t=readMessageContent(e.interaction.raw);return discordJsonBody(buildFreeformModalResponse({customId:e.interaction.customId,prompt:t}))}let t=deriveComponentInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId,inputResponses:t,interaction:e.interaction,send:e.send})),discordJsonBody({type:DISCORD_INTERACTION_RESPONSE_TYPE.DEFERRED_UPDATE_MESSAGE})}function handleModalSubmitInteraction(e){let t=deriveModalInputResponses(e.interaction);return t.length>0&&e.waitUntil(dispatchInputResponses({conversationId:e.interaction.messageId??e.interaction.id,inputResponses:t,interaction:e.interaction,send:e.send})),discordJson({content:`Answer received.`,ephemeral:!0})}async function dispatchCommand(e){let t=commandInteractionMessage(e.interaction),n=formatDiscordContextBlock({channelId:e.interaction.channelId,commandName:e.interaction.commandName,guildId:e.interaction.guildId,interactionId:e.interaction.id,userId:e.interaction.user.id,username:e.interaction.user.username}),r=e.result.context??[];try{await e.send({message:t,context:[n,...r]},{auth:e.result.auth,continuationToken:discordContinuationToken(e.interaction.channelId,e.interaction.id),state:e.state})}catch(e){log.error(`command delivery failed`,{error:e})}}async function dispatchInputResponses(e){try{await e.send({inputResponses:e.inputResponses},{auth:null,continuationToken:discordContinuationToken(e.interaction.channelId,e.conversationId),state:stateFromInteraction(e.interaction,{conversationId:e.conversationId,hasMessageAnchor:!0,initialResponseSent:!0})})}catch(e){log.error(`interaction response delivery failed`,{error:e})}}function stateFromInteraction(e,t){return{applicationId:e.applicationId,channelId:e.channelId,conversationId:t.conversationId,guildId:e.guildId??null,hasMessageAnchor:t.hasMessageAnchor,initialResponseSent:t.initialResponseSent,interactionToken:e.token}}function initialDiscordState(){return{applicationId:null,channelId:null,conversationId:null,guildId:null,hasMessageAnchor:!1,initialResponseSent:!1,interactionToken:null}}function mergeCredentials(e,t){return{applicationId:t.applicationId??e?.applicationId,botToken:e?.botToken,publicKey:e?.publicKey,webhookVerifier:e?.webhookVerifier}}function normalizePostInput(e){return typeof e==`string`?{content:e}:e}function expandPostBodies(e){return typeof e.content==`string`?splitDiscordMessageContent(e.content).map((t,n)=>n===0?{...e,content:t}:{allowed_mentions:e.allowed_mentions,content:t}):[e]}function readString(e){return typeof e==`string`&&e.length>0?e:void 0}export{discordChannel};
|
|
@@ -18,6 +18,7 @@ export interface ChannelMetadataMap {
|
|
|
18
18
|
readonly subagent: InstrumentationChannelMetadata;
|
|
19
19
|
readonly unknown: InstrumentationChannelMetadata;
|
|
20
20
|
readonly "channel:slack": import("#public/channels/slack/slackChannel.js").SlackInstrumentationMetadata;
|
|
21
|
+
readonly "channel:chat-sdk": import("#public/channels/chat-sdk/chatSdkChannel.js").ChatSdkInstrumentationMetadata;
|
|
21
22
|
readonly "channel:discord": import("#public/channels/discord/index.js").DiscordInstrumentationMetadata;
|
|
22
23
|
readonly "channel:twilio": import("#public/channels/twilio/twilioChannel.js").TwilioInstrumentationMetadata;
|
|
23
24
|
readonly "channel:teams": import("#public/channels/teams/index.js").TeamsInstrumentationMetadata;
|
|
@@ -40,6 +41,7 @@ export type InstrumentationChannelKind = keyof ChannelMetadataMap;
|
|
|
40
41
|
*/
|
|
41
42
|
export interface ChannelReferenceMap {
|
|
42
43
|
readonly "channel:slack": import("#public/channels/slack/slackChannel.js").SlackChannel;
|
|
44
|
+
readonly "channel:chat-sdk": import("#public/channels/chat-sdk/chatSdkChannel.js").ChatSdkChannel;
|
|
43
45
|
readonly "channel:discord": import("#public/channels/discord/discordChannel.js").DiscordChannel;
|
|
44
46
|
readonly "channel:twilio": import("#public/channels/twilio/twilioChannel.js").TwilioChannel;
|
|
45
47
|
readonly "channel:teams": import("#public/channels/teams/teamsChannel.js").TeamsChannel;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger,logError}from"#internal/logging.js";import{callSlackApi as callSlackApi$1,fetchSlackThreadReplies,postSlackEphemeral,postSlackMessage,resolveSlackBotToken as resolveSlackBotToken$1,uploadSlackFiles}from"#compiled/@chat-adapter/slack/api.js";import{
|
|
1
|
+
import{createLogger,logError}from"#internal/logging.js";import{isCardElement}from"#compiled/chat/index.js";import{callSlackApi as callSlackApi$1,fetchSlackThreadReplies,postSlackEphemeral,postSlackMessage,resolveSlackBotToken as resolveSlackBotToken$1,uploadSlackFiles}from"#compiled/@chat-adapter/slack/api.js";import{cardToBlocks,cardToFallbackText}from"#public/channels/slack/blocks.js";import{truncateTypingStatus}from"#public/channels/slack/limits.js";import{gfmToSlackMrkdwn,rewriteBareMentions,slackMrkdwnToGfm}from"#public/channels/slack/mrkdwn.js";const log=createLogger(`slack.api`);function slackContinuationToken(e,t){return`${e}:${t}`}async function resolveSlackBotToken(e){let t=e??process.env.SLACK_BOT_TOKEN;if(!t)throw Error(`SLACK_BOT_TOKEN is required.`);return resolveSlackBotToken$1(t)}async function callSlackApi(e){return callSlackApi$1(e.operation,normalizeSlackApiBody(e.body),createSlackApiOptions(e.botToken))}function createSlackRequester(e){return(t,n)=>callSlackApi({botToken:e,operation:t,body:n})}function buildSlackBinding(e){let n=createSlackRequester(e.botToken),r=[],s=e.threadTs;function handleMessageTs(t){s||t===s||(s=t,e.onThreadTsChanged?.(t))}async function uploadFiles(t,n){let r=n?.channelId??e.channelId,i=n?.threadTs??s;return uploadSlackFiles(t.map(toSlackFileUpload),{...createSlackApiOptions(e.botToken),channelId:r||void 0,initialComment:n?.initialComment,threadTs:i||void 0})}return{thread:{recentMessages:r,async post(t){let n=normalizePostInput(t),r=n.files??[],i=`blocks`in n||`card`in n;if(r.length>0&&!i){let e=await uploadFiles(r,{initialComment:`markdown`in n?rewriteBareMentions(gfmToSlackMrkdwn(n.markdown)):`text`in n?rewriteBareMentions(n.text):void 0});return{id:Array.isArray(e.raw.files)&&e.raw.files.length>0?String(e.raw.files[0].id??``):``,raw:e.raw}}let a=await postSlackMessage(buildPostMessageOptions(n,e.channelId,s,e.botToken)),c=a.id;if(handleMessageTs(c),r.length>0&&i)try{await uploadFiles(r)}catch(e){log.warn(`file upload after structured post failed`,{error:e})}return{id:c,raw:a.raw}},async postEphemeral(t,n){let r=await postSlackEphemeral({...buildPostMessageOptions(normalizePostInput(n),e.channelId,s,e.botToken),user:t});return{id:r.id,raw:r.raw}},async postDirectMessage(t,r){let i=await n(`conversations.open`,{users:t}),a=i.ok===!0?i.channel?.id:void 0;if(typeof a!=`string`||a.length===0)throw Error(`Slack conversations.open failed: ${i.error??`unknown_error`}`);let s=await postSlackMessage(buildPostMessageOptions(normalizePostInput(r),a,``,e.botToken));return{id:s.id,raw:s.raw}},async startTyping(r){if(!(!e.channelId||!s))try{let t=r===void 0?``:truncateTypingStatus(r),i={channel_id:e.channelId,thread_ts:s,status:t};t.length>0&&(i.loading_messages=[t]);let a=await n(`assistant.threads.setStatus`,i);a.ok!==!0&&log.warn(`assistant.threads.setStatus returned not-ok`,{error:a.error})}catch(n){logError(log,`startTyping threw — swallowed`,n,{channelId:e.channelId})}},async refresh(){if(r.length=0,!(!e.channelId||!s))try{let t=await fetchSlackThreadReplies({...createSlackApiOptions(e.botToken),channel:e.channelId,limit:50,ts:s});for(let e of t.messages)r.push(parseThreadMessage(e,s))}catch(n){logError(log,`refresh threw — swallowed`,n,{channelId:e.channelId})}},mentionUser(e){return`<@${e}>`}},slack:{channelId:e.channelId,get threadTs(){return s},teamId:e.teamId,request:n,uploadFiles}}}function normalizePostInput(e){return typeof e==`string`?{markdown:e}:isCardElement(e)?{card:e}:e}function buildPostMessageOptions(e,t,n,r){let i={...createSlackApiOptions(r),channel:t,threadTs:n||void 0,unfurlLinks:!1,unfurlMedia:!1};return`card`in e?(i.blocks=cardToBlocks(e.card),i.text=e.fallbackText??cardToFallbackText(e.card),i):`blocks`in e?(i.blocks=[...e.blocks],e.text!==void 0&&(i.text=e.text),i):`markdown`in e?(i.markdownText=rewriteBareMentions(e.markdown),i):(i.text=rewriteBareMentions(e.text),i)}function createSlackApiOptions(e){return{token:()=>resolveSlackBotToken(e)}}function normalizeSlackApiBody(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}function toSlackFileUpload(e){return{data:normalizeFileData(e.data),filename:e.filename}}function normalizeFileData(e){if(e instanceof ArrayBuffer||typeof Blob<`u`&&e instanceof Blob)return e;if(ArrayBuffer.isView(e)){let t=e;return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return e}function parseThreadMessage(e,t){let n=typeof e.text==`string`?e.text:``,r=typeof e.ts==`string`?e.ts:``,i=typeof e.thread_ts==`string`?e.thread_ts:t,a=typeof e.user==`string`?e.user:void 0,o=typeof e.bot_id==`string`?e.bot_id:void 0;return{text:n,markdown:slackMrkdwnToGfm(n),user:a,botId:o,ts:r,threadTs:i,isMe:o!==void 0,raw:e}}export{buildSlackBinding,callSlackApi,resolveSlackBotToken,slackContinuationToken};
|