@economic/agents 2.7.2 → 3.0.0-alpha.32271766282.1.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/dist/index.d.mts CHANGED
@@ -1,84 +1,91 @@
1
- import { n as JwtAuthConfig, t as routeAgentRequest } from "./route-agent-request-D2ll--nF.mjs";
2
- import { Agent as Agent$1, Connection, ConnectionContext, SubAgentClass } from "agents";
3
- import { ChatResponseResult, PrepareStepContext, Session, Think, ToolCallContext, ToolCallDecision, TurnConfig, TurnContext, skills } from "@cloudflare/think";
1
+ import { ChatResponseResult, PrepareStepContext, Session, StepContext, Think, ToolCallContext, ToolCallDecision, ToolCallResultContext, TurnConfig, TurnContext, skills } from "@cloudflare/think";
4
2
  import { JSONValue, LanguageModel, ModelMessage, Tool as Tool$1, UIMessage } from "ai";
3
+ import { Agent, AgentOptions, Connection, ConnectionContext, SubAgentClass } from "agents";
5
4
  import { createCompactFunction } from "agents/experimental/memory/utils";
6
5
  import { SkillSource as SkillSource$1 } from "agents/skills";
7
6
 
8
7
  //#region src/server/types.d.ts
9
8
  /**
10
- * The context object available throughout an agent's lifetime — passed via
11
- * `experimental_context` to tool `execute` functions. Contains the typed
12
- * request body merged with platform capabilities like `logEvent`.ext = AgentToolContext<MyBody>;
13
- * ```
9
+ * Context passed to tool `execute` functions through `experimental_context`.
10
+ * It contains the request context plus authenticated values supplied by the agent.
14
11
  */
15
12
  type ToolContext<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext = Record<string, unknown> | undefined> = RequestContext & {
13
+ _token?: string;
16
14
  _userContext?: UserContext;
17
15
  };
18
16
  interface AgentEnv {
19
17
  AGENTS_DB: D1Database;
20
18
  AGENTS_AUDIT_LOGS: R2Bucket;
21
- AGENTS_ANALYTICS: AnalyticsEngineDataset;
22
- SKILLS_BUCKET: R2Bucket;
23
- LOCAL_AGENT_DB?: D1Database;
19
+ AGENTS_ANALYTICS?: AnalyticsEngineDataset;
24
20
  }
25
21
  type AgentConnectionStatus = "connecting" | "connected" | "disconnected" | "unauthorized" | "error";
26
- type AgentConnectionType = "agent" | "chat" | "assistant";
22
+ type AgentConnectionType = "chat" | "assistant";
27
23
  //#endregion
28
- //#region src/server/features/auth/tokenExchange.d.ts
29
- interface TokenExchangeConfig {
30
- /** Identity server token endpoint, e.g. `${identityOrigin}/connect/token`. */
31
- tokenUrl: string;
32
- /** OAuth client the agent authenticates as. */
33
- clientId: string;
34
- /**
35
- * Plain secret, or a binding resolved with `get()` (e.g. a Cloudflare
36
- * Secrets Store binding). Resolved on every exchange so rotation is
37
- * picked up without a redeploy.
38
- */
39
- clientSecret: string | {
40
- get(): Promise<string>;
41
- };
42
- /**
43
- * Space-separated scopes for the exchanged token. Always sent explicitly:
44
- * omitting `scope` would make the identity server issue every scope the
45
- * client is allowed, the opposite of least privilege.
46
- */
47
- scopes: string;
48
- /**
49
- * Key under the request-context `tokens` record that tools read the token
50
- * from. Defaults to {@link DEFAULT_TOKEN_HEADER}.
51
- */
52
- tokenHeader?: string;
24
+ //#region src/server/features/messages.d.ts
25
+ type MessageFeedbackRating = 1 | -1 | 0;
26
+ type MessageFeedback = {
27
+ message_id: string;
28
+ rating: Exclude<MessageFeedbackRating, 0>;
29
+ comment?: string;
30
+ created_at: number;
31
+ updated_at: number;
32
+ };
33
+ //#endregion
34
+ //#region src/server/features/auth/index.d.ts
35
+ interface JwtVerificationOptions {
36
+ /** Issuers whose tokens are accepted (exact string or RegExp). */
37
+ allowedIssuers: readonly (string | RegExp)[];
38
+ /** Expected `aud` claim. */
39
+ audience: string;
40
+ /** Required OAuth scopes; token `scope` must include all (empty = no scope check). */
41
+ requiredScopes?: readonly string[];
53
42
  }
54
- interface ExchangedToken {
55
- accessToken: string;
56
- /** Unix ms; already includes {@link EXPIRY_MARGIN_MS}. */
57
- expiresAt: number;
43
+ type ClaimsMapper<TClaims extends Record<string, unknown>> = Record<string, unknown> extends TClaims ? {
44
+ /** Extract selected claims, or omit this to receive the complete verified payload. */getClaims?: (payload: Record<string, unknown>) => TClaims;
45
+ } : {
46
+ /** Extract and validate the custom claims exposed by this configuration. */getClaims: (payload: Record<string, unknown>) => TClaims;
47
+ };
48
+ type JwtVerificationConfig<TClaims extends Record<string, unknown> = Record<string, unknown>> = JwtVerificationOptions & ClaimsMapper<TClaims>;
49
+ //#endregion
50
+ //#region src/server/features/auth/authenticate.d.ts
51
+ interface Authenticated<TUserContext extends Record<string, unknown> = Record<string, unknown>> {
52
+ authenticated: true;
53
+ /** Optional downstream credential exposed to tools as `ctx._token`. */
54
+ token?: string;
55
+ userContext?: TUserContext;
58
56
  }
59
- type TokenExchangeResult = ({
60
- success: true;
61
- } & ExchangedToken) | {
62
- success: false;
63
- status: number;
64
- errorCode: string;
57
+ interface AuthenticationDenied {
58
+ authenticated: false;
59
+ status: 401 | 403;
65
60
  message: string;
61
+ }
62
+ type AuthenticationResult<TUserContext extends Record<string, unknown> = Record<string, unknown>> = Authenticated<TUserContext> | AuthenticationDenied;
63
+ /** A generic authentication mechanism used by ChatAgent, Assistant, and TaskAgent. */
64
+ interface Authenticator<TUserContext extends Record<string, unknown> = Record<string, unknown>> {
65
+ authenticate(request: Request): Promise<AuthenticationResult<TUserContext>>;
66
+ }
67
+ interface JwtAuthenticationContext<TClaims extends Record<string, unknown>> {
68
+ /** The verified token, or the value returned by `getExchangedToken`. */
69
+ token: string;
70
+ claims: TClaims;
71
+ }
72
+ type GetExchangedToken<TClaims extends Record<string, unknown>> = (context: JwtAuthenticationContext<TClaims>) => Promise<string> | string;
73
+ interface JwtAuthenticatorConfig<TClaims extends Record<string, unknown> = Record<string, unknown>, TUserContext extends Record<string, unknown> = Record<string, unknown>> {
74
+ /** Configuration consumed by the SDK's built-in JWT verification. */
75
+ verificationConfig: JwtVerificationConfig<TClaims>;
66
76
  /**
67
- * True when the identity server rejected the subject token itself
68
- * (RFC 6749 `invalid_grant`: expired or revoked). Re-authenticating is
69
- * the only fix — other failures (`invalid_client`, `invalid_scope`,
70
- * 5xx) are deployment or identity-server faults the user cannot fix by
71
- * logging in again.
77
+ * Optional consumer-defined exchange. It runs once after verification and
78
+ * receives the verified token and claims.
72
79
  */
73
- subjectTokenRejected: boolean;
74
- };
80
+ getExchangedToken?: GetExchangedToken<TClaims>;
81
+ getUserContext?: (context: JwtAuthenticationContext<TClaims>) => Promise<TUserContext> | TUserContext;
82
+ }
75
83
  /**
76
- * Exchange `subjectToken` for a token issued to the agent's own OAuth client.
77
- *
78
- * Expected identity-server rejections return a failure result; unexpected
79
- * failures (network error, timeout, malformed success response) throw.
84
+ * Creates an authenticator that extracts a bearer JWT, verifies it once,
85
+ * optionally lets the consumer exchange it once, then uses the final token
86
+ * for user-context resolution and tool calls.
80
87
  */
81
- declare function exchangeToken(subjectToken: string, config: TokenExchangeConfig): Promise<TokenExchangeResult>;
88
+ declare function createJwtAuthenticator<TClaims extends Record<string, unknown>, TUserContext extends Record<string, unknown> = Record<string, unknown>>(config: JwtAuthenticatorConfig<TClaims, TUserContext>): Authenticator<TUserContext>;
82
89
  //#endregion
83
90
  //#region src/server/util/tools.d.ts
84
91
  type ToolSet = Record<string, Tool>;
@@ -87,8 +94,81 @@ type Tool<Context extends Record<string, unknown> = Record<string, unknown>, INP
87
94
  };
88
95
  declare function tool<Context extends Record<string, unknown> = Record<string, unknown>, INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any>(tool: Tool<Context, INPUT, OUTPUT>): Tool$1<INPUT, OUTPUT>;
89
96
  //#endregion
90
- //#region src/server/agents/Agent.d.ts
91
- /** What the model would see on its next step — returned by {@link Agent.inspectTurn}. */
97
+ //#region src/server/features/analytics/types.d.ts
98
+ type AnalyticsAttribute = string | number | boolean;
99
+ type AnalyticsAttributes = Readonly<Record<string, AnalyticsAttribute>>;
100
+ interface AnalyticsUsage {
101
+ inputTokens: number;
102
+ outputTokens: number;
103
+ totalTokens: number;
104
+ cachedInputTokens?: number;
105
+ cacheWriteTokens?: number;
106
+ reasoningTokens?: number;
107
+ }
108
+ type AnalyticsEventPayload = {
109
+ type: "prompt.received";
110
+ /**
111
+ * The raw model messages received for the prompt. They may contain user
112
+ * or customer data and must be treated as sensitive by every handler.
113
+ * The built-in Analytics Engine handler records only their size.
114
+ */
115
+ messages: readonly ModelMessage[];
116
+ continuation: boolean;
117
+ } | {
118
+ type: "turn.completed";
119
+ requestId: string;
120
+ status: "completed" | "error" | "aborted";
121
+ continuation: boolean;
122
+ responseSize: number;
123
+ } | {
124
+ type: "llm.completed";
125
+ model: string;
126
+ provider: string;
127
+ finishReason: string;
128
+ usage: AnalyticsUsage;
129
+ durationMs: number;
130
+ inputSize: number;
131
+ responseSize: number;
132
+ stepNumber: number;
133
+ } | {
134
+ type: "tool.completed";
135
+ toolCallId: string;
136
+ toolName: string;
137
+ skillNames: readonly string[];
138
+ success: boolean;
139
+ durationMs: number;
140
+ inputSize: number;
141
+ outputSize: number;
142
+ stepNumber?: number;
143
+ } | {
144
+ type: "feedback.submitted";
145
+ messageId: string; /** `0` means the user cleared their existing feedback. */
146
+ rating: 1 | -1 | 0;
147
+ };
148
+ type AnalyticsEvent = AnalyticsEventPayload & {
149
+ schemaVersion: 1;
150
+ eventId: string;
151
+ timestamp: number;
152
+ agentName: string;
153
+ durableObjectName: string;
154
+ actorId: string;
155
+ attributes: AnalyticsAttributes;
156
+ };
157
+ /** Receives typed product-analytics events emitted by the SDK. */
158
+ interface AnalyticsHandler {
159
+ readonly name?: string;
160
+ handle(event: AnalyticsEvent): void | Promise<void>;
161
+ }
162
+ //#endregion
163
+ //#region src/server/features/analytics/analytics-engine.d.ts
164
+ /**
165
+ * Creates an explicit Cloudflare Analytics Engine destination for SDK events.
166
+ * Prompt content is deliberately never written; only its serialized size is.
167
+ */
168
+ declare function createAnalyticsEngineHandler(dataset: AnalyticsEngineDataset): AnalyticsHandler;
169
+ //#endregion
170
+ //#region src/server/agents/ChatAgent.d.ts
171
+ /** What the model would see on its next step — returned by {@link ChatAgent.inspectTurn}. */
92
172
  interface TurnSnapshot {
93
173
  system: string;
94
174
  tools: ToolSet;
@@ -97,15 +177,16 @@ interface TurnSnapshot {
97
177
  frameworkToolNames: string[];
98
178
  messages: ModelMessage[];
99
179
  }
100
- declare abstract class Agent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>, State = unknown> extends Think<Cloudflare.Env & AgentEnv, State> {
101
- protected agentType: AgentConnectionType;
102
- protected clientIp?: string;
103
- protected forwardedFor?: string;
180
+ declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>, State = unknown> extends Think<Cloudflare.Env & AgentEnv, State> {
181
+ private readonly inspectionContext;
182
+ /** Stable logical identity used in analytics, audit logs, and operational logs. */
183
+ abstract get agentName(): string;
184
+ observability: import("agents/observability").Observability;
104
185
  /**
105
186
  * Returns the user ID from the durable object name.
106
187
  */
107
188
  protected getActorIdFromDurableObjectName(): string;
108
- protected getParentAgent<T extends Agent$1>(): T | undefined;
189
+ protected getParentAgent<T extends Agent>(): T | undefined;
109
190
  abstract getModel(ctx?: ToolContext<RequestContext, UserContext>): LanguageModel;
110
191
  abstract getSystemPrompt(ctx?: ToolContext<RequestContext, UserContext>): string;
111
192
  onStart(): Promise<void>;
@@ -114,6 +195,8 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
114
195
  private _toolsForCurrentTurn;
115
196
  private _authorizedToolsForCurrentTurn;
116
197
  private _toolContextForCurrentTurn?;
198
+ private _analyticsHandlers?;
199
+ private getTurnConnectionState;
117
200
  private getToolContextForCurrentTurn;
118
201
  /**
119
202
  * Merges the client request `body` into `experimental_context` for tools
@@ -137,6 +220,9 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
137
220
  experimental_context: {};
138
221
  }>;
139
222
  beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void>;
223
+ onStepFinish(ctx: StepContext): void;
224
+ afterToolCall(ctx: ToolCallResultContext): void;
225
+ onChatResponse(result: ChatResponseResult): Promise<void>;
140
226
  getTools(): ToolSet;
141
227
  /**
142
228
  * Read-only: what the model would see on its next step for the given history
@@ -153,11 +239,6 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
153
239
  }): Promise<TurnSnapshot>;
154
240
  workspaceBash: boolean;
155
241
  getSkillScriptRunner(): skills.SkillScriptRunner | null;
156
- /**
157
- * Returns the remote skills to be loaded from SKILLS_BUCKET.
158
- * @returns The remote skills to be loaded from SKILLS_BUCKET.
159
- */
160
- protected getRemoteSkills(): string[];
161
242
  private _pruneTurnMessages;
162
243
  private _getAuthorizedTools;
163
244
  /**
@@ -185,60 +266,15 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
185
266
  * `async function*` `execute`'s streaming shape.
186
267
  */
187
268
  private _withTurnContextFallback;
188
- private _getLastActivatedSkillName;
189
269
  /**
190
- * Override to enable JWT authentication on WebSocket connections.
191
- * Return the auth config based on the incoming request, or undefined to skip auth.
192
- * Do not add side effects to this method - return a single JwtAuthConfig from it.
193
- *
194
- * @param env - The worker environment variables
195
- * @returns JWT auth config or undefined to skip authentication
270
+ * Generic authentication for this agent. If implemented, the authenticator
271
+ * runs once when a client connects. Omitting the method leaves the agent open.
196
272
  */
197
- static getJwtAuthConfig?(env: Cloudflare.Env): JwtAuthConfig<Record<string, unknown>> | undefined;
273
+ protected getAuthenticator?(env: Cloudflare.Env): Authenticator<UserContext>;
198
274
  /**
199
- * Override to exchange the verified connect token (RFC 8693) for a token
200
- * issued to this agent's own OAuth client. Requires {@link getJwtAuthConfig}.
201
- *
202
- * When configured, the exchanged token is passed to {@link getUserContext}
203
- * and injected into the tool context every turn under
204
- * `tokens[config.tokenHeader]` — client-sent request-body tokens for that
205
- * key are ignored. Renewal is connection-based: a client presenting a new
206
- * token reconnects, and the connect flow re-verifies and re-exchanges.
207
- *
208
- * Do not add side effects to this method - return a single config from it,
209
- * or undefined to disable the exchange.
210
- *
211
- * @param env - The worker environment variables
212
- * @returns Token exchange config or undefined to disable
213
- */
214
- static getTokenExchangeConfig?(env: Cloudflare.Env): TokenExchangeConfig | undefined;
215
- /**
216
- * The exchanged token for this agent, refreshed on every authenticated
217
- * connect. Kept in memory for the hot path and mirrored to DO storage so
218
- * turns that run after hibernation (or without a connection at all) still
219
- * have it. Short-lived by construction — at most the identity server's
220
- * token lifetime.
221
- */
222
- private _exchangedToken?;
223
- private _storeExchangedToken;
224
- private _getExchangedToken;
225
- /**
226
- * Swaps the client-sent token for the exchanged one in a copy of the turn
227
- * body. No-op when token exchange is not configured.
228
- */
229
- private _applyTokenExchange;
230
- /**
231
- * The user context for the session.
232
- * Define getUserContext to set a user context.
275
+ * User context returned by the configured authenticator for this connection.
233
276
  */
234
277
  protected userContext?: UserContext;
235
- /**
236
- * Returns the identity following verification of the JWT token - getJwtAuthConfig is required.
237
- * This method should not have side effects - return a single object from it.
238
- * @returns The user context from the request.
239
- * @param jwtToken - A valid JWT token following authentication.
240
- */
241
- protected getUserContext?(jwtToken: string): Promise<UserContext>;
242
278
  /**
243
279
  * Self-registers this DO in the global `agent_registry`. Only top-level DOs
244
280
  * are registered — facets are enumerable via their parent's own index, so
@@ -265,46 +301,19 @@ declare abstract class Agent<RequestContext extends Record<string, unknown> = Re
265
301
  */
266
302
  protected registerInstanceActivity(): Promise<void>;
267
303
  /**
268
- * Resolves the analytics/telemetry agent name to the entry-point agent: the
269
- * top-level DO registered in the `agent` catalog table.
270
- *
271
- * `parentPath` is root-first and empty for top-level DOs, so:
272
- * - chat agent running under an Assistant → the Assistant's class name
273
- * (e.g. `EvaAssistant`), since the Assistant is the catalog entry point;
274
- * - standalone chat agent → its own class name (e.g. `EvaAgent`).
275
- */
276
- protected getTelemetryAgentName(): string;
277
- protected getTelemetryActorId(): string;
278
- }
279
- //#endregion
280
- //#region src/server/features/messages.d.ts
281
- type MessageFeedback = {
282
- message_id: string;
283
- rating: number;
284
- comment?: string;
285
- created_at: number;
286
- updated_at: number;
287
- };
288
- //#endregion
289
- //#region src/server/agents/ChatAgent.d.ts
290
- declare abstract class ChatAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>, State = unknown> extends Agent<RequestContext, UserContext, State> {
291
- protected agentType: AgentConnectionType;
292
- onStart(): Promise<void>;
293
- configureSession(session: Session): Session;
294
- beforeTurn(ctx: TurnContext): Promise<void | TurnConfig>;
295
- onChatResponse(_result: ChatResponseResult): Promise<void>;
296
- /**
297
- * Submit feedback for a message by its id.
298
- * @param messageId - The id of the message to give feedback on.
299
- * @param rating - The rating to give the message. 1 = thumbs up, -1 = thumbs down.
300
- * @returns The message id and the rating.
301
- */
302
- submitMessageFeedback(messageId: string, rating: number, comment?: string): Promise<void>;
303
- /**
304
- * Returns all message feedback for the current chat.
305
- * @returns All message feedback for the current chat.
304
+ * Product-analytics destinations for this agent. Nothing is emitted unless
305
+ * a consumer explicitly returns one or more handlers here.
306
306
  */
307
+ protected getAnalyticsHandlers(): readonly AnalyticsHandler[];
308
+ /** Business dimensions added to every analytics event (for example tenant or user type). */
309
+ protected getAnalyticsAttributes(): AnalyticsAttributes;
310
+ /** Emits a typed SDK product event to configured handlers. */
311
+ protected emitAnalyticsEvent(payload: AnalyticsEventPayload | (() => AnalyticsEventPayload)): void;
312
+ /** Submit or replace feedback for a persisted assistant message. */
313
+ submitMessageFeedback(messageId: string, rating: MessageFeedbackRating, comment?: string): Promise<void>;
314
+ /** Returns all feedback stored for this chat, keyed by message id. */
307
315
  getMessageFeedback(): Promise<Record<string, MessageFeedback>>;
316
+ protected getTelemetryActorId(): string;
308
317
  }
309
318
  //#endregion
310
319
  //#region src/server/features/chats.d.ts
@@ -321,10 +330,14 @@ type Chat = {
321
330
  declare const DELETE_CHAT_CALLBACK: "deleteChatCallback";
322
331
  //#endregion
323
332
  //#region src/server/agents/Assistant.d.ts
324
- declare abstract class Assistant<State = unknown> extends Agent$1<Cloudflare.Env & AgentEnv, State> {
325
- private _fix;
333
+ declare abstract class Assistant<State = unknown> extends Agent<Cloudflare.Env & AgentEnv, State> {
334
+ /** Stable logical identity used in operational logs. */
335
+ abstract get agentName(): string;
336
+ observability: import("agents/observability").Observability;
326
337
  protected abstract fastModel: LanguageModel;
327
338
  protected abstract agent: SubAgentClass<ChatAgent>;
339
+ /** Generic authentication for the assistant connection itself. */
340
+ protected getAuthenticator?(env: Cloudflare.Env): Authenticator<Record<string, unknown>>;
328
341
  onStart(): void;
329
342
  onConnect(connection: Connection, ctx: ConnectionContext): Promise<void>;
330
343
  createChat(): Promise<string>;
@@ -334,7 +347,7 @@ declare abstract class Assistant<State = unknown> extends Agent$1<Cloudflare.Env
334
347
  getChatAgentClassName(): Promise<string>;
335
348
  registerChat(durableObjectName: string): Promise<void>;
336
349
  recordChatTurn(durableObjectName: string, messages: UIMessage[]): Promise<void>;
337
- recordChatFeedback(durableObjectName: string, messageId: string, rating: number): Promise<void>;
350
+ recordChatFeedback(durableObjectName: string, messageId: string, rating: MessageFeedbackRating): Promise<void>;
338
351
  private [DELETE_CHAT_CALLBACK];
339
352
  private scheduleChatForAutoDeletion;
340
353
  /**
@@ -349,7 +362,8 @@ declare abstract class Assistant<State = unknown> extends Agent$1<Cloudflare.Env
349
362
  /**
350
363
  * Records activity against this Assistant's registry row by advancing its
351
364
  * `updated_at`, so instances can be ordered by recency of activity. An
352
- * Assistant is a top-level DO, so its row is keyed by its own class + name.
365
+ * Assistant is a top-level DO, so its row is keyed by its logical agent name
366
+ * and Durable Object name.
353
367
  * Best-effort and non-blocking.
354
368
  */
355
369
  private touchInstance;
@@ -369,7 +383,111 @@ interface SkillSource<Context extends Record<string, unknown> = Record<string, u
369
383
  }
370
384
  declare function skill<Context extends Record<string, unknown> = Record<string, unknown>>(definition: Skill<Context>): SkillSource<Context>;
371
385
  //#endregion
372
- //#region src/server/index.d.ts
373
- declare function getCurrentToolContext(): any;
386
+ //#region src/server/agents/TaskAgent.d.ts
387
+ /** The run's input: plain text, or an assembled user message. */
388
+ type TaskRunInput = UIMessage[] | string;
389
+ type TaskRunResult = {
390
+ status: "completed";
391
+ output: string;
392
+ outputType: "text" | "json";
393
+ } | {
394
+ status: "error";
395
+ error: string;
396
+ } /** This instance (runId) already executed — the caller should not retry it. */ | {
397
+ status: "duplicate";
398
+ };
399
+ type TaskAuthentication<TUserContext extends Record<string, unknown> = Record<string, unknown>> = Authenticated<TUserContext>;
400
+ /** Persisted claim on the run id — the at-most-once guard across evictions. */
401
+ interface TaskAgentState {
402
+ claimed: boolean;
403
+ }
404
+ declare abstract class TaskAgent<RequestContext extends Record<string, unknown> = Record<string, unknown>, UserContext extends Record<string, unknown> = Record<string, unknown>> extends Agent<Cloudflare.Env & AgentEnv, TaskAgentState> {
405
+ /** Stable logical identity used in analytics, audit logs, and operational logs. */
406
+ abstract get agentName(): string;
407
+ observability: import("agents/observability").Observability;
408
+ initialState: TaskAgentState;
409
+ protected userContext?: UserContext;
410
+ /** Max tool-call rounds per run. Same name and default as Think's. */
411
+ maxSteps: number;
412
+ /**
413
+ * How long a finished run is retained — same days-based knob as chat's
414
+ * retention. For a task, retention IS the at-most-once window: it is how
415
+ * long the used run id is remembered. After it the instance destroys
416
+ * itself — the id's only afterlife is this guard.
417
+ */
418
+ retentionDays: number;
419
+ abstract getModel(ctx?: ToolContext<RequestContext, UserContext>): LanguageModel;
420
+ abstract getSystemPrompt(ctx?: ToolContext<RequestContext, UserContext>): string;
421
+ /** Generic request authentication. Absent means this task agent is open. */
422
+ protected getAuthenticator?(env: Cloudflare.Env): Authenticator<UserContext>;
423
+ getTools(): ToolSet;
424
+ getSkills(): SkillSource[] | Promise<SkillSource[]>;
425
+ getSkillScriptRunner(): import("agents/skills").SkillScriptRunner | null;
426
+ /** JSON Schema the run's output must conform to; undefined = plain text. */
427
+ protected getOutputSchema(): Record<string, unknown> | undefined;
428
+ /** Extra validation of a produced JSON output — return an error message to fail the run. */
429
+ protected validateOutput(_value: unknown): string | null;
430
+ protected getTelemetryActorId(): string;
431
+ /** Extra metadata stamped onto the run's telemetry (e.g. environment). */
432
+ protected getTelemetryMetadata(): Record<string, string>;
433
+ private _analyticsHandlers?;
434
+ /** Product-analytics destinations for this task agent. Disabled by default. */
435
+ protected getAnalyticsHandlers(): readonly AnalyticsHandler[];
436
+ /** Business dimensions added to every analytics event (for example tenant or user type). */
437
+ protected getAnalyticsAttributes(): AnalyticsAttributes;
438
+ /** Emits a typed product event to the configured handlers. */
439
+ protected emitAnalyticsEvent(payload: AnalyticsEventPayload | (() => AnalyticsEventPayload)): void;
440
+ onStart(): void;
441
+ /**
442
+ * Runs the configured authenticator for one task request. Custom transports
443
+ * call this before passing a successful result to {@link runTask}.
444
+ */
445
+ protected authenticateRequest(request: Request): Promise<Response | TaskAuthentication<UserContext> | undefined>;
446
+ /** Default transport: gate only. Override with your wire protocol. */
447
+ onRequest(request: Request): Promise<Response>;
448
+ /**
449
+ * Execute the run. Runs at most once per instance — the instance name is
450
+ * the run id, so a repeat POST of the same run id (in flight or finished)
451
+ * reports `duplicate` instead of re-executing (and re-billing) the run.
452
+ * The run executes as a durable fiber: ledgered in SQLite and holding a
453
+ * keepAlive so the instance is not idle-evicted mid-run.
454
+ *
455
+ * `requestContext` is the transport's contribution to the run's ToolContext
456
+ * (chat merges the client turn body the same way); the harness adds `_token`
457
+ * and `_userContext` from request-scoped authentication.
458
+ *
459
+ * This method trusts the supplied `authenticated` value. A transport exposed
460
+ * to untrusted callers must obtain it from {@link authenticateRequest}; callers
461
+ * must not be allowed to provide a fabricated authentication result over RPC.
462
+ */
463
+ runTask(input: TaskRunInput, requestContext?: RequestContext, authenticated?: TaskAuthentication<UserContext>): Promise<TaskRunResult>;
464
+ /** Scheduled callback — removes the run's state and evicts the instance. */
465
+ expireRun(): Promise<void>;
466
+ private scheduleSelfDestruction;
467
+ private executeRun;
468
+ /**
469
+ * Same authorization behaviour as the chat harness: unauthorized tools stay
470
+ * callable but their execution is replaced with an explanatory refusal, so
471
+ * the model reports the missing access instead of flailing into other tools.
472
+ */
473
+ private authorizedTools;
474
+ /**
475
+ * Refuses activation of an unauthorized skill — the same check the chat
476
+ * harness runs in beforeToolCall, applied to the registry's activate_skill
477
+ * tool (a task has no beforeToolCall interception point).
478
+ */
479
+ private guardSkillActivation;
480
+ }
481
+ //#endregion
482
+ //#region src/server/util/prompts.d.ts
483
+ /**
484
+ * Render a system-prompt block in the same layout the session memory renders
485
+ * its context blocks with (═-ruled header, UPPERCASE label, optional
486
+ * description, [readonly] tag). Returns an empty string for empty content.
487
+ */
488
+ declare function renderPromptBlock(label: string, content: string, description?: string): string;
489
+ //#endregion
490
+ //#region src/server/route-agent-request.d.ts
491
+ declare function routeAgentRequest<Env>(request: Request, env: Env, options?: AgentOptions<Env>): Promise<Response | null>;
374
492
  //#endregion
375
- export { Agent, type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, Assistant, ChatAgent, type ExchangedToken, type Skill, type SkillSource, type TokenExchangeConfig, type TokenExchangeResult, type Tool, type ToolContext, type ToolSet, type TurnSnapshot, exchangeToken, getCurrentToolContext, routeAgentRequest, skill, tool };
493
+ export { type AgentConnectionStatus, type AgentConnectionType, type AgentEnv, type AnalyticsAttribute, type AnalyticsAttributes, type AnalyticsEvent, type AnalyticsEventPayload, type AnalyticsHandler, type AnalyticsUsage, Assistant, type Authenticated, type AuthenticationDenied, type AuthenticationResult, type Authenticator, ChatAgent, type GetExchangedToken, type JwtAuthenticationContext, type JwtAuthenticatorConfig, type JwtVerificationConfig, type Skill, type SkillSource, TaskAgent, type TaskAuthentication, type TaskRunInput, type TaskRunResult, type Tool, type ToolContext, type ToolSet, type TurnSnapshot, createAnalyticsEngineHandler, createJwtAuthenticator, renderPromptBlock, routeAgentRequest, skill, tool };