runwork 0.36.0 → 0.38.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.
@@ -1,3 +1,3 @@
1
- export { INITIAL_AGENT_STATE, createAgentRegistry, getEntityToolDefs, getIntegrationToolDefs, getCustomToolDefs, getAgentToolDefs, toolDefToMeta, getAgentToolMeta, agentRoutes, entityListSchema, entityGetSchema, integrationApiSchema, } from './core-agent';
2
- export type { AgentState, AgentMessage, MemoryStrategy, AgentDefinition, AgentToolDefinition, AgentToolContext, AgentRegistry, RegisterAgentRequest, AgentToolMeta, AgentToolDef, AgentToolStatus, IntegrationStatus, AgentRuntimeStatus, } from './core-agent';
1
+ export { INITIAL_AGENT_STATE, createAgentRegistry, getEntityToolDefs, getIntegrationToolDefs, getCustomToolDefs, getAgentToolDefs, toolDefToMeta, getAgentToolMeta, agentRoutes, sendAgentMessage, entityListSchema, entityGetSchema, integrationApiSchema, } from './core-agent';
2
+ export type { AgentState, AgentMessage, MemoryStrategy, AgentDefinition, AgentToolDefinition, AgentToolContext, AgentRegistry, RegisterAgentRequest, AgentToolMeta, AgentToolDef, AgentToolStatus, IntegrationStatus, AgentRuntimeStatus, SendAgentMessageOptions, SendAgentMessageResult, } from './core-agent';
3
3
  export { BaseAgent } from './core-base-agent';
@@ -92,6 +92,24 @@ export interface AgentDefinition {
92
92
  * call what the app author listed, never an arbitrary endpoint.
93
93
  */
94
94
  appEndpoints?: string[];
95
+ /**
96
+ * OTHER apps in this workspace whose file storage the agent uses, by slug,
97
+ * e.g. `['labcrm']`. This app's own file storage is always within reach;
98
+ * the agent's file tools reach no other app's unless it is listed here.
99
+ */
100
+ fileStorages?: string[];
101
+ /**
102
+ * Whose authority a run of this agent borrows.
103
+ *
104
+ * - `'triggerer'` (default): the person who started the run. The agent can
105
+ * do only what that person could do themselves.
106
+ * - `'owner'`: the agent's owner, for an agent published as a service to
107
+ * people who do not hold that access themselves.
108
+ *
109
+ * Either way the agent reaches only what it declares in `integrations`,
110
+ * `entities`, `appEndpoints` and `fileStorages`.
111
+ */
112
+ runAs?: 'triggerer' | 'service';
95
113
  /** Memory strategy */
96
114
  memoryStrategy?: MemoryStrategy;
97
115
  /** Custom tools for this agent */
@@ -300,6 +318,48 @@ export interface AgentRuntimeStatus {
300
318
  checkedAt: number;
301
319
  }
302
320
  import type { Hono } from 'hono';
321
+ /**
322
+ * Options for {@link sendAgentMessage}.
323
+ */
324
+ export interface SendAgentMessageOptions {
325
+ /**
326
+ * Conversation to add the message to. Sending again with the same id
327
+ * continues that conversation, history included. Omitted, a new
328
+ * conversation is started.
329
+ */
330
+ sessionId?: string;
331
+ }
332
+ /**
333
+ * Result of {@link sendAgentMessage}.
334
+ */
335
+ export interface SendAgentMessageResult {
336
+ /** The conversation the message was added to; pass it back to continue it. */
337
+ sessionId: string;
338
+ }
339
+ /**
340
+ * Send a message to one of this app's agents from server code (a route, public
341
+ * endpoint, workflow step or scheduled job), as if a person had typed it in
342
+ * the agent's chat.
343
+ *
344
+ * The agent starts working on it before this returns and replies in the
345
+ * conversation; the reply is not returned here. The agent uses its tools as it
346
+ * would in a chat. Work it starts on behalf of a request stays within the run
347
+ * that asked for it.
348
+ *
349
+ * @param env - The environment bindings (needs the BaseAgent binding)
350
+ * @param agentName - The agent's name as defined in agents.ts
351
+ * @param message - The message text
352
+ * @param options - Optional conversation to continue
353
+ *
354
+ * @example
355
+ * ```ts
356
+ * import { sendAgentMessage } from '@runworkai/framework/agents';
357
+ *
358
+ * // In a scheduled job handler
359
+ * const { sessionId } = await sendAgentMessage(ctx.env, 'data-analyzer', "Summarize yesterday's orders.");
360
+ * ```
361
+ */
362
+ export declare function sendAgentMessage(env: Env, agentName: string, message: string, options?: SendAgentMessageOptions): Promise<SendAgentMessageResult>;
303
363
  /**
304
364
  * Mount agent routes on the Hono app
305
365
  * Provides REST API for AI agent interactions
@@ -18,7 +18,7 @@
18
18
  * the agent name stored in the DO's storage.
19
19
  */
20
20
  import { AIChatAgent } from 'agents/ai-chat-agent';
21
- import { type StreamTextOnFinishCallback, type ToolSet } from 'ai';
21
+ import { type StreamTextOnFinishCallback, type ToolSet, type UIMessage } from 'ai';
22
22
  import { type Env } from './core-utils';
23
23
  import { type AgentDefinition, type AgentRuntimeStatus } from './core-agent';
24
24
  /**
@@ -45,6 +45,16 @@ export declare class BaseAgent extends AIChatAgent<Env> {
45
45
  * Called when initializing a new agent instance
46
46
  */
47
47
  setAgentName(name: string): Promise<void>;
48
+ /**
49
+ * Start a turn from the server rather than from a chat connection.
50
+ *
51
+ * `runRef` is the run reference of the request that asked for this turn
52
+ * (`internal/run-ref.ts`). It is an explicit argument because the request's
53
+ * own store does not cross into this Durable Object. The turn, and every tool
54
+ * call it makes, holds it; the agent keeps nothing, so a later turn holds
55
+ * only what its own caller hands it, and a chat message holds none.
56
+ */
57
+ saveMessages(messages: UIMessage[], runRef?: string): Promise<void>;
48
58
  /**
49
59
  * Handle incoming chat messages using AI SDK
50
60
  * This is the main entry point called by AIChatAgent when a message arrives
@@ -26,6 +26,7 @@ interface ChannelEnv {
26
26
  APP_NAME?: string;
27
27
  DEPLOYMENT_MODE?: 'preview' | 'production';
28
28
  WorkspaceObject?: DurableObjectNamespace;
29
+ RUNWORK_PLATFORM?: Fetcher;
29
30
  }
30
31
  /**
31
32
  * Any context that supports waitUntil - compatible with both
@@ -183,11 +183,19 @@ export declare class EndpointRouter {
183
183
  export declare function mountEndpointAsHonoRoute(app: Hono<{
184
184
  Bindings: Env;
185
185
  }>, endpoint: EndpointDefinition): void;
186
+ export interface HandleEndpointRequestOptions {
187
+ /**
188
+ * Whether the platform-set principal headers (`X-Public-Endpoint-*`) may be believed. The core
189
+ * routes pass what the platform-call guard decided; false runs the request as an anonymous
190
+ * caller, so an `apiKey` endpoint refuses it and a `public` one still serves. Defaults to true.
191
+ */
192
+ trustPrincipalHeaders?: boolean;
193
+ }
186
194
  /**
187
195
  * Handle an incoming public endpoint request.
188
196
  * Called by the platform when routing requests to the app.
189
197
  */
190
- export declare function handleEndpointRequest<TQuery = unknown, TBody = unknown, TResponse = unknown>(request: Request, env: Env, endpoints: EndpointDefinition<TQuery, TBody, TResponse>[]): Promise<Response>;
198
+ export declare function handleEndpointRequest<TQuery = unknown, TBody = unknown, TResponse = unknown>(request: Request, env: Env, endpoints: EndpointDefinition<TQuery, TBody, TResponse>[], options?: HandleEndpointRequestOptions): Promise<Response>;
191
199
  /**
192
200
  * Custom error for endpoint handlers
193
201
  * Use this to return specific HTTP status codes
@@ -24,6 +24,7 @@ interface EventEnv {
24
24
  APP_NAME?: string;
25
25
  DEPLOYMENT_MODE?: 'preview' | 'production';
26
26
  WorkspaceObject?: DurableObjectNamespace;
27
+ RUNWORK_PLATFORM?: Fetcher;
27
28
  }
28
29
  /**
29
30
  * Any context that supports waitUntil - compatible with both
@@ -93,7 +93,7 @@ export declare class IntegrationClient {
93
93
  private getLegacyConnectionId;
94
94
  /**
95
95
  * Make a request to external API via platform proxy.
96
- * Uses platformFetch which routes through WorkspaceObject DO in production
96
+ * Uses platformFetch which routes through a platform binding in production
97
97
  * to avoid 522 timeouts from WfP workers.
98
98
  */
99
99
  private makeRequest;
@@ -170,8 +170,12 @@ export declare class SchedulerDO extends DurableObject<Env> {
170
170
  getJobHistory(jobName?: string, limit?: number): Promise<JobRunRecord[]>;
171
171
  /**
172
172
  * Manually trigger a job (for testing/debugging)
173
+ *
174
+ * `runRef` is the run reference of the request that asked for this run. It
175
+ * arrives as a plain string because AsyncLocalStorage does not cross into
176
+ * this Durable Object, and the handler runs holding it.
173
177
  */
174
- triggerJob(jobName: string): Promise<JobResult>;
178
+ triggerJob(jobName: string, runRef?: string): Promise<JobResult>;
175
179
  /**
176
180
  * Pause a scheduled job
177
181
  */
@@ -22,6 +22,12 @@ export interface Env {
22
22
  SchedulerDO: DurableObjectNamespace<SchedulerDO>;
23
23
  BaseAgent?: DurableObjectNamespace<BaseAgent>;
24
24
  WorkspaceObject?: DurableObjectNamespace;
25
+ /**
26
+ * Platform-managed service binding to the workspace, attached at deploy
27
+ * time. The framework's platform calls use it when present; app code does
28
+ * not call it directly.
29
+ */
30
+ RUNWORK_PLATFORM?: Fetcher;
25
31
  WorkflowInstance: DurableObjectNamespace;
26
32
  WorkflowCoordinator: DurableObjectNamespace;
27
33
  BUCKET?: R2Bucket;
@@ -43,6 +49,7 @@ export interface Env {
43
49
  RUNWORK_PROXY_TOKEN?: string;
44
50
  INTEGRATIONS_PROXY_URL?: string;
45
51
  ALLOWED_ORIGINS?: string;
52
+ RUNWORK_PLATFORM_CALLS?: string;
46
53
  }
47
54
  /**
48
55
  * Return a successful JSON response.
@@ -76,11 +83,12 @@ export declare const isStr: (s: unknown) => s is string;
76
83
  */
77
84
  export declare function safeClone<T>(value: T, fallback?: T): T;
78
85
  /**
79
- * Platform fetch - routes requests through WorkspaceObject DO for production workers.
86
+ * Platform fetch - routes requests through a platform binding for production workers.
80
87
  *
81
88
  * Workers for Platforms (WfP) workers cannot reliably make HTTP requests back to their
82
89
  * parent platform worker (they get 522 timeouts). This utility routes platform API calls
83
- * through the WorkspaceObject Durable Object binding, which works across worker boundaries.
90
+ * through the RUNWORK_PLATFORM service binding when the app has it, otherwise through the
91
+ * WorkspaceObject Durable Object binding; both work across worker boundaries.
84
92
  *
85
93
  * Supported paths:
86
94
  * - /api/proxy/integrations/* - Integration proxy (Nango)
@@ -178,16 +186,27 @@ export declare function getRunContext(): RunContext | undefined;
178
186
  */
179
187
  export declare function withRunContextHeader(init?: HeadersInit): HeadersInit | undefined;
180
188
  export declare function platformFetch(env: Env, url: string | URL, rawInit?: RequestInit): Promise<Response>;
189
+ export declare const WORKSPACE_KEY_HEADER = "x-workspace-key";
190
+ export declare const APP_ID_HEADER = "x-runwork-app-id";
191
+ export declare const APP_WORKSPACE_ID_HEADER = "x-runwork-app-workspace-id";
192
+ /**
193
+ * Headers for a request that presents the workspace key: the key plus the app
194
+ * and workspace it belongs to, so the platform can verify the key against the
195
+ * app the request names. Values come from env, and a header the caller already
196
+ * set is never overwritten. Absent env values add no header.
197
+ */
198
+ export declare function workspaceKeyHeaders(env: Pick<Env, 'WORKSPACE_API_KEY' | 'WORKSPACE_ID' | 'APP_ID'>, headers?: HeadersInit): Headers;
181
199
  /**
182
- * Workspace API fetch - routes workspace service requests through WorkspaceObject DO
200
+ * Workspace API fetch - routes workspace service requests through a platform binding
183
201
  * for production WfP workers, avoiding 522 recursive invocation errors.
184
202
  *
185
203
  * Workers for Platforms workers cannot HTTP-fetch back to their dispatcher domain.
186
- * This routes through the WorkspaceObject DO binding in production, and falls back
187
- * to standard HTTP with x-workspace-key auth header in preview/sandbox.
204
+ * This routes through the RUNWORK_PLATFORM service binding in production when the app
205
+ * has it, otherwise through the WorkspaceObject DO binding, and falls back to standard
206
+ * HTTP with x-workspace-key auth header in preview/sandbox.
188
207
  *
189
208
  * @param env - Environment with workspace bindings
190
209
  * @param path - Workspace API sub-path (e.g., '/ingest-event')
191
210
  * @param init - Standard fetch options
192
211
  */
193
- export declare function workspaceApiFetch(env: Pick<Env, 'WORKSPACE_API_URL' | 'WORKSPACE_API_KEY' | 'WORKSPACE_ID' | 'DEPLOYMENT_MODE' | 'WorkspaceObject'>, path: string, rawInit?: RequestInit): Promise<Response>;
212
+ export declare function workspaceApiFetch(env: Pick<Env, 'WORKSPACE_API_URL' | 'WORKSPACE_API_KEY' | 'WORKSPACE_ID' | 'APP_ID' | 'DEPLOYMENT_MODE' | 'WorkspaceObject' | 'RUNWORK_PLATFORM'>, path: string, rawInit?: RequestInit): Promise<Response>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Who opened this app.
3
+ *
4
+ * Who may open a deployed app is decided in Runwork, never in app code: by default only people
5
+ * in the workspace who may run the app; the owner can also make it public or hand out share
6
+ * links. The platform checks every visitor before the request reaches the app, removes the
7
+ * credential it checked, and tells the app who it let in through a signed header. `getVisitor`
8
+ * reads that header; nothing else on the request says who the visitor is.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { getVisitor } from '@runworkai/framework';
13
+ *
14
+ * app.get('/api/me', async (c) => {
15
+ * const visitor = await getVisitor(c.req.raw, c.env);
16
+ * if (visitor?.kind === 'user') return c.json({ signedInAs: visitor.name ?? visitor.userId });
17
+ * return c.json({ signedInAs: null });
18
+ * });
19
+ * ```
20
+ */
21
+ import type { Env } from './core-utils';
22
+ /**
23
+ * How the visitor got in.
24
+ * - `user`: a person in the workspace who may run the app, signed in to Runwork.
25
+ * - `link`: someone who followed a share link for this app; the app is not told who they are.
26
+ * - `anonymous`: a visitor of a public app who may not run it in the workspace; the app is not
27
+ * told who they are.
28
+ */
29
+ export type VisitorKind = 'user' | 'link' | 'anonymous';
30
+ /** The visitor the platform let in, as it signed it for this app. */
31
+ export type Visitor = {
32
+ kind: VisitorKind;
33
+ /** The person's Runwork user id; present when `kind` is `user`. */
34
+ userId?: string;
35
+ /** The person's display name, when the platform sends one; only for `user`. */
36
+ name?: string;
37
+ /** The share link the visitor followed; only for `link`. */
38
+ linkId?: string;
39
+ appId: string;
40
+ workspaceId: string;
41
+ };
42
+ /** The app identity `getVisitor` checks the header against. */
43
+ export type VisitorEnv = Pick<Env, 'WORKSPACE_API_KEY' | 'WORKSPACE_ID' | 'APP_ID'>;
44
+ /**
45
+ * The visitor of this request, or null when the platform did not sign one for this app: no
46
+ * header (local development, a preview, a public endpoint call, a scheduled run), a header that
47
+ * does not verify, or one older than five minutes. Never throws.
48
+ *
49
+ * Do not read identity from any other header, cookie or query parameter: only this one is
50
+ * signed by the platform for this app.
51
+ */
52
+ export declare function getVisitor(request: Request, env: VisitorEnv): Promise<Visitor | null>;
53
+ /** `getVisitor` for a Hono route handler: `await getVisitorFromContext(c)`. */
54
+ export declare function getVisitorFromContext(c: {
55
+ req: {
56
+ raw: Request;
57
+ };
58
+ env: VisitorEnv;
59
+ }): Promise<Visitor | null>;
@@ -6,7 +6,7 @@
6
6
  * Apps in the same workspace can query each other's entities and register
7
7
  * their capabilities (entities, components, endpoints, etc.).
8
8
  */
9
- import type { Env } from './core-utils';
9
+ import { type Env } from './core-utils';
10
10
  import type { ExecutionLimits } from './task-delegation/types';
11
11
  /**
12
12
  * WorkspaceUser - Represents a member of the workspace
@@ -16,7 +16,7 @@ export interface WorkspaceUser {
16
16
  id: string;
17
17
  email: string;
18
18
  name: string;
19
- role: 'owner' | 'admin' | 'editor' | 'viewer';
19
+ role: 'owner' | 'admin' | 'editor' | 'viewer' | 'guest';
20
20
  avatarUrl: string | null;
21
21
  joinedAt: number;
22
22
  }
@@ -162,6 +162,9 @@ export interface RegisterAgentRequest extends Record<string, unknown> {
162
162
  type: 'conversational' | 'task';
163
163
  integrations: string[];
164
164
  entities: string[];
165
+ appEndpoints?: string[];
166
+ fileStorages?: string[];
167
+ runAs?: 'triggerer' | 'service';
165
168
  deploymentMode?: 'preview' | 'production';
166
169
  systemPrompt?: string;
167
170
  prompt?: string;
@@ -207,8 +210,8 @@ export declare class WorkspaceContext {
207
210
  private deploymentMode;
208
211
  constructor(env: Env, workspaceId: string, appId: string, appName: string);
209
212
  private canUseHttpFallback;
210
- private getWorkspaceStub;
211
- private fetchViaDurableObject;
213
+ private getPlatformBinding;
214
+ private fetchViaBinding;
212
215
  private fetchViaHttp;
213
216
  private workspaceFetch;
214
217
  /**
@@ -240,15 +243,15 @@ export declare class WorkspaceContext {
240
243
  *
241
244
  * Deliberately NOT `workspaceFetch`, for two reasons:
242
245
  *
243
- * 1. `workspaceFetch` retries over HTTP whenever the Durable Object returns a
244
- * non-2xx. That is right for entity CRUD, where a non-2xx means the DO
245
- * itself failed. Here a non-2xx is the TARGET ENDPOINT'S OWN ANSWER, so
246
+ * 1. `workspaceFetch` retries over HTTP whenever the binding returns a
247
+ * non-2xx other than a refusal. That is right for entity CRUD, where a non-2xx means the
248
+ * workspace itself failed. Here a non-2xx is the TARGET ENDPOINT'S OWN ANSWER, so
246
249
  * retrying would re-send the request — duplicating POSTs — and in production
247
250
  * the retry goes to the platform's own domain, which a Workers for Platforms
248
251
  * worker cannot fetch: it hangs until timeout, the very failure this function
249
252
  * exists to avoid. A status is a result, never a transport error.
250
253
  *
251
- * 2. Production therefore uses the DO binding ONLY, mirroring `workspaceApiFetch`
254
+ * 2. Production therefore uses a platform binding ONLY, mirroring `workspaceApiFetch`
252
255
  * in core-utils.ts, which is the proven path for every other platform call
253
256
  * made from a deployed app. Preview and sandbox keep the HTTP path, where the
254
257
  * app is reached over a tunnel rather than the dispatch namespace.
@@ -346,8 +349,11 @@ export declare class WorkspaceContext {
346
349
  registerAgent(agentName: string, config: {
347
350
  description: string;
348
351
  type: 'conversational' | 'task';
349
- integrations: string[];
352
+ integrations?: string[];
350
353
  entities: string[];
354
+ appEndpoints?: string[];
355
+ fileStorages?: string[];
356
+ runAs?: 'triggerer' | 'service';
351
357
  systemPrompt?: string;
352
358
  prompt?: string;
353
359
  executionLimits?: ExecutionLimits;
@@ -405,6 +411,9 @@ export declare class WorkspaceContext {
405
411
  type: 'conversational' | 'task';
406
412
  integrations?: string[];
407
413
  entities?: string[];
414
+ appEndpoints?: string[];
415
+ fileStorages?: string[];
416
+ runAs?: 'triggerer' | 'service';
408
417
  systemPrompt?: string;
409
418
  prompt?: string;
410
419
  executionLimits?: ExecutionLimits;
@@ -1,2 +1,2 @@
1
1
  export { isEndpointDefinition, jsonResponse, errorResponse, zodToJsonSchema, EndpointRouter, mountEndpointAsHonoRoute, handleEndpointRequest, EndpointError, endpointToRegistration, } from './core-endpoints';
2
- export type { EndpointAuthType, EndpointMethod, EndpointSchema, EndpointContext, EndpointAuthInfo, EndpointLogger, EndpointMeta, EndpointDefinition, EndpointHandler, ParsedEndpointRequest, } from './core-endpoints';
2
+ export type { EndpointAuthType, EndpointMethod, EndpointSchema, EndpointContext, EndpointAuthInfo, EndpointLogger, EndpointMeta, EndpointDefinition, EndpointHandler, ParsedEndpointRequest, HandleEndpointRequestOptions, } from './core-endpoints';
@@ -3,6 +3,8 @@ export type { CreateAppOptions } from './create-app';
3
3
  export type { AppConfig } from './app-registry';
4
4
  export { ok, bad, notFound, isStr, safeClone, platformFetch, workspaceApiFetch } from './core-utils';
5
5
  export type { Env } from './core-utils';
6
+ export { getVisitor, getVisitorFromContext } from './core-visitor';
7
+ export type { Visitor, VisitorKind, VisitorEnv } from './core-visitor';
6
8
  export type { ApiResponse } from './shared/core-types';
7
9
  export * from './entities';
8
10
  export * from './routes';
@@ -5,7 +5,7 @@
5
5
  * getAgentTaskStatus() polls execution status via /agent-execution/:id.
6
6
  */
7
7
  import type { RunAgentTaskOptions, AgentTaskExecution } from './types';
8
- import type { Env } from '../core-utils';
8
+ import { type Env } from '../core-utils';
9
9
  export { agentTaskToolSchema, RESERVED_ENV_VARS } from './types';
10
10
  export type { AgentTaskResult, AgentTaskUsage, AgentTaskInputFile, AgentTaskOutputFile, ExecutionLimits, AgentTaskExecution, RunAgentTaskOptions, } from './types';
11
11
  /**
@@ -91,7 +91,8 @@ export interface AgentTaskResult {
91
91
  export interface AgentTaskExecution {
92
92
  executionId: string;
93
93
  sessionId?: string;
94
- status: 'running' | 'completed' | 'partial' | 'error' | 'timeout';
94
+ /** `cancelled`: ended early because the person who started it was paused, removed or suspended. */
95
+ status: 'running' | 'completed' | 'partial' | 'error' | 'timeout' | 'cancelled';
95
96
  result?: AgentTaskResult;
96
97
  }
97
98
  /**