eve 0.27.13 → 0.28.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 +19 -0
- package/dist/src/channel/adapter.d.ts +5 -5
- package/dist/src/channel/session.d.ts +2 -2
- package/dist/src/channel/types.d.ts +10 -6
- package/dist/src/chunks/{use-eve-agent-CsSQOKnp.js → use-eve-agent-CZkX_ZTT.js} +90 -1
- package/dist/src/chunks/{use-eve-agent-CWYe-vqE.js → use-eve-agent-hdPX68_i.js} +90 -1
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +8 -2
- package/dist/src/cli/dev/tui/subagent-pump.js +1 -1
- package/dist/src/cli/invoke/result.d.ts +15 -0
- package/dist/src/cli/invoke/result.js +1 -1
- package/dist/src/client/eve-agent-store.d.ts +7 -4
- package/dist/src/client/eve-agent-store.js +1 -1
- package/dist/src/client/index.d.ts +3 -3
- package/dist/src/client/index.js +1 -1
- package/dist/src/client/message-action-parts.js +1 -1
- package/dist/src/client/message-reducer-types.d.ts +5 -3
- package/dist/src/client/message-response.d.ts +4 -4
- package/dist/src/client/ndjson.d.ts +3 -3
- package/dist/src/client/open-stream.d.ts +2 -2
- package/dist/src/client/output-schema.d.ts +2 -2
- package/dist/src/client/reducer.d.ts +2 -2
- package/dist/src/client/session-utils.d.ts +5 -5
- package/dist/src/client/session.d.ts +2 -2
- package/dist/src/client/types.d.ts +2 -2
- package/dist/src/compiler/compile-from-memory.d.ts +1 -0
- package/dist/src/compiler/extension-compatibility.d.ts +8 -8
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +2 -2
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/context/dynamic-instruction-lifecycle.d.ts +2 -2
- package/dist/src/context/dynamic-model-lifecycle.d.ts +2 -2
- package/dist/src/context/dynamic-skill-lifecycle.d.ts +2 -2
- package/dist/src/context/dynamic-tool-lifecycle.d.ts +2 -2
- package/dist/src/context/hook-lifecycle.d.ts +2 -2
- package/dist/src/evals/assertions/run.d.ts +3 -3
- package/dist/src/evals/match.d.ts +4 -4
- package/dist/src/evals/runner/derive-run-facts.d.ts +2 -2
- package/dist/src/evals/session.d.ts +3 -3
- package/dist/src/evals/types.d.ts +12 -12
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/route-child-delivery.d.ts +4 -3
- package/dist/src/execution/route-child-delivery.js +1 -1
- package/dist/src/execution/session-delivery-hook.d.ts +1 -0
- package/dist/src/execution/session-delivery-hook.js +1 -1
- package/dist/src/execution/session-timeout-control.d.ts +9 -0
- package/dist/src/execution/session-timeout-control.js +1 -0
- package/dist/src/execution/session-timeout-steps.d.ts +13 -0
- package/dist/src/execution/session-timeout-steps.js +1 -0
- package/dist/src/execution/session-timeout-workflow.d.ts +6 -0
- package/dist/src/execution/session-timeout-workflow.js +1 -0
- package/dist/src/execution/session-timeout.d.ts +2 -0
- package/dist/src/execution/session-timeout.js +1 -0
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/subagent-hitl-proxy.d.ts +5 -1
- package/dist/src/execution/subagent-hitl-proxy.js +1 -1
- package/dist/src/execution/terminal-session-completion-step.d.ts +5 -0
- package/dist/src/execution/terminal-session-completion-step.js +1 -0
- package/dist/src/execution/terminal-session-failure-step.js +1 -1
- package/dist/src/execution/turn-workflow.js +1 -1
- package/dist/src/execution/workflow-entry.d.ts +1 -0
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +4 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.d.ts +5 -2
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/agent-otel-provider.js +1 -1
- package/dist/src/harness/ai-sdk-hook-bridge.js +1 -1
- package/dist/src/harness/input-extraction.js +1 -1
- package/dist/src/harness/input-request-class.d.ts +23 -0
- package/dist/src/harness/input-request-class.js +1 -0
- package/dist/src/harness/input-requests.d.ts +20 -9
- package/dist/src/harness/input-requests.js +1 -1
- package/dist/src/harness/instrumentation-lifecycle.d.ts +12 -1
- package/dist/src/harness/proxy-input-requests.d.ts +10 -4
- package/dist/src/harness/proxy-input-requests.js +1 -1
- package/dist/src/harness/session-limit-continuation.d.ts +0 -11
- package/dist/src/harness/session-limit-continuation.js +1 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +3 -2
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/session-token-limits.d.ts +41 -0
- package/dist/src/harness/session-token-limits.js +1 -0
- package/dist/src/harness/stale-input-responses.js +1 -1
- package/dist/src/harness/subagent-token-budget.d.ts +6 -4
- package/dist/src/harness/subagent-token-budget.js +1 -1
- package/dist/src/harness/tool-loop.js +1 -1
- package/dist/src/harness/turn-tag-state.d.ts +26 -17
- package/dist/src/harness/turn-tag-state.js +1 -1
- package/dist/src/harness/types.d.ts +4 -4
- package/dist/src/harness/workflow-lifecycle.d.ts +2 -2
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/workflow-core-shim.js +1 -1
- package/dist/src/protocol/event-dedupe.d.ts +25 -0
- package/dist/src/protocol/event-dedupe.js +1 -0
- package/dist/src/protocol/event-id.d.ts +16 -0
- package/dist/src/protocol/event-id.js +1 -0
- package/dist/src/protocol/message.d.ts +39 -23
- package/dist/src/protocol/message.js +2 -2
- package/dist/src/public/channels/discord/discordChannel.d.ts +3 -3
- package/dist/src/public/channels/github/githubChannel.d.ts +3 -3
- package/dist/src/public/channels/linear/linearChannel.d.ts +3 -3
- package/dist/src/public/channels/slack/hitl.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +3 -3
- package/dist/src/public/channels/teams/hitl.js +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +3 -3
- package/dist/src/public/channels/telegram/telegramChannel.d.ts +3 -3
- package/dist/src/public/channels/twilio/twilioChannel.d.ts +3 -3
- package/dist/src/public/definitions/channel.d.ts +4 -4
- package/dist/src/public/definitions/hook.d.ts +2 -2
- package/dist/src/react/use-eve-agent.d.ts +3 -2
- package/dist/src/runtime/framework-tools/ask-question.js +1 -1
- package/dist/src/runtime/hooks/registry.d.ts +2 -2
- package/dist/src/runtime/input/types.d.ts +19 -4
- package/dist/src/runtime/input/types.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/types.d.ts +2 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +2 -2
- package/dist/src/shared/agent-definition.d.ts +12 -0
- package/dist/src/shared/dynamic-tool-definition.d.ts +2 -2
- package/dist/src/shared/ulid.d.ts +39 -0
- package/dist/src/shared/ulid.js +1 -0
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.d.ts +4 -4
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.d.ts +4 -4
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +28 -16
- package/docs/concepts/execution-model-and-durability.mdx +1 -1
- package/docs/concepts/sessions-runs-and-streaming.md +61 -0
- package/docs/guides/client/streaming.mdx +9 -3
- package/docs/guides/frontend/overview.mdx +4 -2
- package/docs/guides/frontend/use-eve-agent-svelte.mdx +1 -1
- package/docs/guides/frontend/use-eve-agent-vue.mdx +10 -10
- package/docs/guides/hooks.md +40 -2
- package/docs/guides/instrumentation.md +4 -0
- package/docs/tools/human-in-the-loop.md +5 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
const HARNESS_TURN_USAGE_STATE_KEY=`eve.harness.turnUsage`,
|
|
1
|
+
import{findRuntimeTokenLimitViolation,grantRuntimeTokenLimits,remainingRuntimeTokenQuota,resolveRuntimeTokenLimits}from"#harness/session-token-limits.js";const HARNESS_TURN_USAGE_STATE_KEY=`eve.harness.turnUsage`,SESSION_RUNTIME_TOKEN_LIMIT_KEY=`eve.harness.sessionRuntimeTokenLimit`,ZERO_TOKEN_USAGE={cacheReadTokens:0,cacheWriteTokens:0,costUsd:0,inputTokens:0,outputTokens:0,sawCost:!1};function getTurnUsageState(e){return e?.[HARNESS_TURN_USAGE_STATE_KEY]}function getSessionTokenUsage(e){return getTurnUsageState(e.state)?.session??ZERO_TOKEN_USAGE}function toUsage(e){return{cacheReadTokens:e.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens,inputTokens:e.inputTokens,outputTokens:e.outputTokens}}function getSessionRuntimeTokenLimits(e){let t=e.state?.[SESSION_RUNTIME_TOKEN_LIMIT_KEY];return resolveRuntimeTokenLimits({configured:configuredSessionTokenLimits(e),stored:t})}function bumpSessionRuntimeTokenLimits(e){let n=getSessionTokenUsage(e),r=grantRuntimeTokenLimits({configured:configuredSessionTokenLimits(e),usage:n});return{...e,state:{...e.state,[SESSION_RUNTIME_TOKEN_LIMIT_KEY]:r}}}function getSessionRemainingTokenQuota(e){let t=getSessionTokenUsage(e);return remainingRuntimeTokenQuota({runtime:getSessionRuntimeTokenLimits(e),usage:t})}function getSessionTokenLimitViolation(t){let n=getSessionTokenUsage(t),r=getSessionRuntimeTokenLimits(t);return findRuntimeTokenLimitViolation({configured:configuredSessionTokenLimits(t),runtime:r,usage:n})}function configuredSessionTokenLimits(e){return{inputTokens:e.limits?.maxInputTokensPerSession,outputTokens:e.limits?.maxOutputTokensPerSession}}function setTurnUsageState(e,t){return{...e,state:{...e.state,[HARNESS_TURN_USAGE_STATE_KEY]:t}}}function accumulateTurnUsage(e){let t=toTokenUsageDelta(e.usage),n=e.previous?.session??ZERO_TOKEN_USAGE;return{...addTokenUsage(e.previous!==void 0&&e.previous.turnId===e.turnId?e.previous:ZERO_TOKEN_USAGE,t),turnId:e.turnId,session:addTokenUsage(n,t)}}function accumulateSessionUsage(e){let t=toTokenUsageDelta(e.usage),n=e.previous??{...ZERO_TOKEN_USAGE,session:ZERO_TOKEN_USAGE,turnId:``};return{...n,session:addTokenUsage(n.session,t)}}function addTokenUsage(e,t){return{cacheReadTokens:e.cacheReadTokens+t.cacheReadTokens,cacheWriteTokens:e.cacheWriteTokens+t.cacheWriteTokens,costUsd:e.costUsd+t.costUsd,inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,sawCost:e.sawCost||t.sawCost}}function toTokenUsageDelta(e){if(e===void 0)return ZERO_TOKEN_USAGE;let t=e.inputTokens??0,n=e.outputTokens??0;return{cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,costUsd:e.costUsd??0,inputTokens:t,outputTokens:n,sawCost:e.costUsd!==void 0}}export{accumulateSessionUsage,accumulateTurnUsage,bumpSessionRuntimeTokenLimits,getSessionRemainingTokenQuota,getSessionRuntimeTokenLimits,getSessionTokenLimitViolation,getSessionTokenUsage,getTurnUsageState,setTurnUsageState,toUsage};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { LanguageModel, ModelMessage, UserContent } from "ai";
|
|
2
2
|
import type { SessionCapabilities } from "#channel/types.js";
|
|
3
3
|
import type { AlsContext } from "#context/container.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type { UnstampedMessageStreamEvent, RuntimeIdentity } from "#protocol/message.js";
|
|
5
5
|
import type { RunMode } from "#shared/run-mode.js";
|
|
6
6
|
import type { RuntimeActionResult } from "#runtime/actions/types.js";
|
|
7
7
|
import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";
|
|
@@ -181,7 +181,7 @@ export type HarnessToolMap = ReadonlyMap<string, HarnessToolDefinition>;
|
|
|
181
181
|
* event handler, then injected into the harness so it can emit lifecycle
|
|
182
182
|
* events without knowing about writables or handlers.
|
|
183
183
|
*/
|
|
184
|
-
export type HarnessEmitFn = (event:
|
|
184
|
+
export type HarnessEmitFn = (event: UnstampedMessageStreamEvent, messages?: readonly import("ai").ModelMessage[]) => Promise<void>;
|
|
185
185
|
/**
|
|
186
186
|
* Unified event handler: emits the event to the stream, then
|
|
187
187
|
* dispatches to hook subscribers and dynamic tool resolvers.
|
|
@@ -190,7 +190,7 @@ export type HarnessEmitFn = (event: HandleMessageStreamEvent, messages?: readonl
|
|
|
190
190
|
* every event goes through channel adapter, stream write, hooks,
|
|
191
191
|
* and dynamic tool dispatch in one call.
|
|
192
192
|
*/
|
|
193
|
-
export type HandleEventFn = (event:
|
|
193
|
+
export type HandleEventFn = (event: UnstampedMessageStreamEvent, messages?: readonly import("ai").ModelMessage[]) => Promise<void>;
|
|
194
194
|
/**
|
|
195
195
|
* Dependencies injected into the tool-loop harness at construction time.
|
|
196
196
|
*/
|
|
@@ -241,7 +241,7 @@ export interface ToolLoopHarnessConfig {
|
|
|
241
241
|
readonly onCompaction?: () => readonly ModelMessage[];
|
|
242
242
|
readonly dispatchDynamicModelEvent?: (input: {
|
|
243
243
|
readonly ctx: AlsContext;
|
|
244
|
-
readonly event:
|
|
244
|
+
readonly event: UnstampedMessageStreamEvent;
|
|
245
245
|
readonly fallback: RuntimeModelReference;
|
|
246
246
|
readonly messages: readonly ModelMessage[];
|
|
247
247
|
}) => Promise<void>;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { HarnessEmissionState } from "#harness/emission.js";
|
|
2
2
|
import type { HarnessToolMap } from "#harness/types.js";
|
|
3
|
-
import { type
|
|
3
|
+
import { type UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
4
4
|
import type { WorkflowSandboxLifecycle } from "#shared/workflow-sandbox.js";
|
|
5
|
-
type EmitWorkflowLifecycleEvent = (event:
|
|
5
|
+
type EmitWorkflowLifecycleEvent = (event: UnstampedMessageStreamEvent) => Promise<void>;
|
|
6
6
|
/** Projects sandboxed subagent calls onto eve's existing action event stream. */
|
|
7
7
|
export declare function createWorkflowLifecycle(input: {
|
|
8
8
|
readonly emit: EmitWorkflowLifecycleEvent;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire}from"node:module";import{existsSync,readFileSync,realpathSync}from"node:fs";import{basename,dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;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{fileURLToPath}from"node:url";import{EVE_PACKAGE_NAME}from"#internal/package-name.js";let cachedPackageInfo,cachedPackageLocation;const BUNDLED_FALLBACK_PACKAGE_VERSION=`0.28.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 tryResolveVerifiedPackageRoot(e){try{let t=realpathSync.native(e);return tryReadInstalledPackageInfo(t,EVE_PACKAGE_NAME)===void 0?void 0:dirname(t)}catch{return}}function findNearestVerifiedPackageRoot(e){let t=e;for(;;){let e=tryResolveVerifiedPackageRoot(join(t,`package.json`));if(e!==void 0)return e;let n=dirname(t);if(n===t)return;t=n}}function tryResolveDirectBuildLocation(e){let t=dirname(e);for(;;){if(basename(t)===`dist`){let e=tryResolveVerifiedPackageRoot(join(dirname(t),`package.json`));if(e!==void 0)return{packageBuildRoot:t,packageRoot:e}}let e=dirname(t);if(e===t)return;t=e}}function isSourceCheckout(e){return existsSync(join(e,`src`,`internal`,`application`,`package.ts`))}function tryCreatePackageLocation(e){if(isSourceCheckout(e))return{packageBuildRoot:null,packageRoot:e};let n=join(e,`dist`);if(existsSync(n))return{packageBuildRoot:n,packageRoot:e}}function resolveSelfPackageJsonPath(t){return createRequire(t).resolve(`${EVE_PACKAGE_NAME}/package.json`)}function resolvePackageLocationFromModulePath(e,t=resolveSelfPackageJsonPath){let n=realpathSync.native(e),i=tryResolveDirectBuildLocation(n);if(i!==void 0)return i;let a=findNearestVerifiedPackageRoot(dirname(n));if(a!==void 0&&isSourceCheckout(a))return{packageBuildRoot:null,packageRoot:a};try{let e=tryResolveVerifiedPackageRoot(t(n)),r=e===void 0?void 0:tryCreatePackageLocation(e);if(r!==void 0)return r}catch{}let o=a===void 0?void 0:tryCreatePackageLocation(a);if(o!==void 0)return o;throw Error(`Failed to resolve the eve package root from "${e}".`)}function resolvePackageLocation(){return cachedPackageLocation??=resolvePackageLocationFromModulePath(resolveCurrentModulePath()),cachedPackageLocation}function resolvePackageBuildRoot(){return resolvePackageLocation().packageBuildRoot}function resolvePackageRoot(){return resolvePackageLocation().packageRoot}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,resolvePackageCompiledFilePath,resolvePackageDependencyPath,resolvePackageLocationFromModulePath,resolvePackageRoot,resolvePackageSourceDirectoryPath,resolvePackageSourceFilePath,resolveWorkflowModulePath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectProviderOptions,expectString,getOptionalStringRecordProperty}from"#internal/authored-module.js";import{isDynamicSentinel}from"#shared/dynamic-tool-definition.js";function normalizeAgentDefinition(e,i){let o=expectObjectRecord(e,i);if(expectOnlyKnownKeys(o,[`build`,`compaction`,`description`,`experimental`,`limits`,`model`,`modelContextWindowTokens`,`modelOptions`,`outputSchema`,`reasoning`],i),o.model===void 0)throw Error(`${i} The "model" field is required.`);let s={model:normalizeAgentModelDefinition(o.model,i)};return o.description!==void 0&&(s.description=expectString(o.description,i)),o.compaction!==void 0&&(s.compaction=normalizeAgentCompactionDefinition(o.compaction,i)),o.build!==void 0&&(s.build=normalizeAgentBuildDefinition(o.build,i)),o.experimental!==void 0&&(s.experimental=normalizeAgentExperimentalDefinition(o.experimental,i)),o.modelOptions!==void 0&&(s.modelOptions=normalizeAgentModelOptions(o.modelOptions,i)),o.modelContextWindowTokens!==void 0&&(s.modelContextWindowTokens=expectPositiveInteger(o.modelContextWindowTokens,i)),o.outputSchema!==void 0&&(s.outputSchema=o.outputSchema),o.reasoning!==void 0&&(s.reasoning=normalizeAgentReasoningDefinition(o.reasoning,i)),o.limits!==void 0&&(s.limits=normalizeAgentLimitsDefinition(o.limits,i)),s}function normalizeAgentReasoningDefinition(e,t){let n=expectString(e,t);switch(n){case`provider-default`:case`none`:case`minimal`:case`low`:case`medium`:case`high`:case`xhigh`:return n;default:throw Error(t)}}function normalizeAgentModelDefinition(r,i){if(!isDynamicSentinel(r))return r;let a=expectObjectRecord(r,i);if(expectOnlyKnownKeys(a,[`events`,`fallback`,`kind`],i),a.fallback===void 0)throw Error(`${i} Dynamic model definitions must include a "fallback" model.`);let o=expectObjectRecord(a.events,i),c={};for(let[t,n]of Object.entries(o))c[t]=expectFunction(n,i);return{events:c,fallback:a.fallback,kind:a.kind}}function expectPositiveIntegerOrFalse(e,t){return e!==!1&&expectPositiveInteger(e,t)}function normalizeAgentLimitsDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`maxInputTokensPerSession`,`maxOutputTokensPerSession`],r);let a={};return i.maxInputTokensPerSession!==void 0&&(a.maxInputTokensPerSession=expectPositiveIntegerOrFalse(i.maxInputTokensPerSession,r)),i.maxOutputTokensPerSession!==void 0&&(a.maxOutputTokensPerSession=expectPositiveIntegerOrFalse(i.maxOutputTokensPerSession,r)),a}function normalizeAgentBuildDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`externalDependencies`],r);let o={};if(i.externalDependencies!==void 0){if(!Array.isArray(i.externalDependencies))throw Error(r);o.externalDependencies=Object.freeze(i.externalDependencies.map(e=>expectString(e,r)))}return o}function normalizeAgentWorkflowDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`world`],r);let a={};return i.world!==void 0&&(a.world=normalizeAgentWorkflowWorldDefinition(i.world,r)),a}function normalizeAgentWorkflowWorldDefinition(e,t){let n=expectString(e,t);if(n.trim()===``)throw Error(`${t} "experimental.workflow.world" must be a non-empty package name.`);return n}function normalizeAgentExperimentalDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`workflow`],r);let a={};return i.workflow!==void 0&&(a.workflow=normalizeAgentWorkflowDefinition(i.workflow,r)),a}function normalizeAgentModelOptions(e,r){let a=expectObjectRecord(e,r);expectOnlyKnownKeys(a,[`providerOptions`],r);let o=a.providerOptions;return o===void 0?{}:{providerOptions:expectProviderOptions(o,r)}}function normalizeAgentCompactionDefinition(e,i){let a=expectObjectRecord(e,i);expectOnlyKnownKeys(a,[`model`,`modelContextWindowTokens`,`thresholdPercent`],i);let o={};if(a.model!==void 0){if(isDynamicSentinel(a.model))throw Error(`${i} "compaction.model" does not support defineDynamic — provide a static model.`);o.model=a.model}if(a.modelContextWindowTokens!==void 0&&(o.modelContextWindowTokens=expectPositiveInteger(a.modelContextWindowTokens,i)),a.thresholdPercent!==void 0){let e=a.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(i);o.thresholdPercent=e}return o}function normalizeInstructionsDefinition(e,r){let i=expectObjectRecord(e,r);return expectOnlyKnownKeys(i,[`markdown`],r),{markdown:expectString(i.markdown,r)}}function normalizeSkillDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`description`,`files`,`license`,`markdown`,`metadata`],r);let s={description:expectString(i.description,r),markdown:expectString(i.markdown,r)},c=i.license,l=getOptionalStringRecordProperty(i,`metadata`,r);return c!==void 0&&(s.license=expectString(c,r)),l!==void 0&&(s.metadata=l),i.files!==void 0&&(s.files=normalizeSkillFiles(i.files,r)),s}function normalizeSkillFiles(e,n){let r=expectObjectRecord(e,n),i={};for(let[e,t]of Object.entries(r)){if(typeof t==`string`||t instanceof Uint8Array){i[e]=t;continue}throw Error(`${n} Expected skill file "${e}" to be a string or Uint8Array.`)}return i}function normalizeScheduleDefinition(r,i){let o=expectObjectRecord(r,i);expectOnlyKnownKeys(o,[`cron`,`markdown`,`run`],i);let s=expectString(o.cron,i),c=o.markdown!==void 0,l=o.run!==void 0;if(c&&l)throw Error(`${i} Pass either "markdown" (fire-and-forget) or "run" (handler) — not both.`);if(!c&&!l)throw Error(`${i} Must provide either "markdown" (fire-and-forget) or "run" (handler).`);let u={cron:s};return c?u.markdown=expectString(o.markdown,i):u.run=expectFunction(o.run,i),u}export{normalizeAgentDefinition,normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition};
|
|
1
|
+
import{expectFunction,expectObjectRecord,expectOnlyKnownKeys,expectPositiveInteger,expectProviderOptions,expectString,getOptionalStringRecordProperty}from"#internal/authored-module.js";import{isDynamicSentinel}from"#shared/dynamic-tool-definition.js";function normalizeAgentDefinition(e,i){let o=expectObjectRecord(e,i);if(expectOnlyKnownKeys(o,[`build`,`compaction`,`description`,`experimental`,`limits`,`model`,`modelContextWindowTokens`,`modelOptions`,`outputSchema`,`reasoning`],i),o.model===void 0)throw Error(`${i} The "model" field is required.`);let s={model:normalizeAgentModelDefinition(o.model,i)};return o.description!==void 0&&(s.description=expectString(o.description,i)),o.compaction!==void 0&&(s.compaction=normalizeAgentCompactionDefinition(o.compaction,i)),o.build!==void 0&&(s.build=normalizeAgentBuildDefinition(o.build,i)),o.experimental!==void 0&&(s.experimental=normalizeAgentExperimentalDefinition(o.experimental,i)),o.modelOptions!==void 0&&(s.modelOptions=normalizeAgentModelOptions(o.modelOptions,i)),o.modelContextWindowTokens!==void 0&&(s.modelContextWindowTokens=expectPositiveInteger(o.modelContextWindowTokens,i)),o.outputSchema!==void 0&&(s.outputSchema=o.outputSchema),o.reasoning!==void 0&&(s.reasoning=normalizeAgentReasoningDefinition(o.reasoning,i)),o.limits!==void 0&&(s.limits=normalizeAgentLimitsDefinition(o.limits,i)),s}function normalizeAgentReasoningDefinition(e,t){let n=expectString(e,t);switch(n){case`provider-default`:case`none`:case`minimal`:case`low`:case`medium`:case`high`:case`xhigh`:return n;default:throw Error(t)}}function normalizeAgentModelDefinition(r,i){if(!isDynamicSentinel(r))return r;let a=expectObjectRecord(r,i);if(expectOnlyKnownKeys(a,[`events`,`fallback`,`kind`],i),a.fallback===void 0)throw Error(`${i} Dynamic model definitions must include a "fallback" model.`);let o=expectObjectRecord(a.events,i),c={};for(let[t,n]of Object.entries(o))c[t]=expectFunction(n,i);return{events:c,fallback:a.fallback,kind:a.kind}}function expectPositiveIntegerOrFalse(e,t){return e!==!1&&expectPositiveInteger(e,t)}function normalizeAgentLimitsDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`maxInputTokensPerSession`,`maxOutputTokensPerSession`,`sessionTimeoutMs`],r);let a={};return i.sessionTimeoutMs!==void 0&&(a.sessionTimeoutMs=expectPositiveIntegerOrFalse(i.sessionTimeoutMs,r)),i.maxInputTokensPerSession!==void 0&&(a.maxInputTokensPerSession=expectPositiveIntegerOrFalse(i.maxInputTokensPerSession,r)),i.maxOutputTokensPerSession!==void 0&&(a.maxOutputTokensPerSession=expectPositiveIntegerOrFalse(i.maxOutputTokensPerSession,r)),a}function normalizeAgentBuildDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`externalDependencies`],r);let o={};if(i.externalDependencies!==void 0){if(!Array.isArray(i.externalDependencies))throw Error(r);o.externalDependencies=Object.freeze(i.externalDependencies.map(e=>expectString(e,r)))}return o}function normalizeAgentWorkflowDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`world`],r);let a={};return i.world!==void 0&&(a.world=normalizeAgentWorkflowWorldDefinition(i.world,r)),a}function normalizeAgentWorkflowWorldDefinition(e,t){let n=expectString(e,t);if(n.trim()===``)throw Error(`${t} "experimental.workflow.world" must be a non-empty package name.`);return n}function normalizeAgentExperimentalDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`workflow`],r);let a={};return i.workflow!==void 0&&(a.workflow=normalizeAgentWorkflowDefinition(i.workflow,r)),a}function normalizeAgentModelOptions(e,r){let a=expectObjectRecord(e,r);expectOnlyKnownKeys(a,[`providerOptions`],r);let o=a.providerOptions;return o===void 0?{}:{providerOptions:expectProviderOptions(o,r)}}function normalizeAgentCompactionDefinition(e,i){let a=expectObjectRecord(e,i);expectOnlyKnownKeys(a,[`model`,`modelContextWindowTokens`,`thresholdPercent`],i);let o={};if(a.model!==void 0){if(isDynamicSentinel(a.model))throw Error(`${i} "compaction.model" does not support defineDynamic — provide a static model.`);o.model=a.model}if(a.modelContextWindowTokens!==void 0&&(o.modelContextWindowTokens=expectPositiveInteger(a.modelContextWindowTokens,i)),a.thresholdPercent!==void 0){let e=a.thresholdPercent;if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw Error(i);o.thresholdPercent=e}return o}function normalizeInstructionsDefinition(e,r){let i=expectObjectRecord(e,r);return expectOnlyKnownKeys(i,[`markdown`],r),{markdown:expectString(i.markdown,r)}}function normalizeSkillDefinition(e,r){let i=expectObjectRecord(e,r);expectOnlyKnownKeys(i,[`description`,`files`,`license`,`markdown`,`metadata`],r);let s={description:expectString(i.description,r),markdown:expectString(i.markdown,r)},c=i.license,l=getOptionalStringRecordProperty(i,`metadata`,r);return c!==void 0&&(s.license=expectString(c,r)),l!==void 0&&(s.metadata=l),i.files!==void 0&&(s.files=normalizeSkillFiles(i.files,r)),s}function normalizeSkillFiles(e,n){let r=expectObjectRecord(e,n),i={};for(let[e,t]of Object.entries(r)){if(typeof t==`string`||t instanceof Uint8Array){i[e]=t;continue}throw Error(`${n} Expected skill file "${e}" to be a string or Uint8Array.`)}return i}function normalizeScheduleDefinition(r,i){let o=expectObjectRecord(r,i);expectOnlyKnownKeys(o,[`cron`,`markdown`,`run`],i);let s=expectString(o.cron,i),c=o.markdown!==void 0,l=o.run!==void 0;if(c&&l)throw Error(`${i} Pass either "markdown" (fire-and-forget) or "run" (handler) — not both.`);if(!c&&!l)throw Error(`${i} Must provide either "markdown" (fire-and-forget) or "run" (handler).`);let u={cron:s};return c?u.markdown=expectString(o.markdown,i):u.run=expectFunction(o.run,i),u}export{normalizeAgentDefinition,normalizeInstructionsDefinition,normalizeScheduleDefinition,normalizeSkillDefinition};
|
|
@@ -38,7 +38,7 @@ export declare function defineHook<T = unknown>(): {
|
|
|
38
38
|
/**
|
|
39
39
|
* Sleeps from inside workflow-body code.
|
|
40
40
|
*/
|
|
41
|
-
export declare function sleep():
|
|
41
|
+
export declare function sleep(duration: string | number | Date): Promise<void>;
|
|
42
42
|
/**
|
|
43
43
|
* `resumeHook()` is an external/runtime API and must not run in workflow bodies.
|
|
44
44
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const WORKFLOW_CONTEXT_SYMBOL=Symbol.for(`WORKFLOW_CONTEXT`),WORKFLOW_CREATE_HOOK=Symbol.for(`WORKFLOW_CREATE_HOOK`),WORKFLOW_GET_STREAM_ID=Symbol.for(`WORKFLOW_GET_STREAM_ID`),WORKFLOW_USE_STEP=Symbol.for(`WORKFLOW_USE_STEP`),STREAM_NAME_SYMBOL=Symbol.for(`WORKFLOW_STREAM_NAME`),workflowGlobal=globalThis;var RetryableError=class extends Error{},FatalError=class extends Error{};function createHook(e){let n=workflowGlobal[WORKFLOW_CREATE_HOOK];if(n===void 0)throw Error("`createHook()` can only be called inside a workflow function");return n(e)}function getWorkflowMetadata(){let t=workflowGlobal[WORKFLOW_CONTEXT_SYMBOL];if(t===void 0)throw Error("`getWorkflowMetadata()` can only be called inside a workflow or step function");return t}function getWritable(e={}){let t=workflowGlobal[WORKFLOW_GET_STREAM_ID];if(t===void 0)throw Error("`getWritable()` can only be called inside a workflow function");let r=t(e.namespace);return Object.create(globalThis.WritableStream.prototype,{[STREAM_NAME_SYMBOL]:{value:r,writable:!1}})}function createWebhook(e){let t=createHook(e),n=getWorkflowMetadata();return t.url=`${typeof n.url==`string`?n.url:``}/.well-known/workflow/v1/webhook/${encodeURIComponent(t.token)}`,t}function defineHook(){return{create:createHook,resume(){throw Error("`defineHook().resume()` can only be called from external contexts.")}}}function sleep(){throw Error("`sleep()`
|
|
1
|
+
const WORKFLOW_CONTEXT_SYMBOL=Symbol.for(`WORKFLOW_CONTEXT`),WORKFLOW_CREATE_HOOK=Symbol.for(`WORKFLOW_CREATE_HOOK`),WORKFLOW_GET_STREAM_ID=Symbol.for(`WORKFLOW_GET_STREAM_ID`),WORKFLOW_SLEEP=Symbol.for(`WORKFLOW_SLEEP`),WORKFLOW_USE_STEP=Symbol.for(`WORKFLOW_USE_STEP`),STREAM_NAME_SYMBOL=Symbol.for(`WORKFLOW_STREAM_NAME`),workflowGlobal=globalThis;var RetryableError=class extends Error{},FatalError=class extends Error{};function createHook(e){let n=workflowGlobal[WORKFLOW_CREATE_HOOK];if(n===void 0)throw Error("`createHook()` can only be called inside a workflow function");return n(e)}function getWorkflowMetadata(){let t=workflowGlobal[WORKFLOW_CONTEXT_SYMBOL];if(t===void 0)throw Error("`getWorkflowMetadata()` can only be called inside a workflow or step function");return t}function getWritable(e={}){let t=workflowGlobal[WORKFLOW_GET_STREAM_ID];if(t===void 0)throw Error("`getWritable()` can only be called inside a workflow function");let r=t(e.namespace);return Object.create(globalThis.WritableStream.prototype,{[STREAM_NAME_SYMBOL]:{value:r,writable:!1}})}function createWebhook(e){let t=createHook(e),n=getWorkflowMetadata();return t.url=`${typeof n.url==`string`?n.url:``}/.well-known/workflow/v1/webhook/${encodeURIComponent(t.token)}`,t}function defineHook(){return{create:createHook,resume(){throw Error("`defineHook().resume()` can only be called from external contexts.")}}}function sleep(e){let t=workflowGlobal[WORKFLOW_SLEEP];if(t===void 0)throw Error("`sleep()` can only be called inside a workflow function");return t(e)}function resumeHook(){throw Error("`resumeHook()` can only be called from outside a workflow function")}function getStepMetadata(){throw Error("`getStepMetadata()` can only be called inside a step function")}async function setAttributes(e,t={}){let n=Object.entries(e);if(n.length===0)return;let r=workflowGlobal[WORKFLOW_USE_STEP];if(r===void 0)throw Error("`setAttributes()` can only be called inside a workflow runtime context");let i=n.map(([e,t])=>({key:e,value:t===void 0?null:t})),a=t.allowReservedAttributes===!0?{allowReservedAttributes:!0}:{};await r(`__builtin_set_attributes`)(i,a)}export{FatalError,RetryableError,createHook,createWebhook,defineHook,getStepMetadata,getWorkflowMetadata,getWritable,resumeHook,setAttributes,sleep};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { MessageStreamEvent } from "#protocol/message.js";
|
|
2
|
+
/** Remembers which session-stream events have already been consumed. */
|
|
3
|
+
export type EventDeduper = {
|
|
4
|
+
/**
|
|
5
|
+
* Records `event` and returns true when it is new — false when its id was
|
|
6
|
+
* already admitted, so the caller should drop it.
|
|
7
|
+
*/
|
|
8
|
+
admit(event: MessageStreamEvent): boolean;
|
|
9
|
+
/** Number of ids currently remembered. */
|
|
10
|
+
readonly size: number;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Creates an {@link EventDeduper} keyed on the durable `meta.id`.
|
|
14
|
+
*
|
|
15
|
+
* Catches a reconnect that overlaps handled events, a rewind to an earlier
|
|
16
|
+
* `startIndex`, and a saved log merged with the prefix a live stream replays.
|
|
17
|
+
* A retried step is not a duplicate: it re-emits under new ids.
|
|
18
|
+
*
|
|
19
|
+
* The window is unbounded because a bounded one cannot survive a rewind past
|
|
20
|
+
* its capacity — the oldest id is already evicted, so re-admitting it evicts
|
|
21
|
+
* the next and the whole replay cascades back in. Callers here retain an
|
|
22
|
+
* object per event anyway; one that retains nothing should bound its reads
|
|
23
|
+
* with the `startIndex` cursor instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare function createEventDeduper(): EventDeduper;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function createEventDeduper(){let e=new Set;return{admit(t){let n=t.meta?.id;return n===void 0?!0:e.has(n)?!1:(e.add(n),!0)},get size(){return e.size}}}export{createEventDeduper};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Prefix stamped on every eve session stream event id. */
|
|
2
|
+
export declare const EVENT_ID_PREFIX = "evt_";
|
|
3
|
+
/**
|
|
4
|
+
* Mints the id carried on one session stream event's `meta.id`:
|
|
5
|
+
* {@link EVENT_ID_PREFIX} followed by a ULID.
|
|
6
|
+
*
|
|
7
|
+
* See `#shared/ulid.js` for the ordering guarantee — it holds within a
|
|
8
|
+
* process, not across the separate steps of one session.
|
|
9
|
+
*/
|
|
10
|
+
export declare function createEventId(): string;
|
|
11
|
+
/**
|
|
12
|
+
* Returns true when `value` has the shape {@link createEventId} produces.
|
|
13
|
+
*
|
|
14
|
+
* Shape-only: this does not prove eve minted the id.
|
|
15
|
+
*/
|
|
16
|
+
export declare function isEventId(value: string): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createUlid,isUlid}from"#shared/ulid.js";const EVENT_ID_PREFIX=`evt_`;function createEventId(){return`${EVENT_ID_PREFIX}${createUlid()}`}function isEventId(e){return e.startsWith(`evt_`)&&isUlid(e.slice(4))}export{EVENT_ID_PREFIX,createEventId,isEventId};
|
|
@@ -9,7 +9,7 @@ export declare const EVE_STREAM_TAIL_INDEX_HEADER = "x-eve-stream-tail-index";
|
|
|
9
9
|
export declare const EVE_STREAM_VERSION_HEADER = "x-eve-stream-version";
|
|
10
10
|
export declare const EVE_MESSAGE_STREAM_CONTENT_TYPE = "application/x-ndjson; charset=utf-8";
|
|
11
11
|
export declare const EVE_MESSAGE_STREAM_FORMAT = "ndjson";
|
|
12
|
-
export declare const EVE_MESSAGE_STREAM_VERSION = "
|
|
12
|
+
export declare const EVE_MESSAGE_STREAM_VERSION = "20";
|
|
13
13
|
/**
|
|
14
14
|
* eve-owned finish reason for one completed assistant step.
|
|
15
15
|
*
|
|
@@ -28,11 +28,21 @@ export interface StepCompletedProviderMetadata {
|
|
|
28
28
|
/**
|
|
29
29
|
* Durable metadata attached to one persisted session stream event.
|
|
30
30
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
31
|
+
* Stamped once, immediately before the event is written to the workflow-owned
|
|
32
|
+
* stream, and stored with it. Re-reading the stream — reconnecting, rewinding,
|
|
33
|
+
* or replaying a finished session — yields the same values every time.
|
|
33
34
|
*/
|
|
34
|
-
export interface
|
|
35
|
+
export interface MessageStreamEventMeta {
|
|
36
|
+
/** ISO-8601 emission time. */
|
|
35
37
|
readonly at: string;
|
|
38
|
+
/**
|
|
39
|
+
* Unique, lexicographically sortable identifier for this event.
|
|
40
|
+
*
|
|
41
|
+
* Stamped from stream version 20 on: rewinding into a session that started
|
|
42
|
+
* before the upgrade yields events whose `id` is absent despite this type,
|
|
43
|
+
* and those cannot be deduplicated.
|
|
44
|
+
*/
|
|
45
|
+
readonly id: string;
|
|
36
46
|
}
|
|
37
47
|
/**
|
|
38
48
|
* Normalized completion status for one emitted runtime action result.
|
|
@@ -242,7 +252,7 @@ export interface SubagentStartedStreamEvent {
|
|
|
242
252
|
export interface SubagentChildEventStreamEvent {
|
|
243
253
|
data: {
|
|
244
254
|
callId: string;
|
|
245
|
-
event:
|
|
255
|
+
event: UnstampedMessageStreamEvent;
|
|
246
256
|
subagentName: string;
|
|
247
257
|
};
|
|
248
258
|
type: "subagent.event";
|
|
@@ -519,33 +529,40 @@ export interface SessionCompletedStreamEvent {
|
|
|
519
529
|
type: "session.completed";
|
|
520
530
|
}
|
|
521
531
|
/**
|
|
522
|
-
* Serializable
|
|
532
|
+
* Serializable event before eve stamps the durable stream envelope.
|
|
533
|
+
*
|
|
534
|
+
* Internal emitters use this type while constructing events. Public stream
|
|
535
|
+
* consumers receive {@link MessageStreamEvent}.
|
|
523
536
|
*/
|
|
524
|
-
export type
|
|
525
|
-
readonly meta?: HandleMessageStreamEventMeta;
|
|
526
|
-
};
|
|
537
|
+
export type UnstampedMessageStreamEvent = CompactionCompletedStreamEvent | CompactionRequestedStreamEvent | AuthorizationCompletedStreamEvent | AuthorizationRequiredStreamEvent | MessageAppendedStreamEvent | MessageCompletedStreamEvent | MessageReceivedStreamEvent | ReasoningAppendedStreamEvent | SessionCompletedStreamEvent | SessionFailedStreamEvent | SessionStartedStreamEvent | SessionWaitingStreamEvent | ResultCompletedStreamEvent | SubagentCalledStreamEvent | SubagentChildEventStreamEvent | SubagentCompletedStreamEvent | SubagentStartedStreamEvent | ActionsRequestedStreamEvent | InputRequestedStreamEvent | ActionResultStreamEvent | ReasoningCompletedStreamEvent | StepCompletedStreamEvent | StepFailedStreamEvent | StepStartedStreamEvent | TurnCancelledStreamEvent | TurnCompletedStreamEvent | TurnFailedStreamEvent | TurnStartedStreamEvent;
|
|
527
538
|
/**
|
|
528
539
|
* Stream events that represent an unrecovered turn/session failure.
|
|
529
540
|
*/
|
|
530
541
|
export type TurnFailureStreamEvent = SessionFailedStreamEvent | StepFailedStreamEvent | TurnFailedStreamEvent;
|
|
531
542
|
/**
|
|
532
|
-
* One
|
|
543
|
+
* One event read from an eve session stream.
|
|
533
544
|
*
|
|
534
|
-
*
|
|
535
|
-
* original `meta.at` value instead of recomputing it.
|
|
545
|
+
* eve stamps the durable identity and emission time before writing the event.
|
|
536
546
|
*/
|
|
537
|
-
export type
|
|
538
|
-
readonly meta:
|
|
547
|
+
export type MessageStreamEvent = UnstampedMessageStreamEvent & {
|
|
548
|
+
readonly meta: MessageStreamEventMeta;
|
|
539
549
|
};
|
|
550
|
+
/**
|
|
551
|
+
* @deprecated Use {@link MessageStreamEvent}.
|
|
552
|
+
*/
|
|
553
|
+
export type HandleMessageStreamEvent = MessageStreamEvent;
|
|
540
554
|
/**
|
|
541
555
|
* Returns true when the current stream has reached a turn boundary or terminal
|
|
542
556
|
* session outcome.
|
|
543
557
|
*/
|
|
544
|
-
export declare function isCurrentTurnBoundaryEvent(event:
|
|
558
|
+
export declare function isCurrentTurnBoundaryEvent(event: UnstampedMessageStreamEvent): boolean;
|
|
545
559
|
/**
|
|
546
560
|
* Narrows a stream event to the failure events that terminate or poison a turn.
|
|
561
|
+
*
|
|
562
|
+
* Generic so narrowing keeps the input's stamping: a
|
|
563
|
+
* {@link MessageStreamEvent} narrows to a stamped failure event.
|
|
547
564
|
*/
|
|
548
|
-
export declare function isTurnFailureEvent(event:
|
|
565
|
+
export declare function isTurnFailureEvent<TEvent extends UnstampedMessageStreamEvent>(event: TEvent): event is TEvent & TurnFailureStreamEvent;
|
|
549
566
|
/**
|
|
550
567
|
* Creates the `session.started` event for one session.
|
|
551
568
|
*/
|
|
@@ -798,16 +815,15 @@ export declare function createSessionFailedEvent(input: {
|
|
|
798
815
|
*/
|
|
799
816
|
export declare function createSessionCompletedEvent(): SessionCompletedStreamEvent;
|
|
800
817
|
/**
|
|
801
|
-
* Stamps one session event with durable
|
|
802
|
-
* is written to the workflow-owned stream.
|
|
818
|
+
* Stamps one session event with its durable identity and emission time.
|
|
803
819
|
*
|
|
804
|
-
*
|
|
805
|
-
*
|
|
806
|
-
*
|
|
820
|
+
* Runtime/execution code only, once per event, immediately before the write.
|
|
821
|
+
* One stamping seam is what makes the persisted stream and authored hooks
|
|
822
|
+
* observe the same `meta.id`.
|
|
807
823
|
*/
|
|
808
|
-
export declare function
|
|
824
|
+
export declare function stampMessageStreamEvent(event: UnstampedMessageStreamEvent): MessageStreamEvent;
|
|
809
825
|
/**
|
|
810
826
|
* Encodes one message stream event as newline-delimited JSON.
|
|
811
827
|
*/
|
|
812
|
-
export declare function encodeMessageStreamEvent(event:
|
|
828
|
+
export declare function encodeMessageStreamEvent(event: MessageStreamEvent): Uint8Array;
|
|
813
829
|
export {};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{toChannelLocalContinuationToken}from"#shared/continuation-token.js";import{deserializeUrlFilePart,hasInternalRefScheme,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{decodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";const EVE_SESSION_ID_HEADER=`x-eve-session-id`,EVE_STREAM_FORMAT_HEADER=`x-eve-stream-format`,EVE_STREAM_TAIL_INDEX_HEADER=`x-eve-stream-tail-index`,EVE_STREAM_VERSION_HEADER=`x-eve-stream-version`,EVE_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,EVE_MESSAGE_STREAM_FORMAT=`ndjson`,EVE_MESSAGE_STREAM_VERSION=`
|
|
2
|
-
`)}function projectUserContentParts(e){if(typeof e==`string`)return[{text:e,type:`text`}];let t=[];for(let n of e)n.type===`text`?t.push({text:n.text,type:`text`}):n.type===`file`?t.push(projectFileLikePart(n.data,n.mediaType,n.filename)):n.type===`image`&&t.push(projectFileLikePart(n.image,n.mediaType??`application/octet-stream`,void 0));return t}function projectFileLikePart(e,t,n){if(isSandboxRefUrl(e)){let t=decodeSandboxRef(e);return createProjectedFilePart({filename:basenameOf(n??t.path),mediaType:t.mediaType,size:t.size})}let r=projectTaggedFileData(e,t,n);if(r!==void 0)return r;let i=byteLengthOf(e);return createProjectedFilePart(i===void 0?{filename:n,mediaType:t,...clientUrlFragment(e)}:{filename:n,mediaType:t,size:i})}function projectTaggedFileData(e,t,n){if(isTaggedFileData(e))switch(e.type){case`data`:{let r=byteLengthOf(e.data);return createProjectedFilePart(r===void 0?{filename:n,mediaType:t}:{filename:n,mediaType:t,size:r})}case`reference`:case`text`:return createProjectedFilePart({filename:n,mediaType:t});case`url`:return createProjectedFilePart({filename:n,mediaType:t,...clientUrlFragment(e.url)})}}function createProjectedFilePart(e){let t={mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),e.size!==void 0&&(t.size=e.size),e.url!==void 0&&(t.url=e.url),t}function isTaggedFileData(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`data`||t===`reference`||t===`text`||t===`url`}function byteLengthOf(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return e.byteLength}function clientUrlFragment(e){if(isSerializedUrlFilePart(e))try{let n=deserializeUrlFilePart(e);return isClientResolvableUrl(n)?{url:n.href}:{}}catch{return{}}if(e instanceof URL)return isClientResolvableUrl(e)?{url:e.href}:{};if(typeof e!=`string`||hasInternalRefScheme(e))return{};if(e.startsWith(`data:`))return{url:e};try{let t=new URL(e);return isClientResolvableUrl(t)?{url:t.href}:{}}catch{return{}}}function isClientResolvableUrl(e){return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`}function basenameOf(e){let t=e.replaceAll(`\\`,`/`),n=t.slice(t.lastIndexOf(`/`)+1);return n.length>0?n:e}function createActionsRequestedEvent(e){return{data:{actions:e.actions,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`actions.requested`}}function createAuthorizationRequiredEvent(e){let t={description:e.description,name:e.name,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.webhookUrl!==void 0&&(t.webhookUrl=e.webhookUrl),{data:t,type:`authorization.required`}}function createAuthorizationCompletedEvent(e){let t={name:e.name,outcome:e.outcome,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.reason!==void 0&&(t.reason=e.reason),{data:t,type:`authorization.completed`}}function createInputRequestedEvent(e){return{data:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`input.requested`}}function createActionResultEvent(e){let t=e.rejected===!0?{error:buildActionResultError(e.result),status:`rejected`}:normalizeActionResultOutcome(e.result);return{data:{error:t.error,result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,status:t.status,turnId:e.turnId},type:`action.result`}}function createSubagentCalledEvent(e){return{data:{callId:e.callId,childSessionId:e.childSessionId,sessionId:e.sessionId,sequence:e.sequence,name:e.name,remote:e.remote,toolName:e.toolName,turnId:e.turnId,workflowId:e.workflowId},type:`subagent.called`}}function createMessageAppendedEvent(e){return{data:{messageDelta:e.messageDelta,messageSoFar:e.messageSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.appended`}}function createReasoningAppendedEvent(e){return{data:{reasoningDelta:e.reasoningDelta,reasoningSoFar:e.reasoningSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.appended`}}function createMessageCompletedEvent(e){return{data:{finishReason:e.finishReason??`stop`,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.completed`}}function createReasoningCompletedEvent(e){return{data:{reasoning:e.reasoning,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.completed`}}function createResultCompletedEvent(e){return{data:{result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`result.completed`}}function createStepStartedEvent(e){return{data:{sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.started`}}function createStepCompletedEvent(e){let t={finishReason:e.finishReason,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.usage!==void 0&&(t.usage=e.usage),e.providerMetadata!==void 0&&(t.providerMetadata=e.providerMetadata),{data:t,type:`step.completed`}}function createStepFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.failed`}}function createTurnCompletedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.completed`}}function createTurnFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,turnId:e.turnId},type:`turn.failed`}}function createTurnCancelledEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.cancelled`}}function createCompactionRequestedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,usageInputTokens:e.usageInputTokens??null},type:`compaction.requested`}}function createCompactionCompletedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId},type:`compaction.completed`}}function createSessionWaitingEvent(t){return{data:{continuationToken:toChannelLocalContinuationToken(t),wait:`next-user-message`},type:`session.waiting`}}function createSessionFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sessionId:e.sessionId},type:`session.failed`}}function createSessionCompletedEvent(){return{type:`session.completed`}}function
|
|
1
|
+
import{toChannelLocalContinuationToken}from"#shared/continuation-token.js";import{deserializeUrlFilePart,hasInternalRefScheme,isSerializedUrlFilePart}from"#internal/attachments/url-refs.js";import{decodeSandboxRef,isSandboxRefUrl}from"#internal/attachments/sandbox-refs.js";import{createEventId}from"#protocol/event-id.js";const EVE_SESSION_ID_HEADER=`x-eve-session-id`,EVE_STREAM_FORMAT_HEADER=`x-eve-stream-format`,EVE_STREAM_TAIL_INDEX_HEADER=`x-eve-stream-tail-index`,EVE_STREAM_VERSION_HEADER=`x-eve-stream-version`,EVE_MESSAGE_STREAM_CONTENT_TYPE=`application/x-ndjson; charset=utf-8`,EVE_MESSAGE_STREAM_FORMAT=`ndjson`,EVE_MESSAGE_STREAM_VERSION=`20`,textEncoder=new TextEncoder;function isCurrentTurnBoundaryEvent(e){return e.type===`session.completed`||e.type===`session.failed`||e.type===`session.waiting`}function isTurnFailureEvent(e){return e.type===`session.failed`||e.type===`step.failed`||e.type===`turn.failed`}function createSessionStartedEvent(e){let t={};return e?.invocation!==void 0&&(t.invocation=e.invocation),e?.runtime!==void 0&&(t.runtime=e.runtime),{data:t,type:`session.started`}}function createTurnStartedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.started`}}function createMessageReceivedEvent(e){return{data:{message:summarizeUserContent(e.message),parts:projectUserContentParts(e.message),sequence:e.sequence,turnId:e.turnId},type:`message.received`}}function summarizeUserContent(e){if(typeof e==`string`)return e;let t=[];for(let n of e)if(n.type===`text`)t.push(n.text);else if(n.type===`file`){let e=n.filename??n.mediaType;t.push(`[file: ${e} (${n.mediaType})]`)}else n.type===`image`&&t.push(`[image: ${n.mediaType??`image`}]`);return t.join(`
|
|
2
|
+
`)}function projectUserContentParts(e){if(typeof e==`string`)return[{text:e,type:`text`}];let t=[];for(let n of e)n.type===`text`?t.push({text:n.text,type:`text`}):n.type===`file`?t.push(projectFileLikePart(n.data,n.mediaType,n.filename)):n.type===`image`&&t.push(projectFileLikePart(n.image,n.mediaType??`application/octet-stream`,void 0));return t}function projectFileLikePart(e,t,n){if(isSandboxRefUrl(e)){let t=decodeSandboxRef(e);return createProjectedFilePart({filename:basenameOf(n??t.path),mediaType:t.mediaType,size:t.size})}let r=projectTaggedFileData(e,t,n);if(r!==void 0)return r;let i=byteLengthOf(e);return createProjectedFilePart(i===void 0?{filename:n,mediaType:t,...clientUrlFragment(e)}:{filename:n,mediaType:t,size:i})}function projectTaggedFileData(e,t,n){if(isTaggedFileData(e))switch(e.type){case`data`:{let r=byteLengthOf(e.data);return createProjectedFilePart(r===void 0?{filename:n,mediaType:t}:{filename:n,mediaType:t,size:r})}case`reference`:case`text`:return createProjectedFilePart({filename:n,mediaType:t});case`url`:return createProjectedFilePart({filename:n,mediaType:t,...clientUrlFragment(e.url)})}}function createProjectedFilePart(e){let t={mediaType:e.mediaType,type:`file`};return e.filename!==void 0&&(t.filename=e.filename),e.size!==void 0&&(t.size=e.size),e.url!==void 0&&(t.url=e.url),t}function isTaggedFileData(e){if(typeof e!=`object`||!e)return!1;let t=e.type;return t===`data`||t===`reference`||t===`text`||t===`url`}function byteLengthOf(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return e.byteLength}function clientUrlFragment(e){if(isSerializedUrlFilePart(e))try{let n=deserializeUrlFilePart(e);return isClientResolvableUrl(n)?{url:n.href}:{}}catch{return{}}if(e instanceof URL)return isClientResolvableUrl(e)?{url:e.href}:{};if(typeof e!=`string`||hasInternalRefScheme(e))return{};if(e.startsWith(`data:`))return{url:e};try{let t=new URL(e);return isClientResolvableUrl(t)?{url:t.href}:{}}catch{return{}}}function isClientResolvableUrl(e){return e.protocol===`http:`||e.protocol===`https:`||e.protocol===`data:`}function basenameOf(e){let t=e.replaceAll(`\\`,`/`),n=t.slice(t.lastIndexOf(`/`)+1);return n.length>0?n:e}function createActionsRequestedEvent(e){return{data:{actions:e.actions,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`actions.requested`}}function createAuthorizationRequiredEvent(e){let t={description:e.description,name:e.name,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.webhookUrl!==void 0&&(t.webhookUrl=e.webhookUrl),{data:t,type:`authorization.required`}}function createAuthorizationCompletedEvent(e){let t={name:e.name,outcome:e.outcome,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.authorization!==void 0&&(t.authorization=e.authorization),e.reason!==void 0&&(t.reason=e.reason),{data:t,type:`authorization.completed`}}function createInputRequestedEvent(e){return{data:{requests:e.requests,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`input.requested`}}function createActionResultEvent(e){let t=e.rejected===!0?{error:buildActionResultError(e.result),status:`rejected`}:normalizeActionResultOutcome(e.result);return{data:{error:t.error,result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,status:t.status,turnId:e.turnId},type:`action.result`}}function createSubagentCalledEvent(e){return{data:{callId:e.callId,childSessionId:e.childSessionId,sessionId:e.sessionId,sequence:e.sequence,name:e.name,remote:e.remote,toolName:e.toolName,turnId:e.turnId,workflowId:e.workflowId},type:`subagent.called`}}function createMessageAppendedEvent(e){return{data:{messageDelta:e.messageDelta,messageSoFar:e.messageSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.appended`}}function createReasoningAppendedEvent(e){return{data:{reasoningDelta:e.reasoningDelta,reasoningSoFar:e.reasoningSoFar,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.appended`}}function createMessageCompletedEvent(e){return{data:{finishReason:e.finishReason??`stop`,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`message.completed`}}function createReasoningCompletedEvent(e){return{data:{reasoning:e.reasoning,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`reasoning.completed`}}function createResultCompletedEvent(e){return{data:{result:e.result,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`result.completed`}}function createStepStartedEvent(e){return{data:{sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.started`}}function createStepCompletedEvent(e){let t={finishReason:e.finishReason,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId};return e.usage!==void 0&&(t.usage=e.usage),e.providerMetadata!==void 0&&(t.providerMetadata=e.providerMetadata),{data:t,type:`step.completed`}}function createStepFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId},type:`step.failed`}}function createTurnCompletedEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.completed`}}function createTurnFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sequence:e.sequence,turnId:e.turnId},type:`turn.failed`}}function createTurnCancelledEvent(e){return{data:{sequence:e.sequence,turnId:e.turnId},type:`turn.cancelled`}}function createCompactionRequestedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId,usageInputTokens:e.usageInputTokens??null},type:`compaction.requested`}}function createCompactionCompletedEvent(e){return{data:{modelId:e.modelId,sequence:e.sequence,sessionId:e.sessionId,turnId:e.turnId},type:`compaction.completed`}}function createSessionWaitingEvent(t){return{data:{continuationToken:toChannelLocalContinuationToken(t),wait:`next-user-message`},type:`session.waiting`}}function createSessionFailedEvent(e){return{data:{code:e.code,details:e.details,message:e.message,sessionId:e.sessionId},type:`session.failed`}}function createSessionCompletedEvent(){return{type:`session.completed`}}function stampMessageStreamEvent(e){return{...e,meta:{at:new Date().toISOString(),id:createEventId()}}}function encodeMessageStreamEvent(e){return textEncoder.encode(`${JSON.stringify(e)}\n`)}function normalizeActionResultOutcome(e){if(e.isError===!0)return{error:buildActionResultError(e),status:`failed`};let t=readActionResultOutputError(e.output);return t===void 0?{status:`completed`}:{error:t,status:`failed`}}function buildActionResultError(e){let t=readActionResultOutputError(e.output);return t===void 0?{code:`ACTION_RESULT_FAILED`,message:formatActionResultOutput(e.output)}:t}function readActionResultOutputError(e){let t=parseActionResultOutputRecord(e);if(t===void 0)return;let n=typeof t.code==`string`&&t.code.length>0?t.code:void 0,r=typeof t.message==`string`&&t.message.length>0?t.message:void 0;if(!(n===void 0||r===void 0))return{code:n,message:r}}function parseActionResultOutputRecord(e){if(typeof e==`object`&&e)return e;if(typeof e!=`string`)return;let t=e.trim();if(t.length!==0)try{let e=JSON.parse(t);if(typeof e==`object`&&e)return e}catch{return}}function formatActionResultOutput(e){if(typeof e==`string`)return e;let t=JSON.stringify(e);return typeof t==`string`&&t.length>0?t:`Action failed.`}export{EVE_MESSAGE_STREAM_CONTENT_TYPE,EVE_MESSAGE_STREAM_FORMAT,EVE_MESSAGE_STREAM_VERSION,EVE_SESSION_ID_HEADER,EVE_STREAM_FORMAT_HEADER,EVE_STREAM_TAIL_INDEX_HEADER,EVE_STREAM_VERSION_HEADER,createActionResultEvent,createActionsRequestedEvent,createAuthorizationCompletedEvent,createAuthorizationRequiredEvent,createCompactionCompletedEvent,createCompactionRequestedEvent,createInputRequestedEvent,createMessageAppendedEvent,createMessageCompletedEvent,createMessageReceivedEvent,createReasoningAppendedEvent,createReasoningCompletedEvent,createResultCompletedEvent,createSessionCompletedEvent,createSessionFailedEvent,createSessionStartedEvent,createSessionWaitingEvent,createStepCompletedEvent,createStepFailedEvent,createStepStartedEvent,createSubagentCalledEvent,createTurnCancelledEvent,createTurnCompletedEvent,createTurnFailedEvent,createTurnStartedEvent,encodeMessageStreamEvent,isCurrentTurnBoundaryEvent,isTurnFailureEvent,stampMessageStreamEvent};
|
|
@@ -2,13 +2,13 @@ import type { DiscordInstrumentationMetadata } from "#public/channels/discord/in
|
|
|
2
2
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
3
3
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
4
4
|
import type { ChannelSessionOps } from "#public/definitions/channel.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
6
6
|
import { type DiscordApiOptions, type DiscordApiResponse, type DiscordCredentials, type DiscordMessageBody, type DiscordPostedMessage } from "#public/channels/discord/api.js";
|
|
7
7
|
import { type DiscordCommandInteraction } from "#public/channels/discord/inbound.js";
|
|
8
8
|
import { type DiscordWebhookVerifier } from "#public/channels/discord/verify.js";
|
|
9
9
|
import { type JsonObject } from "#shared/json.js";
|
|
10
10
|
import { type Channel } from "#public/definitions/channel.js";
|
|
11
|
-
type EventData<T extends
|
|
11
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
12
12
|
type: T;
|
|
13
13
|
}> extends {
|
|
14
14
|
data: infer D;
|
|
@@ -66,7 +66,7 @@ export type DiscordCommandResult = {
|
|
|
66
66
|
} | null;
|
|
67
67
|
/** Sync or async {@link DiscordCommandResult}. */
|
|
68
68
|
export type DiscordCommandResultOrPromise = DiscordCommandResult | Promise<DiscordCommandResult>;
|
|
69
|
-
type DiscordEventHandler<T extends
|
|
69
|
+
type DiscordEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: DiscordEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
70
70
|
type DiscordSessionFailedHandler = (data: EventData<"session.failed">, channel: DiscordEventContext) => void | Promise<void>;
|
|
71
71
|
/** Per-event handlers for `discordChannel({ events })`. Supplied handlers override built-in defaults per key; unspecified events keep their defaults. `session.failed` receives only `(data, channel)`; every other handler also gets the session `ctx`. */
|
|
72
72
|
export interface DiscordChannelEvents {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
2
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
3
3
|
import type { ChannelSessionOps } from "#public/definitions/channel.js";
|
|
4
|
-
import type {
|
|
4
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
5
5
|
import { type GitHubHandle, type GitHubThread } from "#public/channels/github/binding.js";
|
|
6
6
|
import { type GitHubApiOptions } from "#public/channels/github/api.js";
|
|
7
7
|
import type { GitHubChannelCredentials } from "#public/channels/github/auth.js";
|
|
@@ -9,7 +9,7 @@ import { type GitHubCheckRunEvent, type GitHubCheckSuiteEvent, type GitHubCommen
|
|
|
9
9
|
import { type GitHubChannelState } from "#public/channels/github/state.js";
|
|
10
10
|
import type { GitHubPullRequestContextConfig } from "#public/channels/github/pr-context.js";
|
|
11
11
|
import { type Channel } from "#public/definitions/channel.js";
|
|
12
|
-
type EventData<T extends
|
|
12
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
13
13
|
type: T;
|
|
14
14
|
}> extends {
|
|
15
15
|
data: infer D;
|
|
@@ -67,7 +67,7 @@ export type GitHubInboundResult = {
|
|
|
67
67
|
* promise for one.
|
|
68
68
|
*/
|
|
69
69
|
export type GitHubInboundResultOrPromise = GitHubInboundResult | Promise<GitHubInboundResult>;
|
|
70
|
-
type GitHubEventHandler<T extends
|
|
70
|
+
type GitHubEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: GitHubEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
71
71
|
type GitHubSessionFailedHandler = (data: EventData<"session.failed">, channel: GitHubEventContext) => void | Promise<void>;
|
|
72
72
|
/**
|
|
73
73
|
* Event handlers for `githubChannel({ events })`. The channel installs built-in
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
2
|
-
import type {
|
|
2
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
3
3
|
import { createLinearAgentActivity, listLinearAgentSessionActivities, updateLinearAgentSession, type LinearApiOptions } from "#public/channels/linear/api.js";
|
|
4
4
|
import type { LinearChannelCredentials } from "#public/channels/linear/auth.js";
|
|
5
5
|
import { type LinearAgentSessionEvent, type LinearAgentSessionRef, type LinearDataWebhookEvent, type LinearDelivery } from "#public/channels/linear/inbound.js";
|
|
6
6
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
7
7
|
import { type Channel, type ChannelSessionOps } from "#public/definitions/channel.js";
|
|
8
8
|
import type { JsonObject } from "#shared/json.js";
|
|
9
|
-
type EventData<T extends
|
|
9
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
10
10
|
type: T;
|
|
11
11
|
}> extends {
|
|
12
12
|
data: infer D;
|
|
@@ -90,7 +90,7 @@ export interface LinearHandle {
|
|
|
90
90
|
readonly success: boolean;
|
|
91
91
|
}>;
|
|
92
92
|
}
|
|
93
|
-
type LinearEventHandler<T extends
|
|
93
|
+
type LinearEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: LinearEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
94
94
|
type LinearSessionFailedHandler = (data: EventData<"session.failed">, channel: LinearEventContext) => void | Promise<void>;
|
|
95
95
|
/** Event handlers supported by `linearChannel({ events })`. */
|
|
96
96
|
export interface LinearChannelEvents {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{SLACK_SECTION_TEXT_MAX_LENGTH,truncateCardBodyText,truncateModalTitle,truncatePlainText,truncateSectionText}from"#public/channels/slack/limits.js";const HITL_ACTION_PREFIX=`eve_input:`,HITL_FREEFORM_ACTION_PREFIX=`eve_input_freeform:`,HITL_FREEFORM_MODAL_CALLBACK_ID=`eve_input_freeform_submit`,HITL_FREEFORM_MODAL_BLOCK_ID=`eve_freeform_block`,HITL_FREEFORM_MODAL_ACTION_ID=`eve_freeform_text`,BUTTON_ACTION_ID_RE=/^(?<requestId>.+):button:\d+$/u,TOOL_INPUT_SUFFIX="\n```";function deriveHitlResponse(e){if(!e.actionId.startsWith(`eve_input:`))return null;let t=e.actionId.slice(10);if(e.selectedOptionValue!==void 0)return t?{optionId:e.selectedOptionValue,requestId:t}:null;if(e.value!==void 0){let n=BUTTON_ACTION_ID_RE.exec(t)?.groups?.requestId;return n?{optionId:e.value,requestId:n}:null}return null}function isHitlAction(e){return e.startsWith(HITL_ACTION_PREFIX)}function renderInputRequestBlocks(e){let t={text:{text:truncateSectionText(e.prompt),type:`mrkdwn`},type:`section`},n=renderInputRequestDetailBlocks(e),r=`${HITL_ACTION_PREFIX}${e.requestId}`,a=e.options,o=e.allowFreeform===!0||!a||a.length===0;if(a&&a.length>0&&e.display===`select`){let e=a.length<=6?{type:`radio_buttons`,action_id:r,options:a.map(buildOption)}:{type:`static_select`,action_id:r,options:a.map(buildOption),placeholder:{type:`plain_text`,text:`Choose an option`}};return[t,...n,{type:`actions`,elements:[e]}]}if(a&&a.length>0){let t=renderInputRequestCardBlock(e,r),n=renderToolInputContainerBlock(e);return n===void 0?[t]:[t,n]}return o?[t,...n,{type:`actions`,elements:[{type:`button`,action_id:`${HITL_FREEFORM_ACTION_PREFIX}${e.requestId}`,text:{type:`plain_text`,text:`Type your answer`},style:`primary`,value:e.requestId}]}]:[t]}function formatInputRequestFallbackText(e){let t=formatToolInputDetails(e);return t===void 0?e.prompt:`${e.prompt}\n${t}`}function buildFreeformModalView(e){let t=e.prompt?truncateModalTitle(e.prompt):`Your answer`,r=e.prompt?[{type:`section`,text:{type:`mrkdwn`,text:truncateSectionText(e.prompt)}}]:[];return{type:`modal`,callback_id:HITL_FREEFORM_MODAL_CALLBACK_ID,private_metadata:JSON.stringify(e.metadata),title:{type:`plain_text`,text:t},submit:{type:`plain_text`,text:`Submit`},close:{type:`plain_text`,text:`Cancel`},blocks:[...r,{type:`input`,block_id:HITL_FREEFORM_MODAL_BLOCK_ID,element:{type:`plain_text_input`,action_id:HITL_FREEFORM_MODAL_ACTION_ID,multiline:!0,placeholder:{type:`plain_text`,text:`Type your answer here...`}},label:{type:`plain_text`,text:`Answer`}}]}}function isFreeformAction(e){return e.startsWith(HITL_FREEFORM_ACTION_PREFIX)}function freeformRequestIdFromActionId(e){if(!isFreeformAction(e))return;let t=e.slice(19);return t.length>0?t:void 0}function buildCardButton(e,t,n){let i={type:`button`,text:{type:`plain_text`,text:truncatePlainText(e.label),emoji:!1},action_id:`${t}:button:${n}`,value:e.id};return(e.style===`primary`||e.style===`danger`)&&(i.style=e.style),i}function buildOption(e){let t={text:{text:truncatePlainText(e.label),type:`plain_text`},value:e.id},n=truncatePlainText(e.description);return n&&n.length>0&&(t.description={text:n,type:`plain_text`}),t}function renderInputRequestCardBlock(e,n){return{type:`card`,body:{type:`mrkdwn`,text:truncateCardBodyText(`*${e.prompt}*`),verbatim:!1},actions:cardButtonOptions(e).map((e,t)=>buildCardButton(e,n,t))}}function cardButtonOptions(e){let t=e.options??[];if(!isApprovalRequest(e))return t.map(toCardButtonOption);let n=t.find(e=>e.id===`approve`),r=t.find(e=>e.id===`deny`);return!n||!r?t.map(toCardButtonOption):[{id:r.id,label:`Deny`},{id:n.id,label:`Allow`,style:`primary`}]}function toCardButtonOption(e){let t={id:e.id,label:e.label};return e.style===`primary`||e.style===`danger`?{...t,style:e.style}:t}function buildAnsweredBlocks(t){let n=[];for(let e of t.promptBlocks)e!=null&&n.push(e);let r=truncateWithEllipsis(t.answerLabel,SLACK_SECTION_TEXT_MAX_LENGTH-20-1);return n.push({type:`section`,text:{type:`mrkdwn`,text:`:white_check_mark: *${r}*`}}),t.userId&&t.userId.length>0&&n.push({type:`context`,elements:[{type:`mrkdwn`,text:`Answered by <@${t.userId}>`}]}),n}function renderInputRequestDetailBlocks(e){let t=formatToolInputDetails(e);return t===void 0?[]:[{type:`section`,text:{type:`mrkdwn`,text:t}}]}function renderToolInputContainerBlock(e){let t=formatToolInputContainerText(e);if(t!==void 0)return{type:`container`,title:{type:`plain_text`,text:`Tool input`},is_collapsible:!0,default_collapsed:!1,child_blocks:[{type:`section`,text:{type:`mrkdwn`,text:t}}]}}function formatToolInputContainerText(t){if(!isApprovalRequest(t))return;let n=JSON.stringify(t.action.input,null,2);return n===`{}`?void 0:`\`\`\`
|
|
2
2
|
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-4-4)}${TOOL_INPUT_SUFFIX}`}function formatToolInputDetails(t){if(!isApprovalRequest(t))return;let n=JSON.stringify(t.action.input,null,2);return n===`{}`?void 0:`*Tool input*
|
|
3
3
|
\`\`\`
|
|
4
|
-
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-17-4)}${TOOL_INPUT_SUFFIX}`}function truncateWithEllipsis(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function isApprovalRequest(e){return e.
|
|
4
|
+
${truncateWithEllipsis(n,SLACK_SECTION_TEXT_MAX_LENGTH-17-4)}${TOOL_INPUT_SUFFIX}`}function truncateWithEllipsis(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}function isApprovalRequest(e){return e.kind===`tool-approval`}export{HITL_ACTION_PREFIX,HITL_FREEFORM_ACTION_PREFIX,HITL_FREEFORM_MODAL_ACTION_ID,HITL_FREEFORM_MODAL_BLOCK_ID,HITL_FREEFORM_MODAL_CALLBACK_ID,buildAnsweredBlocks,buildFreeformModalView,deriveHitlResponse,formatInputRequestFallbackText,freeformRequestIdFromActionId,isFreeformAction,isHitlAction,renderInputRequestBlocks};
|
|
@@ -4,14 +4,14 @@ import type { CancelTurnResult, SessionAuthContext } from "#channel/types.js";
|
|
|
4
4
|
import type { CardElement } from "#compiled/chat/index.js";
|
|
5
5
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
6
6
|
import type { ChannelSessionOps } from "#public/definitions/channel.js";
|
|
7
|
-
import type {
|
|
7
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
8
8
|
import { type SlackBotToken, type SlackHandle, type SlackThread, type SlackWorkspaceHandle } from "#public/channels/slack/api.js";
|
|
9
9
|
import { type SlackEvent, type SlackEventEnvelope, type SlackMessage } from "#public/channels/slack/inbound.js";
|
|
10
10
|
import { type LoadThreadContextMessagesOptions } from "#public/channels/slack/thread.js";
|
|
11
11
|
import { type UploadPolicyInput } from "#public/channels/upload-policy.js";
|
|
12
12
|
import { type SlackWebhookVerifier } from "#public/channels/slack/verify.js";
|
|
13
13
|
import { type Channel, type ResetResult } from "#public/definitions/channel.js";
|
|
14
|
-
type EventData<T extends
|
|
14
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
15
15
|
type: T;
|
|
16
16
|
}> extends {
|
|
17
17
|
data: infer D;
|
|
@@ -46,7 +46,7 @@ export interface SlackEventContext extends SlackChannelContext, ChannelSessionOp
|
|
|
46
46
|
}
|
|
47
47
|
export type { SlackApiResponse, SlackBotToken, SlackHandle, SlackThread, SlackWorkspaceHandle, } from "#public/channels/slack/api.js";
|
|
48
48
|
export type { SlackWebhookVerifier } from "#public/channels/slack/verify.js";
|
|
49
|
-
type SlackEventHandler<T extends
|
|
49
|
+
type SlackEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: SlackEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
50
50
|
/**
|
|
51
51
|
* Delivery surface handed to `authorization.required` overrides. The
|
|
52
52
|
* connection challenge is a credential: anyone who completes the sign-in
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{TEAMS_ADAPTIVE_CARD_ACTION_LIMIT,TEAMS_ADAPTIVE_CARD_ACTION_TITLE_MAX_LENGTH,TEAMS_ADAPTIVE_CARD_CHOICE_TITLE_MAX_LENGTH,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH}from"#public/channels/teams/limits.js";const TEAMS_ADAPTIVE_CARD_CONTENT_TYPE=`application/vnd.microsoft.card.adaptive`,TEAMS_HITL_DATA_KEY=`eve_input`,TEAMS_HITL_CHOICE_INPUT_ID=`eve_option`,TEAMS_HITL_FREEFORM_INPUT_ID=`eve_freeform_text`;function renderInputRequestMessage(e,t={}){let n=formatApprovalInput(e),r=n?truncate(n,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH):null;return{attachments:[renderInputRequestAttachment(e,t)],text:r?`${e.prompt}\n\nTool input:\n${r}`:e.prompt}}function renderInputRequestAttachment(e,n={}){let r=formatApprovalInput(e);return{content:parseJsonObject({$schema:`http://adaptivecards.io/schemas/adaptive-card.json`,actions:renderActions(e,n.replyToActivityId),body:[{text:truncate(e.prompt,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0},...r?[{fontType:`Monospace`,text:truncate(r,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0}]:[],...renderInputs(e)],type:`AdaptiveCard`,version:n.adaptiveCardVersion??`1.5`}),contentType:TEAMS_ADAPTIVE_CARD_CONTENT_TYPE}}function renderAnsweredInputRequestMessage(e){return{attachments:[{content:parseJsonObject({$schema:`http://adaptivecards.io/schemas/adaptive-card.json`,body:[{text:truncate(e.prompt,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0},{color:`good`,text:e.label?`Answered: ${e.label}`:`Answered`,type:`TextBlock`,wrap:!0}],type:`AdaptiveCard`,version:`1.5`}),contentType:TEAMS_ADAPTIVE_CARD_CONTENT_TYPE}],text:e.label?`Answered: ${e.label}`:`Answered`}}function isTeamsInputResponseActivity(e){return deriveTeamsInputResponses(e).length>0}function deriveTeamsInputResponses(e){let t=readActivityValue(e);if(!t)return[];let n=readHitlPayload(t);if(!n)return[];let r=typeof n.requestId==`string`?n.requestId:``;if(!r)return[];let i=typeof n.optionId==`string`?n.optionId:typeof t.eve_option==`string`?t[TEAMS_HITL_CHOICE_INPUT_ID]:void 0,a=typeof t.eve_freeform_text==`string`?t[TEAMS_HITL_FREEFORM_INPUT_ID]:void 0;return i===void 0?a===void 0?[{requestId:r}]:[{requestId:r,text:a}]:[{optionId:i,requestId:r}]}function readTeamsInputReplyToActivityId(e){let t=readActivityValue(e);if(!t)return null;let n=readHitlPayload(t);return n&&typeof n.replyToActivityId==`string`?n.replyToActivityId:null}function teamsInvokeResponse(e={}){return{statusCode:e.statusCode??200,type:`application/vnd.microsoft.activity.message`,value:e.message??`Answer received.`}}function renderInputs(e){return e.display===`select`&&e.options&&e.options.length>0?[{choices:e.options.map(e=>({title:truncate(e.label,TEAMS_ADAPTIVE_CARD_CHOICE_TITLE_MAX_LENGTH),value:e.id})),id:TEAMS_HITL_CHOICE_INPUT_ID,isMultiSelect:!1,style:`compact`,type:`Input.ChoiceSet`}]:e.allowFreeform===!0||!e.options||e.options.length===0?[{id:TEAMS_HITL_FREEFORM_INPUT_ID,isMultiline:!0,placeholder:`Type your answer`,type:`Input.Text`}]:[]}function renderActions(e,t){let payload=n=>{let r={requestId:e.requestId};return t!==void 0&&(r.replyToActivityId=t),n!==void 0&&(r.optionId=n),r},i=e.options;return i&&i.length>0&&e.display!==`select`?i.slice(0,TEAMS_ADAPTIVE_CARD_ACTION_LIMIT).map(e=>({data:{[TEAMS_HITL_DATA_KEY]:payload(e.id)},title:truncate(e.label,TEAMS_ADAPTIVE_CARD_ACTION_TITLE_MAX_LENGTH),type:`Action.Submit`})):[{data:{[TEAMS_HITL_DATA_KEY]:payload()},title:`Submit`,type:`Action.Submit`}]}function readActivityValue(e){return e.type===`message`?readMessageValue(e):e.type===`invoke`?readInvokeValue(e):null}function readMessageValue(e){return e.value??null}function readInvokeValue(t){let n=t.value;if(!n)return null;let r=isObject(n.action)?n.action:null;return(r&&isObject(r.data)?r.data:null)??n}function readHitlPayload(t){let n=t[TEAMS_HITL_DATA_KEY];if(isObject(n))return n;let r=isObject(t.action)?t.action:null,i=(r&&isObject(r.data)?r.data:null)?.[TEAMS_HITL_DATA_KEY];return isObject(i)?i:null}function formatApprovalInput(e){if(e.
|
|
1
|
+
import{isObject}from"#shared/guards.js";import{parseJsonObject}from"#shared/json.js";import{TEAMS_ADAPTIVE_CARD_ACTION_LIMIT,TEAMS_ADAPTIVE_CARD_ACTION_TITLE_MAX_LENGTH,TEAMS_ADAPTIVE_CARD_CHOICE_TITLE_MAX_LENGTH,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH}from"#public/channels/teams/limits.js";const TEAMS_ADAPTIVE_CARD_CONTENT_TYPE=`application/vnd.microsoft.card.adaptive`,TEAMS_HITL_DATA_KEY=`eve_input`,TEAMS_HITL_CHOICE_INPUT_ID=`eve_option`,TEAMS_HITL_FREEFORM_INPUT_ID=`eve_freeform_text`;function renderInputRequestMessage(e,t={}){let n=formatApprovalInput(e),r=n?truncate(n,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH):null;return{attachments:[renderInputRequestAttachment(e,t)],text:r?`${e.prompt}\n\nTool input:\n${r}`:e.prompt}}function renderInputRequestAttachment(e,n={}){let r=formatApprovalInput(e);return{content:parseJsonObject({$schema:`http://adaptivecards.io/schemas/adaptive-card.json`,actions:renderActions(e,n.replyToActivityId),body:[{text:truncate(e.prompt,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0},...r?[{fontType:`Monospace`,text:truncate(r,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0}]:[],...renderInputs(e)],type:`AdaptiveCard`,version:n.adaptiveCardVersion??`1.5`}),contentType:TEAMS_ADAPTIVE_CARD_CONTENT_TYPE}}function renderAnsweredInputRequestMessage(e){return{attachments:[{content:parseJsonObject({$schema:`http://adaptivecards.io/schemas/adaptive-card.json`,body:[{text:truncate(e.prompt,TEAMS_ADAPTIVE_CARD_TEXT_MAX_LENGTH),type:`TextBlock`,wrap:!0},{color:`good`,text:e.label?`Answered: ${e.label}`:`Answered`,type:`TextBlock`,wrap:!0}],type:`AdaptiveCard`,version:`1.5`}),contentType:TEAMS_ADAPTIVE_CARD_CONTENT_TYPE}],text:e.label?`Answered: ${e.label}`:`Answered`}}function isTeamsInputResponseActivity(e){return deriveTeamsInputResponses(e).length>0}function deriveTeamsInputResponses(e){let t=readActivityValue(e);if(!t)return[];let n=readHitlPayload(t);if(!n)return[];let r=typeof n.requestId==`string`?n.requestId:``;if(!r)return[];let i=typeof n.optionId==`string`?n.optionId:typeof t.eve_option==`string`?t[TEAMS_HITL_CHOICE_INPUT_ID]:void 0,a=typeof t.eve_freeform_text==`string`?t[TEAMS_HITL_FREEFORM_INPUT_ID]:void 0;return i===void 0?a===void 0?[{requestId:r}]:[{requestId:r,text:a}]:[{optionId:i,requestId:r}]}function readTeamsInputReplyToActivityId(e){let t=readActivityValue(e);if(!t)return null;let n=readHitlPayload(t);return n&&typeof n.replyToActivityId==`string`?n.replyToActivityId:null}function teamsInvokeResponse(e={}){return{statusCode:e.statusCode??200,type:`application/vnd.microsoft.activity.message`,value:e.message??`Answer received.`}}function renderInputs(e){return e.display===`select`&&e.options&&e.options.length>0?[{choices:e.options.map(e=>({title:truncate(e.label,TEAMS_ADAPTIVE_CARD_CHOICE_TITLE_MAX_LENGTH),value:e.id})),id:TEAMS_HITL_CHOICE_INPUT_ID,isMultiSelect:!1,style:`compact`,type:`Input.ChoiceSet`}]:e.allowFreeform===!0||!e.options||e.options.length===0?[{id:TEAMS_HITL_FREEFORM_INPUT_ID,isMultiline:!0,placeholder:`Type your answer`,type:`Input.Text`}]:[]}function renderActions(e,t){let payload=n=>{let r={requestId:e.requestId};return t!==void 0&&(r.replyToActivityId=t),n!==void 0&&(r.optionId=n),r},i=e.options;return i&&i.length>0&&e.display!==`select`?i.slice(0,TEAMS_ADAPTIVE_CARD_ACTION_LIMIT).map(e=>({data:{[TEAMS_HITL_DATA_KEY]:payload(e.id)},title:truncate(e.label,TEAMS_ADAPTIVE_CARD_ACTION_TITLE_MAX_LENGTH),type:`Action.Submit`})):[{data:{[TEAMS_HITL_DATA_KEY]:payload()},title:`Submit`,type:`Action.Submit`}]}function readActivityValue(e){return e.type===`message`?readMessageValue(e):e.type===`invoke`?readInvokeValue(e):null}function readMessageValue(e){return e.value??null}function readInvokeValue(t){let n=t.value;if(!n)return null;let r=isObject(n.action)?n.action:null;return(r&&isObject(r.data)?r.data:null)??n}function readHitlPayload(t){let n=t[TEAMS_HITL_DATA_KEY];if(isObject(n))return n;let r=isObject(t.action)?t.action:null,i=(r&&isObject(r.data)?r.data:null)?.[TEAMS_HITL_DATA_KEY];return isObject(i)?i:null}function formatApprovalInput(e){if(e.kind!==`tool-approval`)return null;let t=JSON.stringify(e.action.input,null,2);return t===`{}`?null:t}function truncate(e,t){if(e.length<=t)return e;let n=Math.max(0,t-3);return`${e.slice(0,n).trimEnd()}...`}export{TEAMS_ADAPTIVE_CARD_CONTENT_TYPE,TEAMS_HITL_CHOICE_INPUT_ID,TEAMS_HITL_DATA_KEY,TEAMS_HITL_FREEFORM_INPUT_ID,deriveTeamsInputResponses,isTeamsInputResponseActivity,readTeamsInputReplyToActivityId,renderAnsweredInputRequestMessage,renderInputRequestAttachment,renderInputRequestMessage,teamsInvokeResponse};
|
|
@@ -2,14 +2,14 @@ import type { TeamsInstrumentationMetadata } from "#public/channels/teams/index.
|
|
|
2
2
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
3
3
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
4
4
|
import type { ChannelSessionOps } from "#public/definitions/channel.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
6
6
|
import { type TeamsFilesConfig } from "#public/channels/teams/attachments.js";
|
|
7
7
|
import { type TeamsApiOptions, type TeamsApiResponse, type TeamsChannelAccount, type TeamsCredentials, type TeamsMention, type TeamsMessageBody, type TeamsOutboundActivity, type TeamsPostedActivity } from "#public/channels/teams/api.js";
|
|
8
8
|
import { type TeamsInvokeActivity, type TeamsMessageActivity } from "#public/channels/teams/inbound.js";
|
|
9
9
|
import { type TeamsWebhookVerifier } from "#public/channels/teams/verify.js";
|
|
10
10
|
import { type JsonObject } from "#shared/json.js";
|
|
11
11
|
import { type Channel } from "#public/definitions/channel.js";
|
|
12
|
-
type EventData<T extends
|
|
12
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
13
13
|
type: T;
|
|
14
14
|
}> extends {
|
|
15
15
|
data: infer D;
|
|
@@ -92,7 +92,7 @@ export type TeamsInputResponseResult = {
|
|
|
92
92
|
export type TeamsInvokeResult = Record<string, unknown> | Response | null | undefined;
|
|
93
93
|
/** Sync or async {@link TeamsInvokeResult}. */
|
|
94
94
|
export type TeamsInvokeResultOrPromise = TeamsInvokeResult | Promise<TeamsInvokeResult>;
|
|
95
|
-
type TeamsEventHandler<T extends
|
|
95
|
+
type TeamsEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: TeamsEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
96
96
|
type TeamsSessionFailedHandler = (data: EventData<"session.failed">, channel: TeamsEventContext) => void | Promise<void>;
|
|
97
97
|
/** Event handlers supported by `teamsChannel({ events })`. */
|
|
98
98
|
export interface TeamsChannelEvents {
|
|
@@ -2,7 +2,7 @@ import type { TelegramInstrumentationMetadata } from "#public/channels/telegram/
|
|
|
2
2
|
import type { SessionAuthContext } from "#channel/types.js";
|
|
3
3
|
import type { SessionContext } from "#public/definitions/callback-context.js";
|
|
4
4
|
import type { ChannelSessionOps } from "#public/definitions/channel.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { UnstampedMessageStreamEvent } from "#protocol/message.js";
|
|
6
6
|
import { type TelegramApiOptions, type TelegramApiResponse, type TelegramCredentials, type TelegramMessageBody, type TelegramMessageResult } from "#public/channels/telegram/api.js";
|
|
7
7
|
import { type TelegramHitlState } from "#public/channels/telegram/hitl.js";
|
|
8
8
|
import { type TelegramCallbackQuery, type TelegramChatType, type TelegramMessage } from "#public/channels/telegram/inbound.js";
|
|
@@ -10,7 +10,7 @@ import { type UploadPolicyInput } from "#public/channels/upload-policy.js";
|
|
|
10
10
|
import { type TelegramWebhookSecretToken, type TelegramWebhookVerifier } from "#public/channels/telegram/verify.js";
|
|
11
11
|
import { type Channel } from "#public/definitions/channel.js";
|
|
12
12
|
import { type JsonObject } from "#shared/json.js";
|
|
13
|
-
type EventData<T extends
|
|
13
|
+
type EventData<T extends UnstampedMessageStreamEvent["type"]> = Extract<UnstampedMessageStreamEvent, {
|
|
14
14
|
type: T;
|
|
15
15
|
}> extends {
|
|
16
16
|
data: infer D;
|
|
@@ -61,7 +61,7 @@ export type TelegramInboundResult = {
|
|
|
61
61
|
} | null;
|
|
62
62
|
/** Sync or async {@link TelegramInboundResult}. */
|
|
63
63
|
export type TelegramInboundResultOrPromise = TelegramInboundResult | Promise<TelegramInboundResult>;
|
|
64
|
-
type TelegramEventHandler<T extends
|
|
64
|
+
type TelegramEventHandler<T extends UnstampedMessageStreamEvent["type"]> = (data: EventData<T>, channel: TelegramEventContext, ctx: SessionContext) => void | Promise<void>;
|
|
65
65
|
type TelegramSessionFailedHandler = (data: EventData<"session.failed">, channel: TelegramEventContext) => void | Promise<void>;
|
|
66
66
|
/** Per-event handlers for `telegramChannel({ events })`. Each entry overrides the built-in default (handlers merge over {@link defaultEvents}). `session.failed` receives `(data, channel)`; all others also receive the {@link SessionContext}. */
|
|
67
67
|
export interface TelegramChannelEvents {
|