Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(routines): require connected apps a routine lists (#8690)
Wolf Mermelstein79ca134ba505
diff --git a/apps/web/src/features/routines/components/routine-editor.tsx b/apps/web/src/features/routines/components/routine-editor.tsxindex f89907187b..8bea3aab40 100644--- a/apps/web/src/features/routines/components/routine-editor.tsx+++ b/apps/web/src/features/routines/components/routine-editor.tsx@@ -20,6 +20,7 @@ export function RoutineEditor(props: {runActions?: JSX.Element;instructions: JSX.Element;executionPicker: JSX.Element;+ apps?: JSX.Element;triggerContent?: JSX.Element;nextRun: string;history: JSX.Element;@@ -147,6 +148,7 @@ export function RoutineEditor(props: {props.onChange((draft) => ({ ...draft, runVisibility }))}/>+ {props.apps}</EntityComposer.Properties></fieldset><Layer depth={1}>diff --git a/apps/web/src/features/routines/context/routine-slots.ts b/apps/web/src/features/routines/context/routine-slots.tsindex 69289857aa..62bea31f82 100644--- a/apps/web/src/features/routines/context/routine-slots.ts+++ b/apps/web/src/features/routines/context/routine-slots.ts@@ -1,4 +1,5 @@import type { Accessor, Component } from 'solid-js';+import type { RoutineApp } from '../core/draft';import type { RoutineTarget } from '../core/routine-target';import type { RoutineTriggerDraft } from '../core/routine-triggers';import type { HistoryMetadata } from './history';@@ -17,6 +18,12 @@ export type RoutineEditorSlots = {triggers: RoutineTriggerDraft[];onChange(triggers: RoutineTriggerDraft[]): void;}>;+ Apps: Component<{+ apps: RoutineApp[];+ onChange(apps: RoutineApp[]): void;+ }>;+ /** The viewer's connected app slugs; undefined until they load. */+ createConnectedApps(): Accessor<ReadonlySet<string> | undefined>;};export type RoutineDetailSlots = RoutineEditorSlots & {createChatMetadata(id: string): Accessor<HistoryMetadata>;diff --git a/apps/web/src/features/routines/core/draft.ts b/apps/web/src/features/routines/core/draft.tsindex ebd664ac37..9df3c847c3 100644--- a/apps/web/src/features/routines/core/draft.ts+++ b/apps/web/src/features/routines/core/draft.ts@@ -1,6 +1,9 @@import type { RoutineTarget } from './routine-target';import type { RoutineTriggerDraft } from './routine-triggers';+/** A Pipedream app, as stored on the routine's task. */+export type RoutineApp = { app_slug: string; server_name: string };+export type ScheduleFrequency = 'week' | 'month' | 'once';/**@@ -27,6 +30,8 @@ export type ScheduleDraft = {/** 1-31 day-of-month when frequency === "month". */dayOfMonth: string;target: RoutineTarget;+ /** Apps every run requires, added to the target's own. Each must be connected. */+ apps: RoutineApp[];onceAt?: string;timezone?: string;};diff --git a/apps/web/src/features/routines/core/routine-draft.ts b/apps/web/src/features/routines/core/routine-draft.tsindex 37a94f6df5..d90163557e 100644--- a/apps/web/src/features/routines/core/routine-draft.ts+++ b/apps/web/src/features/routines/core/routine-draft.ts@@ -75,6 +75,7 @@ export function createEmptyDraft(model: string): ScheduleDraft {dayOfMonth: '1',target: { kind: 'model', model },runVisibility: DEFAULT_RUN_VISIBILITY,+ apps: [],};}@@ -124,6 +125,17 @@ export function validateRoutineDraft(return null;}+/** Null until the owner's connections load; the server checks again on save. */+export function validateRoutineApps(+ apps: readonly { app_slug: string }[],+ connectedSlugs: ReadonlySet<string> | undefined+): string | null {+ if (!connectedSlugs) return null;+ return apps.every((app) => connectedSlugs.has(app.app_slug))+ ? null+ : 'Connect every app this routine requires.';+}+export function getErrorMessage(error: unknown): string {if (error instanceof Error && error.message) return error.message;return 'Please try again.';diff --git a/apps/web/src/features/routines/draft-storage.test.ts b/apps/web/src/features/routines/draft-storage.test.tsindex a8d8b9781b..e589975481 100644--- a/apps/web/src/features/routines/draft-storage.test.ts+++ b/apps/web/src/features/routines/draft-storage.test.ts@@ -17,6 +17,7 @@ const draft: ScheduleDraft = {daysOfWeek: [],dayOfMonth: '',target: { kind: 'model', model: 'retired-model' },+ apps: [],};function store(value: unknown): void {diff --git a/apps/web/src/features/routines/draft-storage.ts b/apps/web/src/features/routines/draft-storage.tsindex fb4dafb4d9..e773c6c353 100644--- a/apps/web/src/features/routines/draft-storage.ts+++ b/apps/web/src/features/routines/draft-storage.ts@@ -21,6 +21,11 @@ const draftFields = {// Older clients saved routine activation with the draft.enabled: z.boolean().optional(),runVisibility: z.enum(['listed', 'unlisted']).optional(),+ // Drafts saved before routines took apps have none.+ apps: z+ .array(z.strictObject({ app_slug: z.string(), server_name: z.string() }))+ .max(64)+ .default([]),};const draftSchema = zdiff --git a/apps/web/src/features/routines/primitives/routine-composer.test.ts b/apps/web/src/features/routines/primitives/routine-composer.test.tsindex 65ed5cca51..ba5acd46a7 100644--- a/apps/web/src/features/routines/primitives/routine-composer.test.ts+++ b/apps/web/src/features/routines/primitives/routine-composer.test.ts@@ -16,7 +16,10 @@ const draft = {let dispose = () => {};afterEach(() => dispose());-function setup(create: () => Promise<string>) {+function setup(+ create: () => Promise<string>,+ connected: () => ReadonlySet<string> | undefined = () => new Set()+) {const storage: RoutineDraftStorage = {load: () => draft,save: vi.fn(),@@ -37,7 +40,13 @@ function setup(create: () => Promise<string>) {};const composer = createRoot((cleanup) => {dispose = cleanup;- return createRoutineComposer(source, storage, 'default-model', onCreated);+ return createRoutineComposer(+ source,+ storage,+ 'default-model',+ onCreated,+ connected+ );});return { composer, storage, onCreated, source };}@@ -91,4 +100,25 @@ describe('routine creation state without app providers', () => {expect.objectContaining({ triggers: [] }));});++ it('creates a routine only once every app it requires is connected', async () => {+ const [connected, setConnected] = createSignal<ReadonlySet<string>>(+ new Set()+ );+ const { composer, source } = setup(async () => 'created', connected);+ composer.change((current) => ({+ ...current,+ apps: [{ app_slug: 'linear', server_name: 'Linear' }],+ }));+ await composer.create();+ expect(composer.formError()).toBe(+ 'Connect every app this routine requires.'+ );+ expect(source.create).not.toHaveBeenCalled();++ setConnected(new Set(['linear']));+ expect(composer.formError()).toBeNull();+ await composer.create();+ expect(source.create).toHaveBeenCalledOnce();+ });});diff --git a/apps/web/src/features/routines/primitives/routine-composer.ts b/apps/web/src/features/routines/primitives/routine-composer.tsindex f8c0a9c169..dfc0a3b78a 100644--- a/apps/web/src/features/routines/primitives/routine-composer.ts+++ b/apps/web/src/features/routines/primitives/routine-composer.ts@@ -1,5 +1,5 @@import { debounce } from '@solid-primitives/scheduled';-import { createSignal, onCleanup } from 'solid-js';+import { type Accessor, createSignal, onCleanup } from 'solid-js';import type {RoutineCreatorSource,RoutineDraftStorage,@@ -8,6 +8,7 @@ import type { ScheduleDraft } from '../core/draft';import {createEmptyDraft,getErrorMessage,+ validateRoutineApps,validateRoutineDraft,} from '../core/routine-draft';@@ -15,7 +16,8 @@ export function createRoutineComposer(source: RoutineCreatorSource,storage: RoutineDraftStorage,defaultModel: string,- onCreated: (id: string) => void+ onCreated: (id: string) => void,+ connectedApps: Accessor<ReadonlySet<string> | undefined>) {const restored = storage.load();const [draft, setDraft] = createSignal<ScheduleDraft>(@@ -29,6 +31,9 @@ export function createRoutineComposer();const [attempted, setAttempted] = createSignal(false);const [submitError, setSubmitError] = createSignal<string>();+ const formError = () =>+ validateRoutineDraft(draft(), true) ??+ validateRoutineApps(draft().apps, connectedApps());const save = debounce((value: ScheduleDraft) => storage.save(value), 300);let dirty = false;function change(update: (draft: ScheduleDraft) => ScheduleDraft) {@@ -47,7 +52,7 @@ export function createRoutineComposer(async function create() {if (source.pending()) return;setAttempted(true);- if (validateRoutineDraft(draft(), true)) return;+ if (formError()) return;let id: string;try {id = await source.create(draft());@@ -60,5 +65,5 @@ export function createRoutineComposer(storage.clear();onCreated(id);}- return { draft, change, attempted, submitError, create };+ return { draft, change, attempted, formError, submitError, create };}diff --git a/apps/web/src/features/routines/primitives/routine-detail.ts b/apps/web/src/features/routines/primitives/routine-detail.tsindex 9c09c545d2..fdf5c9b183 100644--- a/apps/web/src/features/routines/primitives/routine-detail.ts+++ b/apps/web/src/features/routines/primitives/routine-detail.ts@@ -2,7 +2,11 @@ import { type Accessor, createEffect, createSignal, on } from 'solid-js';import type { RoutineDetailSource } from '../context/routine-sources';import { isClaimActive } from '../core/claim';import type { ScheduleDraft } from '../core/draft';-import { formatDateTime, validateRoutineDraft } from '../core/routine-draft';+import {+ formatDateTime,+ validateRoutineApps,+ validateRoutineDraft,+} from '../core/routine-draft';import { hasOnlyScheduledTriggers } from '../core/routine-triggers';import { createRoutineAutosave } from './routine-autosave';@@ -17,6 +21,7 @@ export function createRoutineDetail(source: RoutineDetailSource,options: {userId: Accessor<string | undefined>;+ connectedApps: Accessor<ReadonlySet<string> | undefined>;onRename(name: string): void;}) {@@ -37,7 +42,11 @@ export function createRoutineDetail(const formError = () => {const draft = state();- return draft ? validateRoutineDraft(draft) : null;+ if (!draft) return null;+ return (+ validateRoutineDraft(draft) ??+ validateRoutineApps(draft.apps, options.connectedApps())+ );};const autosave = createRoutineAutosave<ScheduleDraft>(async (draft) => {@@ -67,6 +76,19 @@ export function createRoutineDetail(autosave.queue(formError() ? undefined : next);}+ // An edit held back only by an unconnected app saves once it is connected.+ createEffect(+ on(+ formError,+ (error, previous) => {+ const draft = state();+ if (!error && previous && draft && autosave.dirty())+ autosave.queue(draft);+ },+ { defer: true }+ )+ );+function runNow(): void {if (!isOwned() ||diff --git a/apps/web/src/features/routines/queries/routine-draft.test.ts b/apps/web/src/features/routines/queries/routine-draft.test.tsindex 18dbc64b29..c130aa36f2 100644--- a/apps/web/src/features/routines/queries/routine-draft.test.ts+++ b/apps/web/src/features/routines/queries/routine-draft.test.ts@@ -452,3 +452,53 @@ describe('run visibility', () => {});});});++describe('routine required apps', () => {+ it('reads, creates, and updates the apps a routine requires', () => {+ const withApps: ScheduledAction = {+ ...cron,+ task: {+ model: 'claude-sonnet-4-6',+ user_prompt: 'Summarize updates',+ prompt: '',+ mcp_servers: [{ app_slug: 'linear', server_name: 'Linear' }],+ },+ };+ const restored = loadedDraft(withApps);+ expect(restored.apps).toEqual([+ { app_slug: 'linear', server_name: 'Linear' },+ ]);+ expect(draftToCreateBody(restored).task.mcp_servers).toEqual([+ { app_slug: 'linear', server_name: 'Linear' },+ ]);+ expect(draftToCreateBody(loadedDraft(cron)).task.mcp_servers).toEqual([]);++ // Untouched apps keep the stored task as it was.+ expect(draftToUpdateBody(restored, withApps)?.task).toBe(withApps.task);++ // Removing every app sends an explicit empty list.+ expect(+ draftToUpdateBody({ ...restored, apps: [] }, withApps)?.task+ ).toEqual({+ model: 'claude-sonnet-4-6',+ user_prompt: 'Summarize updates',+ prompt: '',+ mcp_servers: [],+ });++ expect(+ draftToUpdateBody(+ {+ ...loadedDraft(cron),+ apps: [{ app_slug: 'slack', server_name: 'Slack' }],+ },+ cron+ )?.task+ ).toEqual({+ model: 'claude-sonnet-4-6',+ user_prompt: 'Summarize updates',+ prompt: '',+ mcp_servers: [{ app_slug: 'slack', server_name: 'Slack' }],+ });+ });+});diff --git a/apps/web/src/features/routines/queries/routine-draft.ts b/apps/web/src/features/routines/queries/routine-draft.tsindex 644646062f..6f367cd817 100644--- a/apps/web/src/features/routines/queries/routine-draft.ts+++ b/apps/web/src/features/routines/queries/routine-draft.ts@@ -32,6 +32,9 @@ const agentTaskSchema = z.looseObject({agent: z.looseObject({ bot_id: routineAgentIdSchema }).nullish(),model: routineModelSchema.nullish(),+ mcp_servers: z+ .array(z.object({ app_slug: z.string(), server_name: z.string() }))+ .optional(),prompt: z.string(),user_prompt: z.string(),})@@ -94,6 +97,7 @@ export function draftFromSchedule(dayOfMonth: parsed.dayOfMonth,target: targetFromTask(task),runVisibility: schedule.run_visibility,+ apps: task.mcp_servers ?? [],timezone: trigger?.timezone,triggers,...(trigger ? onceFromCron(trigger.schedule, trigger.timezone) : {}),@@ -118,7 +122,11 @@ function applyTarget(task: RoutineTask, target: RoutineTarget): void {function buildAgentTask(draft: ScheduleDraft): RoutineTask {const target = routineTargetSchema.parse(draft.target);- const task: RoutineTask = { prompt: '', user_prompt: draft.prompt.trim() };+ const task: RoutineTask = {+ prompt: '',+ user_prompt: draft.prompt.trim(),+ mcp_servers: draft.apps,+ };applyTarget(task, target);return task;}@@ -149,11 +157,15 @@ export function draftToUpdateBody(targetFromTask(previousTask));const promptChanged = draft.prompt !== previousTask.user_prompt;+ const appsChanged =+ draft.apps.map((app) => app.app_slug).join(',') !==+ (previousTask.mcp_servers ?? []).map((app) => app.app_slug).join(',');let task = previous.task;- if (targetChanged || promptChanged) {+ if (targetChanged || promptChanged || appsChanged) {const editedTask = { ...previousTask };if (targetChanged) applyTarget(editedTask, target.data);if (promptChanged) editedTask.user_prompt = draft.prompt.trim();+ if (appsChanged) editedTask.mcp_servers = draft.apps;task = editedTask;}const runVisibility = draft.runVisibility ?? previous.run_visibility;diff --git a/apps/web/src/features/routines/routine-apps.tsx b/apps/web/src/features/routines/routine-apps.tsxnew file mode 100644index 0000000000..ce9bbf2089--- /dev/null+++ b/apps/web/src/features/routines/routine-apps.tsx@@ -0,0 +1,92 @@+import { Popover } from '@kobalte/core/popover';+import PlugsIcon from '@phosphor/plugs.svg';+import { usePipedreamConnectedSlugs } from '@queries/pipedream-connectors';+import { badgeTriggerClasses } from '@ui';+import { type Accessor, Show } from 'solid-js';+import { PipedreamAppPicker } from '../settings/PipedreamAppPicker';+import type { RoutineApp } from './core/draft';++/** The viewer's connected app slugs, undefined until they load. */+export function createRoutineConnectedApps(): Accessor<+ ReadonlySet<string> | undefined+> {+ const connections = usePipedreamConnectedSlugs();+ return () => (connections.ready() ? connections.slugs() : undefined);+}++/** Apps a routine requires, picked from the Pipedream catalog. */+export function RoutineApps(props: {+ apps: RoutineApp[];+ onChange: (apps: RoutineApp[]) => void;+}) {+ const connections = usePipedreamConnectedSlugs();+ let triggerRef: HTMLButtonElement | undefined;+ // Mount Connect inside the enclosing dialog so its focus trap allows it.+ const dialog = () =>+ triggerRef?.closest<HTMLElement>('[role="dialog"]') ?? undefined;+ const missing = () =>+ connections.ready() &&+ props.apps.some((app) => !connections.slugs().has(app.app_slug));+ const label = () =>+ props.apps.length === 0+ ? 'Add apps'+ : props.apps.map((app) => app.server_name).join(', ');++ return (+ <Popover+ placement="bottom-start"+ gutter={6}+ boundary={() => document.documentElement}+ >+ <Popover.Trigger+ ref={triggerRef}+ aria-label={+ props.apps.length === 0 ? 'Add required apps' : 'Required apps'+ }+ title={missing() ? 'Connect every app this routine requires' : label()}+ class={badgeTriggerClasses({+ variant: 'outline',+ size: 'sm',+ class: 'min-w-0 max-w-full text-left text-ink-muted',+ })}+ >+ <PlugsIcon class="size-3 shrink-0" />+ <span class="min-w-0 truncate">{label()}</span>+ <Show when={missing()}>+ <span+ aria-hidden="true"+ class="size-1.5 shrink-0 rounded-full bg-failure"+ />+ </Show>+ </Popover.Trigger>+ <Popover.Portal+ mount={dialog()}+ ref={(element) => {+ element.style.display = 'contents';+ }}+ >+ <Popover.Content+ class="menu-surface z-modal flex max-h-[min(32rem,var(--kb-popper-content-available-height))] w-96 max-w-[calc(100vw-1rem)] flex-col overflow-y-auto overscroll-contain p-3"+ onKeyDown={(e) => e.stopPropagation()}+ // A pick removes the tapped result, so focus falls out of the popover.+ onFocusOutside={(event) => event.preventDefault()}+ >+ <Popover.Title class="text-sm font-medium">+ Required apps+ </Popover.Title>+ <Popover.Description class="mb-3 mt-1 text-xs text-ink-muted">+ Every run gets these apps on top of the agent's own. Connect each+ one before the routine can be saved or run.+ </Popover.Description>+ <PipedreamAppPicker+ selected={props.apps}+ onChange={props.onChange}+ connectedSlugs={connections.slugs}+ connectionsReady={connections.ready}+ connectContainer={dialog}+ />+ </Popover.Content>+ </Popover.Portal>+ </Popover>+ );+}diff --git a/apps/web/src/features/routines/routine-creator.test.tsx b/apps/web/src/features/routines/routine-creator.test.tsxindex 2e3b901055..8e98d01767 100644--- a/apps/web/src/features/routines/routine-creator.test.tsx+++ b/apps/web/src/features/routines/routine-creator.test.tsx@@ -273,6 +273,7 @@ describe('routine composer execution selection', () => {const expectedTask: Record<string, unknown> = {prompt: '',user_prompt: 'Summarize updates',+ mcp_servers: [],};if (target === 'model') expectedTask.model = 'vendor/custom-model';else expectedTask.agent = { bot_id: agentId };diff --git a/apps/web/src/features/routines/routine-creator.tsx b/apps/web/src/features/routines/routine-creator.tsxindex 1a8d8012dd..76a43ed046 100644--- a/apps/web/src/features/routines/routine-creator.tsx+++ b/apps/web/src/features/routines/routine-creator.tsx@@ -9,6 +9,7 @@ import {saveRoutineComposerDraft,} from './draft-storage';import { createRoutineCreatorSource } from './queries/routine-sources';+import { createRoutineConnectedApps, RoutineApps } from './routine-apps';import { RoutineExecutionPicker } from './routine-execution-picker';import { RoutinePromptEditor } from './routine-prompt-editor';import { RoutineTriggers } from './routine-triggers';@@ -35,6 +36,8 @@ export function RoutineCreator(PromptEditor: RoutinePromptEditor,ExecutionPicker: RoutineExecutionPicker,Triggers: RoutineTriggers,+ Apps: RoutineApps,+ createConnectedApps: createRoutineConnectedApps,}}onClose={() => panel.handle.close()}onCreated={(id) => {diff --git a/apps/web/src/features/routines/routine-detail.test.tsx b/apps/web/src/features/routines/routine-detail.test.tsxindex 2af24f8d1c..5b1e4b51ec 100644--- a/apps/web/src/features/routines/routine-detail.test.tsx+++ b/apps/web/src/features/routines/routine-detail.test.tsx@@ -157,6 +157,10 @@ vi.mock('./routine-prompt-editor', () => ({);},}));+vi.mock('./routine-apps', () => ({+ RoutineApps: () => null,+ createRoutineConnectedApps: () => () => new Set(),+}));vi.mock('./routine-execution-picker', () => ({RoutineExecutionPicker: (props: {target: RoutineTarget;diff --git a/apps/web/src/features/routines/routine-detail.tsx b/apps/web/src/features/routines/routine-detail.tsxindex 26206c2a11..faf2e9ed15 100644--- a/apps/web/src/features/routines/routine-detail.tsx+++ b/apps/web/src/features/routines/routine-detail.tsx@@ -15,6 +15,7 @@ import {createChatHistoryMetadata,} from './queries/history-metadata';import { createRoutineDetailSource } from './queries/routine-sources';+import { createRoutineConnectedApps, RoutineApps } from './routine-apps';import { RoutineExecutionPicker } from './routine-execution-picker';import { RoutinePromptEditor } from './routine-prompt-editor';import { RoutineTriggers } from './routine-triggers';@@ -99,6 +100,8 @@ export function RoutineDetail(props: {PromptEditor: RoutinePromptEditor,ExecutionPicker: RoutineExecutionPicker,Triggers: RoutineTriggers,+ Apps: RoutineApps,+ createConnectedApps: createRoutineConnectedApps,createChatMetadata: createChatHistoryMetadata,createAgentMetadata: createAgentHistoryMetadata,}}diff --git a/apps/web/src/features/routines/views/routine-creator.tsx b/apps/web/src/features/routines/views/routine-creator.tsxindex 73a6e87e2a..669e4a88f9 100644--- a/apps/web/src/features/routines/views/routine-creator.tsx+++ b/apps/web/src/features/routines/views/routine-creator.tsx@@ -10,7 +10,6 @@ import type {RoutineDraftStorage,} from '../context/routine-sources';import { DEFAULT_RUN_VISIBILITY } from '../core/draft';-import { validateRoutineDraft } from '../core/routine-draft';import { createRoutineComposer } from '../primitives/routine-composer';export function RoutineCreatorView(props: {@@ -21,12 +20,13 @@ export function RoutineCreatorView(props: {onCreated(id: string): void;onClose(): void;}) {- const { draft, change, attempted, submitError, create } =+ const { draft, change, attempted, formError, submitError, create } =createRoutineComposer(props.source,props.storage,props.defaultModel,- props.onCreated+ props.onCreated,+ props.slots.createConnectedApps());return (<EntityComposer.Root@@ -93,9 +93,13 @@ export function RoutineCreatorView(props: {change((draft) => ({ ...draft, runVisibility }))}/>+ <props.slots.Apps+ apps={draft().apps}+ onChange={(apps) => change((draft) => ({ ...draft, apps }))}+ /></EntityComposer.Properties></fieldset>- <Show when={attempted() && validateRoutineDraft(draft(), true)}>+ <Show when={attempted() && formError()}>{(message) => (<p role="alert" class="mt-3 text-xs text-failure">{message()}diff --git a/apps/web/src/features/routines/views/routine-detail.tsx b/apps/web/src/features/routines/views/routine-detail.tsxindex 6319d6a989..f46faa4f51 100644--- a/apps/web/src/features/routines/views/routine-detail.tsx+++ b/apps/web/src/features/routines/views/routine-detail.tsx@@ -43,7 +43,11 @@ export function RoutineDetailView(props: {runDisabled,activationDisabled,runNow,- } = createRoutineDetail(props.source, props);+ } = createRoutineDetail(props.source, {+ userId: props.userId,+ connectedApps: props.slots.createConnectedApps(),+ onRename: (name) => props.onRename(name),+ });const [tab, setTab] = createSignal(props.initialTab ?? 'settings');const back = () => props.onBack();const copyPrompt = async () => {@@ -148,6 +152,18 @@ export function RoutineDetailView(props: {)}</Show>}+ apps={+ <Show when={state()}>+ {(draft) => (+ <props.slots.Apps+ apps={draft().apps}+ onChange={(apps) =>+ setState((current) => ({ ...current, apps }))+ }+ />+ )}+ </Show>+ }triggerContent={<Showwhen={state()}diff --git a/apps/web/src/features/settings/PipedreamAppPicker.tsx b/apps/web/src/features/settings/PipedreamAppPicker.tsxindex 13216c96a2..1b4c98dcf4 100644--- a/apps/web/src/features/settings/PipedreamAppPicker.tsx+++ b/apps/web/src/features/settings/PipedreamAppPicker.tsx@@ -20,14 +20,14 @@ import { ConnectAction, StatusDot } from './integration-ui';import { IntegrationRow } from './primitives';/**- * Picks Pipedream apps for an agent from the whole catalog, connected or- * not, and shows for each picked app whether the *viewer* has connected it.+ * Picks Pipedream apps from the whole catalog, connected or not, and shows+ * for each picked app whether the *viewer* has connected it.*- * Selection is the agent's; connection is personal. A teammate opening the- * same agent sees their own dots, because a session spends the connections- * of whoever runs it. So an unconnected pick is never an error here - it is- * the agent's author saying "this agent uses Linear", and each person- * connects Linear on their own, from this row or from Settings → Integrations.+ * For an agent, selection is the agent's and connection is personal: a+ * teammate opening the same agent sees their own dots, because a session+ * spends the connections of whoever runs it, so an unconnected pick is not+ * an error. A routine runs as its owner and requires its apps, so the+ * routine editor refuses to save until each one is connected.*/export function PipedreamAppPicker(props: {selected: readonly AgentMcpServer[];diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex 7135c10adc..1130058491 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -4317,6 +4317,9 @@ export const CreateRoutine = z.object({});}}),+ requiredApps: z+ .array(z.object({ appSlug: z.string(), name: z.string() }))+ .optional(),}),});@@ -16826,6 +16829,9 @@ export const UpdateRoutine = z.object({});}}),+ requiredApps: z+ .array(z.object({ appSlug: z.string(), name: z.string() }))+ .optional(),}),type: z.literal('configuration'),}),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex e148fb8228..02c60a6659 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -8186,6 +8186,25 @@ export interface RoutineConfiguration {instructions: string;target: RoutineTarget;schedule: RoutineSchedule;+ /**+ * Apps every run needs, on top of the target's own. The user must already+ * have each one connected (offer a connect link via DiscoverConnectors if+ * not). Updates replace the list: restate it to keep the apps.+ */+ requiredApps?: RoutineApp[];+}+/**+ * A Pipedream app a routine requires.+ */+export interface RoutineApp {+ /**+ * Pipedream app slug, e.g. `linear`.+ */+ appSlug: string;+ /**+ * Display name, e.g. `Linear`.+ */+ name: string;}/*** Compact routine details returned to the caller.diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentMcpServer.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentMcpServer.tsnew file mode 100644index 0000000000..52e07cbc1c--- /dev/null+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentMcpServer.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * scheduled_action+ * API for managing scheduled actions+ * OpenAPI spec version: 0.1.0+ */++/**+ * One Pipedream app an agent lists under [`AgentMcpServers::Selected`].++Only the catalog identity is stored. Whether a given person has connected+the app is theirs, resolved at call time by the egress proxy, never here.+ */+export interface AgentMcpServer {+ /** Pipedream app slug, e.g. `linear`. */+ app_slug: string;+ /** Display name, e.g. `Linear`. */+ server_name: string;+}diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentTask.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentTask.tsindex 5598fb5fe8..a482fca268 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentTask.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/agentTask.ts@@ -5,11 +5,16 @@* API for managing scheduled actions* OpenAPI spec version: 0.1.0*/++import type { AgentMcpServer } from './agentMcpServer';import type { AgentTaskAgentProperty } from './agentTaskAgentProperty';import type { AgentTaskModel } from './agentTaskModel';export interface AgentTask {agent?: AgentTaskAgentProperty;+ /** Apps the routine requires on top of the agent's own. The owner must+have each one connected to save the routine and for it to run. */+ mcp_servers?: AgentMcpServer[];model?: AgentTaskModel;prompt: string;user_prompt: string;diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.tsindex ac3af75a92..e74f34f303 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/index.ts@@ -24,6 +24,7 @@ export * from './actionTriggerOneOfFiveType';export * from './actionTriggerOneOfThree';export * from './actionTriggerOneOfThreeType';export * from './actionTriggerOneOfType';+export * from './agentMcpServer';export * from './agentTask';export * from './agentTaskAgent';export * from './agentTaskAgentProperty';diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.jsonindex 32e719b553..a1e1bd64f2 100644--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json@@ -762,6 +762,21 @@],"description": "A routine may run on one trigger or any of several schedules and Macro events."},+ "AgentMcpServer": {+ "type": "object",+ "description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",+ "required": ["app_slug", "server_name"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Pipedream app slug, e.g. `linear`."+ },+ "server_name": {+ "type": "string",+ "description": "Display name, e.g. `Linear`."+ }+ }+ },"AgentTask": {"type": "object","required": ["prompt", "user_prompt"],@@ -777,6 +792,13 @@}]},+ "mcp_servers": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AgentMcpServer"+ },+ "description": "Apps the routine requires on top of the agent's own. The owner must\nhave each one connected to save the routine and for it to run."+ },"model": {"oneOf": [{diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.jsonindex 28b64141aa..97fa4da0af 100644--- a/crates/agent_code_mode/src/domain/documentation.json+++ b/crates/agent_code_mode/src/domain/documentation.json@@ -45,7 +45,7 @@"name": "routines","description": "Create scheduled and event-triggered agent routines and inspect executions.","overview": "<!-- src/entities/routines/namespace/classes/RoutineNamespace.md -->\n# Class: RoutineNamespace\n\nScheduled and event-triggered routines.\n\n## Constructors\n\n### Constructor\n\n> **new RoutineNamespace**(`client`): `RoutineNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`RoutineNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Routine`](../../routine/classes/Routine.md)\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Routine`](../../routine/classes/Routine.md)\n\n***\n\n### create()\n\n> **create**(`options`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\nCreate an agent routine.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../../routine/interfaces/RoutineOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\n***\n\n### list()\n\n> **list**(`options?`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\nList routines, optionally including event triggers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `includeEvents?`: `boolean`; \\} |\n| `options.includeEvents?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\n\n<!-- src/entities/routines/routine/interfaces/RoutineOptions.md -->\n# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | [`Agent`](../../../agents/agent/classes/Agent.md) | Agent to run the task. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model override. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | [`RoutineTriggerOptions`](../type-aliases/RoutineTriggerOptions.md) | Schedules or Macro events that start the routine. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineEventFilter.md -->\n# Type Alias: RoutineEventFilter\n\n> **RoutineEventFilter** = `Omit`\\<[`EventFilter`](../../../../../generated/scheduled-action/types.gen/type-aliases/EventFilter.md), `\"ids\"` \\| `\"condition\"`\\> & \\{ `condition?`: `string`; `entities?`: [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[]; \\}\n\nAn event selector references resources by typed handles.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `condition?` | `string` | Optional yes/no condition on the triggering content. |\n| `entities?` | [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[] | Resource selectors for these events. Omit to match all resources. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineTriggerOptions.md -->\n# Type Alias: RoutineTriggerOptions\n\n> **RoutineTriggerOptions** = [`SingleRoutineTrigger`](SingleRoutineTrigger.md) \\| \\{ `triggers`: [`SingleRoutineTrigger`](SingleRoutineTrigger.md)[]; `type`: `\"multiple\"`; \\}\n\nOne or multiple routine triggers.\n\n\n<!-- src/entities/routines/routine/type-aliases/SingleRoutineTrigger.md -->\n# Type Alias: SingleRoutineTrigger\n\n> **SingleRoutineTrigger** = `Extract`\\<[`RoutineTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTrigger.md), \\{ `type`: `\"cron\"`; \\}\\> \\| \\{ `filters`: [`RoutineEventFilter`](RoutineEventFilter.md)[]; `type`: `\"events\"`; \\}\n\nOne schedule or set of event selectors.\n",- "documentation": "# Macro SDK: routines\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md -->\n# Type Alias: ActionExecutionRecord\n\n> **ActionExecutionRecord** = \\{ `action_id`: `string`; `created_at`: `string`; `end_time`: `string`; `id?`: `string` \\| `null`; `is_success`: `boolean`; `resource_id?`: `string` \\| `null`; `result`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `start_time`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action_id\"></a> `action_id` | `string` | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-end_time\"></a> `end_time` | `string` | - |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-is_success\"></a> `is_success` | `boolean` | - |\n| <a id=\"property-resource_id\"></a> `resource_id?` | `string` \\| `null` | ID of the primary resource produced by this run. Its type is recorded in `result`, independently of the routine's current configuration. |\n| <a id=\"property-result\"></a> `result` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-start_time\"></a> `start_time` | `string` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionKind.md -->\n# Type Alias: ActionKind\n\n> **ActionKind** = `\"Agent\"`\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md -->\n# Type Alias: ActionTrigger\n\n> **ActionTrigger** = \\{ `schedule`: [`Schedule`](Schedule.md); `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: [`EventFilters`](EventFilters.md); `type`: `\"events\"`; \\} \\| \\{ `triggers`: [`RoutineTriggers`](RoutineTriggers.md); `type`: `\"multiple\"`; \\}\n\nA routine may run on one trigger or any of several schedules and Macro events.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md -->\n# Type Alias: AgentTaskAgent\n\n> **AgentTaskAgent** = \\{ `bot_id`: `string`; \\}\n\nA persona selection, independent of its runtime and current default model.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-bot_id\"></a> `bot_id` | `string` |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventFilter.md -->\n# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: [`EventName`](EventName.md)[]; `ids?`: `string`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | [`EventName`](EventName.md)[] | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventFilters.md -->\n# Type Alias: EventFilters\n\n> **EventFilters** = [`EventFilter`](EventFilter.md)[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventName.md -->\n# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RoutineTrigger.md -->\n# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: [`Schedule`](Schedule.md); `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: [`EventFilters`](EventFilters.md); `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RoutineTriggers.md -->\n# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = [`RoutineTrigger`](RoutineTrigger.md)[]\n\nBounded schedules and one combined set of event filters.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RunVisibility.md -->\n# Type Alias: RunVisibility\n\n> **RunVisibility** = `\"listed\"` \\| `\"unlisted\"`\n\nWhether a routine's runs are listed in Home and the Agents list. Routines\nthat run often would bury the owner's own work, so runs start unlisted;\neither way they stay in the routine's history. The string form is the\n`scheduled_action.run_visibility` column's.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/Schedule.md -->\n# Type Alias: Schedule\n\n> **Schedule** = `string`\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md -->\n# Type Alias: ScheduledAction\n\n> **ScheduledAction** = \\{ `claimed?`: `string` \\| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \\| `null`; `id?`: `string` \\| `null`; `kind`: [`ActionKind`](ActionKind.md); `name`: `string`; `next_run_at?`: `string` \\| `null`; `owner`: `string`; `run_visibility`: [`RunVisibility`](RunVisibility.md); `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-claimed\"></a> `claimed?` | `string` \\| `null` | - |\n| <a id=\"property-configuration_revision\"></a> `configuration_revision` | `number` | Independent of execution bookkeeping in `updated_at`. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-enabled\"></a> `enabled` | `boolean` | When false, automatic dispatch skips this action. `run_now` remains available regardless. |\n| <a id=\"property-event_activated_at\"></a> `event_activated_at?` | `string` \\| `null` | Event publication boundary; absent for cron actions. |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-kind\"></a> `kind` | [`ActionKind`](ActionKind.md) | - |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-next_run_at\"></a> `next_run_at?` | `string` \\| `null` | Next cron firing, absent for event-triggered actions. |\n| <a id=\"property-owner\"></a> `owner` | `string` | Who the action belongs to. Every action is user-owned today, but the type no longer says so: the principal string on the wire and in the `owner` column is the same, and a bot- or team-owned row decodes rather than failing to parse. |\n| <a id=\"property-run_visibility\"></a> `run_visibility` | [`RunVisibility`](RunVisibility.md) | Whether the action's runs are listed in Home and the Agents list. |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | [`ActionTrigger`](ActionTrigger.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md -->\n# Type Alias: ScheduledActionResponse\n\n> **ScheduledActionResponse** = [`ScheduledAction`](ScheduledAction.md) & \\{ `schedule?`: `string` \\| `null`; `timezone?`: `string` \\| `null`; \\}\n\nCanonical trigger plus deprecated cron fields for existing clients. Event\nresponses omit legacy fields rather than inventing a schedule or timezone.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `schedule?` | `string` \\| `null` | Deprecated: use `trigger.schedule`. Present only for cron actions. **Deprecated** |\n| `timezone?` | `string` \\| `null` | Deprecated: use `trigger.timezone`. Present only for cron actions. **Deprecated** |\n\n\n<!-- src/entities/routines/namespace/classes/RoutineNamespace.md -->\n# Class: RoutineNamespace\n\nScheduled and event-triggered routines.\n\n## Constructors\n\n### Constructor\n\n> **new RoutineNamespace**(`client`): `RoutineNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`RoutineNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Routine`](../../routine/classes/Routine.md)\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Routine`](../../routine/classes/Routine.md)\n\n***\n\n### create()\n\n> **create**(`options`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\nCreate an agent routine.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../../routine/interfaces/RoutineOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\n***\n\n### list()\n\n> **list**(`options?`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\nList routines, optionally including event triggers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `includeEvents?`: `boolean`; \\} |\n| `options.includeEvents?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\n\n<!-- src/entities/routines/routine/classes/Routine.md -->\n# Class: Routine\n\nA scheduled or event-triggered agent task.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-enabled\"></a> `enabled` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the routine is enabled. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Routine name. | - |\n| <a id=\"property-nextrunat\"></a> `nextRunAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Next scheduled execution. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Routine owner. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Configuration revision. | - |\n| <a id=\"property-runvisibility\"></a> `runVisibility` | `readonly` | () => `Promise`\\<[`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md)\\> | Whether the routine's runs appear in Home and the Agents list. | - |\n| <a id=\"property-trigger\"></a> `trigger` | `readonly` | () => `Promise`\\<[`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md)\\> | Configured triggers. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the routine.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### execute()\n\n> **execute**(): `Promise`\\<[`AgentSession`](../../../agent-sessions/agent-session/classes/AgentSession.md) \\| [`Chat`](../../../chats/chat/classes/Chat.md) \\| `undefined`\\>\n\nStart an execution immediately and return its transcript handle if available.\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../../agent-sessions/agent-session/classes/AgentSession.md) \\| [`Chat`](../../../chats/chat/classes/Chat.md) \\| `undefined`\\>\n\n***\n\n### history()\n\n> **history**(): `Promise`\\<[`RoutineExecution`](RoutineExecution.md)[]\\>\n\nCompleted executions, with their routine scoped identity.\n\n#### Returns\n\n`Promise`\\<[`RoutineExecution`](RoutineExecution.md)[]\\>\n\n***\n\n### setEnabled()\n\n> **setEnabled**(`enabled`): `Promise`\\<`void`\\>\n\nEnable or disable triggering.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `enabled` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nReplace the routine's task and trigger configuration.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Routine`\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Routine`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `Routine`\n\nSeed a handle from a server record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md) |\n\n#### Returns\n\n`Routine`\n\n\n<!-- src/entities/routines/routine/classes/RoutineExecution.md -->\n# Class: RoutineExecution\n\nA completed routine execution, as recorded by the service.\n\n## Constructors\n\n### Constructor\n\n> **new RoutineExecution**(`routine`, `record`): `RoutineExecution`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `routine` | [`Routine`](Routine.md) | Parent routine. |\n| `record` | [`ActionExecutionRecord`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md) | Execution snapshot. |\n\n#### Returns\n\n`RoutineExecution`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-record\"></a> `record` | `readonly` | [`ActionExecutionRecord`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md) | Execution snapshot. |\n| <a id=\"property-routine\"></a> `routine` | `readonly` | [`Routine`](Routine.md) | Parent routine. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string` \\| `undefined`\n\nExecution identity, when assigned.\n\n##### Returns\n\n`string` \\| `undefined`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `action_id`: `string`; `created_at`: `string`; `end_time`: `string`; `id?`: `string` \\| `null`; `is_success`: `boolean`; `resource_id?`: `string` \\| `null`; `result`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `routine`: `string`; `start_time`: `string`; \\}\n\nSerialize without the authenticated client.\n\n#### Returns\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action_id` | `string` | - |\n| `created_at` | `string` | - |\n| `end_time` | `string` | - |\n| `id?` | `string` \\| `null` | - |\n| `is_success` | `boolean` | - |\n| `resource_id?` | `string` \\| `null` | ID of the primary resource produced by this run. Its type is recorded in `result`, independently of the routine's current configuration. |\n| `result` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| `routine` | `string` | - |\n| `start_time` | `string` | - |\n\n\n<!-- src/entities/routines/routine/functions/routineBody.md -->\n# Function: routineBody()\n\n> **routineBody**(`options`): \\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined`; `task`: \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \\}\n\nTranslate typed routine options into the generated wire contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |\n\n## Returns\n\n\\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined`; `task`: \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \\}\n\n| Name | Type | Default value |\n| ------ | ------ | ------ |\n| `enabled` | `boolean` \\| `undefined` | `options.enabled` |\n| `kind` | `\"Agent\"` | - |\n| `name` | `string` | `options.name` |\n| `run_visibility` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined` | `options.runVisibility` |\n| `task` | \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\} | - |\n| `task.agent?` | [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null` | - |\n| `task.model?` | `string` \\| `null` | - |\n| `task.prompt` | `string` | - |\n| `task.user_prompt` | `string` | - |\n| `trigger` | [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md) | - |\n\n\n<!-- src/entities/routines/routine/interfaces/RoutineOptions.md -->\n# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | [`Agent`](../../../agents/agent/classes/Agent.md) | Agent to run the task. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model override. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | [`RoutineTriggerOptions`](../type-aliases/RoutineTriggerOptions.md) | Schedules or Macro events that start the routine. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineEventFilter.md -->\n# Type Alias: RoutineEventFilter\n\n> **RoutineEventFilter** = `Omit`\\<[`EventFilter`](../../../../../generated/scheduled-action/types.gen/type-aliases/EventFilter.md), `\"ids\"` \\| `\"condition\"`\\> & \\{ `condition?`: `string`; `entities?`: [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[]; \\}\n\nAn event selector references resources by typed handles.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `condition?` | `string` | Optional yes/no condition on the triggering content. |\n| `entities?` | [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[] | Resource selectors for these events. Omit to match all resources. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineTriggerOptions.md -->\n# Type Alias: RoutineTriggerOptions\n\n> **RoutineTriggerOptions** = [`SingleRoutineTrigger`](SingleRoutineTrigger.md) \\| \\{ `triggers`: [`SingleRoutineTrigger`](SingleRoutineTrigger.md)[]; `type`: `\"multiple\"`; \\}\n\nOne or multiple routine triggers.\n\n\n<!-- src/entities/routines/routine/type-aliases/SingleRoutineTrigger.md -->\n# Type Alias: SingleRoutineTrigger\n\n> **SingleRoutineTrigger** = `Extract`\\<[`RoutineTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTrigger.md), \\{ `type`: `\"cron\"`; \\}\\> \\| \\{ `filters`: [`RoutineEventFilter`](RoutineEventFilter.md)[]; `type`: `\"events\"`; \\}\n\nOne schedule or set of event selectors.\n"+ "documentation": "# Macro SDK: routines\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md -->\n# Type Alias: ActionExecutionRecord\n\n> **ActionExecutionRecord** = \\{ `action_id`: `string`; `created_at`: `string`; `end_time`: `string`; `id?`: `string` \\| `null`; `is_success`: `boolean`; `resource_id?`: `string` \\| `null`; `result`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `start_time`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-action_id\"></a> `action_id` | `string` | - |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-end_time\"></a> `end_time` | `string` | - |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-is_success\"></a> `is_success` | `boolean` | - |\n| <a id=\"property-resource_id\"></a> `resource_id?` | `string` \\| `null` | ID of the primary resource produced by this run. Its type is recorded in `result`, independently of the routine's current configuration. |\n| <a id=\"property-result\"></a> `result` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-start_time\"></a> `start_time` | `string` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionKind.md -->\n# Type Alias: ActionKind\n\n> **ActionKind** = `\"Agent\"`\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md -->\n# Type Alias: ActionTrigger\n\n> **ActionTrigger** = \\{ `schedule`: [`Schedule`](Schedule.md); `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: [`EventFilters`](EventFilters.md); `type`: `\"events\"`; \\} \\| \\{ `triggers`: [`RoutineTriggers`](RoutineTriggers.md); `type`: `\"multiple\"`; \\}\n\nA routine may run on one trigger or any of several schedules and Macro events.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md -->\n# Type Alias: AgentMcpServer\n\n> **AgentMcpServer** = \\{ `app_slug`: `string`; `server_name`: `string`; \\}\n\nOne Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-app_slug\"></a> `app_slug` | `string` | Pipedream app slug, e.g. `linear`. |\n| <a id=\"property-server_name\"></a> `server_name` | `string` | Display name, e.g. `Linear`. |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md -->\n# Type Alias: AgentTaskAgent\n\n> **AgentTaskAgent** = \\{ `bot_id`: `string`; \\}\n\nA persona selection, independent of its runtime and current default model.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-bot_id\"></a> `bot_id` | `string` |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventFilter.md -->\n# Type Alias: EventFilter\n\n> **EventFilter** = \\{ `condition?`: `string` \\| `null`; `events`: [`EventName`](EventName.md)[]; `ids?`: `string`[] \\| `null`; \\}\n\nAn event name AND an entity ID must match within the same filter. A\ncondition further requires the event's content to answer it with yes.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-condition\"></a> `condition?` | `string` \\| `null` | Yes/no question about the triggering content, e.g. \"Is this email an invoice?\". The routine runs only when the answer is yes. |\n| <a id=\"property-events\"></a> `events` | [`EventName`](EventName.md)[] | - |\n| <a id=\"property-ids\"></a> `ids?` | `string`[] \\| `null` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventFilters.md -->\n# Type Alias: EventFilters\n\n> **EventFilters** = [`EventFilter`](EventFilter.md)[]\n\nBounded nonempty OR of filters, canonicalized to remove duplicates.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/EventName.md -->\n# Type Alias: EventName\n\n> **EventName** = `\"document.created\"` \\| `\"document.updated\"` \\| `\"document.deleted\"` \\| `\"task.created\"` \\| `\"task.status_changed\"` \\| `\"task.priority_changed\"` \\| `\"task.property_changed\"` \\| `\"email.message_received\"` \\| `\"channel.created\"` \\| `\"channel.message_posted\"` \\| `\"channel.mentioned\"` \\| `\"channel.message_patched\"` \\| `\"channel.message_attachment_created\"` \\| `\"call.started\"` \\| `\"call.ended\"`\n\nClosed allowlist: unknown names, deletions and ambiguous attribution are not\nselectors. Adding a broker variant does not automatically enable routines.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RoutineTrigger.md -->\n# Type Alias: RoutineTrigger\n\n> **RoutineTrigger** = \\{ `schedule`: [`Schedule`](Schedule.md); `timezone`: `string`; `type`: `\"cron\"`; \\} \\| \\{ `filters`: [`EventFilters`](EventFilters.md); `type`: `\"events\"`; \\}\n\nAn individual trigger in a routine's trigger list.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RoutineTriggers.md -->\n# Type Alias: RoutineTriggers\n\n> **RoutineTriggers** = [`RoutineTrigger`](RoutineTrigger.md)[]\n\nBounded schedules and one combined set of event filters.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/RunVisibility.md -->\n# Type Alias: RunVisibility\n\n> **RunVisibility** = `\"listed\"` \\| `\"unlisted\"`\n\nWhether a routine's runs are listed in Home and the Agents list. Routines\nthat run often would bury the owner's own work, so runs start unlisted;\neither way they stay in the routine's history. The string form is the\n`scheduled_action.run_visibility` column's.\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/Schedule.md -->\n# Type Alias: Schedule\n\n> **Schedule** = `string`\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ScheduledAction.md -->\n# Type Alias: ScheduledAction\n\n> **ScheduledAction** = \\{ `claimed?`: `string` \\| `null`; `configuration_revision`: `number`; `created_at`: `string`; `enabled`: `boolean`; `event_activated_at?`: `string` \\| `null`; `id?`: `string` \\| `null`; `kind`: [`ActionKind`](ActionKind.md); `name`: `string`; `next_run_at?`: `string` \\| `null`; `owner`: `string`; `run_visibility`: [`RunVisibility`](RunVisibility.md); `task`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `trigger`: [`ActionTrigger`](ActionTrigger.md); `updated_at`: `string`; \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-claimed\"></a> `claimed?` | `string` \\| `null` | - |\n| <a id=\"property-configuration_revision\"></a> `configuration_revision` | `number` | Independent of execution bookkeeping in `updated_at`. |\n| <a id=\"property-created_at\"></a> `created_at` | `string` | - |\n| <a id=\"property-enabled\"></a> `enabled` | `boolean` | When false, automatic dispatch skips this action. `run_now` remains available regardless. |\n| <a id=\"property-event_activated_at\"></a> `event_activated_at?` | `string` \\| `null` | Event publication boundary; absent for cron actions. |\n| <a id=\"property-id\"></a> `id?` | `string` \\| `null` | - |\n| <a id=\"property-kind\"></a> `kind` | [`ActionKind`](ActionKind.md) | - |\n| <a id=\"property-name\"></a> `name` | `string` | - |\n| <a id=\"property-next_run_at\"></a> `next_run_at?` | `string` \\| `null` | Next cron firing, absent for event-triggered actions. |\n| <a id=\"property-owner\"></a> `owner` | `string` | Who the action belongs to. Every action is user-owned today, but the type no longer says so: the principal string on the wire and in the `owner` column is the same, and a bot- or team-owned row decodes rather than failing to parse. |\n| <a id=\"property-run_visibility\"></a> `run_visibility` | [`RunVisibility`](RunVisibility.md) | Whether the action's runs are listed in Home and the Agents list. |\n| <a id=\"property-task\"></a> `task` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| <a id=\"property-trigger\"></a> `trigger` | [`ActionTrigger`](ActionTrigger.md) | - |\n| <a id=\"property-updated_at\"></a> `updated_at` | `string` | - |\n\n\n<!-- generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md -->\n# Type Alias: ScheduledActionResponse\n\n> **ScheduledActionResponse** = [`ScheduledAction`](ScheduledAction.md) & \\{ `schedule?`: `string` \\| `null`; `timezone?`: `string` \\| `null`; \\}\n\nCanonical trigger plus deprecated cron fields for existing clients. Event\nresponses omit legacy fields rather than inventing a schedule or timezone.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `schedule?` | `string` \\| `null` | Deprecated: use `trigger.schedule`. Present only for cron actions. **Deprecated** |\n| `timezone?` | `string` \\| `null` | Deprecated: use `trigger.timezone`. Present only for cron actions. **Deprecated** |\n\n\n<!-- src/entities/routines/namespace/classes/RoutineNamespace.md -->\n# Class: RoutineNamespace\n\nScheduled and event-triggered routines.\n\n## Constructors\n\n### Constructor\n\n> **new RoutineNamespace**(`client`): `RoutineNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`RoutineNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`Routine`](../../routine/classes/Routine.md)\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`Routine`](../../routine/classes/Routine.md)\n\n***\n\n### create()\n\n> **create**(`options`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\nCreate an agent routine.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../../routine/interfaces/RoutineOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)\\>\n\n***\n\n### list()\n\n> **list**(`options?`): `Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\nList routines, optionally including event triggers.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options?` | \\{ `includeEvents?`: `boolean`; \\} |\n| `options.includeEvents?` | `boolean` |\n\n#### Returns\n\n`Promise`\\<[`Routine`](../../routine/classes/Routine.md)[]\\>\n\n\n<!-- src/entities/routines/routine/classes/Routine.md -->\n# Class: Routine\n\nA scheduled or event-triggered agent task.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-enabled\"></a> `enabled` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the routine is enabled. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | Routine name. | - |\n| <a id=\"property-nextrunat\"></a> `nextRunAt` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Next scheduled execution. | - |\n| <a id=\"property-owner\"></a> `owner` | `readonly` | () => `Promise`\\<[`User`](../../../users/user/classes/User.md)\\> | Routine owner. | - |\n| <a id=\"property-revision\"></a> `revision` | `readonly` | () => `Promise`\\<`number`\\> | Configuration revision. | - |\n| <a id=\"property-runvisibility\"></a> `runVisibility` | `readonly` | () => `Promise`\\<[`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md)\\> | Whether the routine's runs appear in Home and the Agents list. | - |\n| <a id=\"property-trigger\"></a> `trigger` | `readonly` | () => `Promise`\\<[`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md)\\> | Configured triggers. | - |\n\n## Methods\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete the routine.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### execute()\n\n> **execute**(): `Promise`\\<[`AgentSession`](../../../agent-sessions/agent-session/classes/AgentSession.md) \\| [`Chat`](../../../chats/chat/classes/Chat.md) \\| `undefined`\\>\n\nStart an execution immediately and return its transcript handle if available.\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../../agent-sessions/agent-session/classes/AgentSession.md) \\| [`Chat`](../../../chats/chat/classes/Chat.md) \\| `undefined`\\>\n\n***\n\n### history()\n\n> **history**(): `Promise`\\<[`RoutineExecution`](RoutineExecution.md)[]\\>\n\nCompleted executions, with their routine scoped identity.\n\n#### Returns\n\n`Promise`\\<[`RoutineExecution`](RoutineExecution.md)[]\\>\n\n***\n\n### setEnabled()\n\n> **setEnabled**(`enabled`): `Promise`\\<`void`\\>\n\nEnable or disable triggering.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `enabled` | `boolean` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### update()\n\n> **update**(`options`): `Promise`\\<`void`\\>\n\nReplace the routine's task and trigger configuration.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `Routine`\n\nConstruct a lazy routine handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`Routine`\n\n***\n\n### from()\n\n> `static` **from**(`client`, `record`): `Routine`\n\nSeed a handle from a server record.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `record` | [`ScheduledActionResponse`](../../../../../generated/scheduled-action/types.gen/type-aliases/ScheduledActionResponse.md) |\n\n#### Returns\n\n`Routine`\n\n\n<!-- src/entities/routines/routine/classes/RoutineExecution.md -->\n# Class: RoutineExecution\n\nA completed routine execution, as recorded by the service.\n\n## Constructors\n\n### Constructor\n\n> **new RoutineExecution**(`routine`, `record`): `RoutineExecution`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `routine` | [`Routine`](Routine.md) | Parent routine. |\n| `record` | [`ActionExecutionRecord`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md) | Execution snapshot. |\n\n#### Returns\n\n`RoutineExecution`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-record\"></a> `record` | `readonly` | [`ActionExecutionRecord`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionExecutionRecord.md) | Execution snapshot. |\n| <a id=\"property-routine\"></a> `routine` | `readonly` | [`Routine`](Routine.md) | Parent routine. |\n\n## Accessors\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string` \\| `undefined`\n\nExecution identity, when assigned.\n\n##### Returns\n\n`string` \\| `undefined`\n\n## Methods\n\n### toJSON()\n\n> **toJSON**(): \\{ `action_id`: `string`; `created_at`: `string`; `end_time`: `string`; `id?`: `string` \\| `null`; `is_success`: `boolean`; `resource_id?`: `string` \\| `null`; `result`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `routine`: `string`; `start_time`: `string`; \\}\n\nSerialize without the authenticated client.\n\n#### Returns\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action_id` | `string` | - |\n| `created_at` | `string` | - |\n| `end_time` | `string` | - |\n| `id?` | `string` \\| `null` | - |\n| `is_success` | `boolean` | - |\n| `resource_id?` | `string` \\| `null` | ID of the primary resource produced by this run. Its type is recorded in `result`, independently of the routine's current configuration. |\n| `result` | \\{\\[`key`: `string`\\]: `unknown`; \\} | - |\n| `routine` | `string` | - |\n| `start_time` | `string` | - |\n\n\n<!-- src/entities/routines/routine/functions/routineBody.md -->\n# Function: routineBody()\n\n> **routineBody**(`options`): \\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined`; `task`: \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \\}\n\nTranslate typed routine options into the generated wire contract.\n\n## Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`RoutineOptions`](../interfaces/RoutineOptions.md) |\n\n## Returns\n\n\\{ `enabled`: `boolean` \\| `undefined`; `kind`: `\"Agent\"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined`; `task`: \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \\}\n\n| Name | Type | Default value | Description |\n| ------ | ------ | ------ | ------ |\n| `enabled` | `boolean` \\| `undefined` | `options.enabled` | - |\n| `kind` | `\"Agent\"` | - | - |\n| `name` | `string` | `options.name` | - |\n| `run_visibility` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \\| `undefined` | `options.runVisibility` | - |\n| `task` | \\{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \\| `null`; `prompt`: `string`; `user_prompt`: `string`; \\} | - | - |\n| `task.agent?` | [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \\| `null` | - | - |\n| `task.mcp_servers?` | [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[] | - | Apps the routine requires on top of the agent's own. The owner must have each one connected to save the routine and for it to run. |\n| `task.model?` | `string` \\| `null` | - | - |\n| `task.prompt` | `string` | - | - |\n| `task.user_prompt` | `string` | - | - |\n| `trigger` | [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md) | - | - |\n\n\n<!-- src/entities/routines/routine/interfaces/RoutineOptions.md -->\n# Interface: RoutineOptions\n\nConfiguration of an agent routine.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-agent\"></a> `agent?` | [`Agent`](../../../agents/agent/classes/Agent.md) | Agent to run the task. |\n| <a id=\"property-enabled\"></a> `enabled?` | `boolean` | Whether triggers can start executions. Defaults to true on creation. |\n| <a id=\"property-model\"></a> `model?` | `string` | Model override. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | Instructions delivered to the agent. |\n| <a id=\"property-runvisibility\"></a> `runVisibility?` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) | Whether runs appear in Home and the Agents list. Defaults to `unlisted` on creation; an update that omits it keeps the stored value. |\n| <a id=\"property-trigger\"></a> `trigger` | [`RoutineTriggerOptions`](../type-aliases/RoutineTriggerOptions.md) | Schedules or Macro events that start the routine. |\n| <a id=\"property-userprompt\"></a> `userPrompt` | `string` | Original user instructions. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineEventFilter.md -->\n# Type Alias: RoutineEventFilter\n\n> **RoutineEventFilter** = `Omit`\\<[`EventFilter`](../../../../../generated/scheduled-action/types.gen/type-aliases/EventFilter.md), `\"ids\"` \\| `\"condition\"`\\> & \\{ `condition?`: `string`; `entities?`: [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[]; \\}\n\nAn event selector references resources by typed handles.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `condition?` | `string` | Optional yes/no condition on the triggering content. |\n| `entities?` | [`EntityReference`](../../../reference/type-aliases/EntityReference.md)[] | Resource selectors for these events. Omit to match all resources. |\n\n\n<!-- src/entities/routines/routine/type-aliases/RoutineTriggerOptions.md -->\n# Type Alias: RoutineTriggerOptions\n\n> **RoutineTriggerOptions** = [`SingleRoutineTrigger`](SingleRoutineTrigger.md) \\| \\{ `triggers`: [`SingleRoutineTrigger`](SingleRoutineTrigger.md)[]; `type`: `\"multiple\"`; \\}\n\nOne or multiple routine triggers.\n\n\n<!-- src/entities/routines/routine/type-aliases/SingleRoutineTrigger.md -->\n# Type Alias: SingleRoutineTrigger\n\n> **SingleRoutineTrigger** = `Extract`\\<[`RoutineTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/RoutineTrigger.md), \\{ `type`: `\"cron\"`; \\}\\> \\| \\{ `filters`: [`RoutineEventFilter`](RoutineEventFilter.md)[]; `type`: `\"events\"`; \\}\n\nOne schedule or set of event selectors.\n"},{"name": "unfurls",diff --git a/crates/agent_session/src/domain/coding_agents.rs b/crates/agent_session/src/domain/coding_agents.rsindex 6226a2e13c..1be92b65c9 100644--- a/crates/agent_session/src/domain/coding_agents.rs+++ b/crates/agent_session/src/domain/coding_agents.rs@@ -223,6 +223,7 @@ impl<Directory: CodingAgentDirectory, Sessions: RoutineSessions>owner: command.user_id.clone(),bot_id,model: None,+ mcp_servers: Vec::new(),},session_id,source: SessionSource::Agent,diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rsindex e8c61ca0c2..1774689c6a 100644--- a/crates/agent_session/src/domain/model.rs+++ b/crates/agent_session/src/domain/model.rs@@ -178,7 +178,8 @@ pub enum SessionStatus {}/// Which Pipedream MCP servers a session is handed: the agent's own choice,-/// snapshotted onto the session at creation like `instructions`. The servers+/// plus any apps a routine requires, snapshotted onto the session at creation+/// like `instructions`. The servers/// it resolves to are re-listed before each prompt, so an app the owner/// connects mid-session reaches a live agent that can `session/resume`;/// editing the agent's selection applies to its next session.diff --git a/crates/agent_session/src/domain/routines.rs b/crates/agent_session/src/domain/routines.rsindex ec5be001df..d1932b9e4f 100644--- a/crates/agent_session/src/domain/routines.rs+++ b/crates/agent_session/src/domain/routines.rs@@ -43,3 +43,13 @@ pub trait RoutineSessions: Send + Sync + 'static {command: RoutineSessionAction,) -> impl Future<Output = Result<(), RoutineSessionError>> + Send;}++/// The Pipedream apps a user has connected and enabled for tool use, which+/// is what the egress proxy treats as connected.+pub trait ConnectedApps: Send + Sync + 'static {+ /// App slugs of the user's enabled connections.+ fn connected_app_slugs(+ &self,+ user: ¯o_user_id::user_id::MacroUserIdStr<'static>,+ ) -> impl Future<Output = anyhow::Result<Vec<String>>> + Send;+}diff --git a/crates/agent_session/src/domain/routines/models.rs b/crates/agent_session/src/domain/routines/models.rsindex d7307c867f..8cd225c2ee 100644--- a/crates/agent_session/src/domain/routines/models.rs+++ b/crates/agent_session/src/domain/routines/models.rs@@ -5,7 +5,7 @@ use bots::domain::models::BotId;use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};-use crate::domain::model::{AgentSessionId, SessionSource, SessionVisibility};+use crate::domain::model::{AgentMcpServer, AgentSessionId, SessionSource, SessionVisibility};/// A persona selected by a routine's validated user owner.#[derive(Debug, Clone, Serialize, Deserialize)]@@ -16,6 +16,10 @@ pub struct ValidateRoutineSession {pub bot_id: BotId,/// Omitted means the persona's current default at preparation time.pub model: Option<String>,+ /// Apps the routine itself requires. The owner must have each one+ /// connected; the session gets them on top of the persona's own servers.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub mcp_servers: Vec<AgentMcpServer>,}/// An authorized selection. Validation does not establish runtime availability.@@ -146,6 +150,13 @@ pub enum RoutineSessionError {/// Persona access or session ownership was denied.#[error("routine owner is not authorized")]Forbidden,+ /// The owner has not connected an app the routine requires.+ #[error("connect every app this routine requires")]+ AppNotConnected,+ /// The selected agent's runtime opens its own sessions and cannot be+ /// handed the routine's apps.+ #[error("the selected agent cannot use apps added to a routine")]+ AppsUnsupported,/// A runtime could not serve the selected agent.#[error("selected runtime is unavailable")]RuntimeUnavailable,diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rsindex 48f73ec516..5fa0b74c6f 100644--- a/crates/agent_session/src/domain/routines/service.rs+++ b/crates/agent_session/src/domain/routines/service.rs@@ -4,9 +4,9 @@ use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};use model_owner::Owner;use super::status::action_status;-use super::{RoutineSessions, models::*};+use super::{ConnectedApps, RoutineSessions, models::*};use crate::domain::error::AgentSessionError;-use crate::domain::model::{AgentSession, AgentSessionId};+use crate::domain::model::{AgentMcpServer, AgentMcpServers, AgentSession, AgentSessionId};use crate::domain::ports::{AgentSessionNotificationRecipient, BotDirectory, ControlDisposition, ControlEvent,ExternalSessionRequester, ManagedPersonaError, OpenManagedSession, RequestedExternalSession,@@ -16,16 +16,17 @@ use crate::domain::service::AgentSessionService;/// Domain orchestration using the same provisioning and controls as interactive sessions.#[derive(Clone)]-pub struct RoutineSessionsService<Bots, Opener, External, Sessions, Controls> {+pub struct RoutineSessionsService<Bots, Opener, External, Sessions, Controls, Apps> {bots: Bots,opener: Opener,external: External,sessions: Sessions,controls: Controls,+ apps: Apps,}-impl<Bots, Opener, External, Sessions, Controls>- RoutineSessionsService<Bots, Opener, External, Sessions, Controls>+impl<Bots, Opener, External, Sessions, Controls, Apps>+ RoutineSessionsService<Bots, Opener, External, Sessions, Controls, Apps>{/// Compose existing capabilities; no new runtime or persistence implementation.pub fn new(@@ -34,6 +35,7 @@ impl<Bots, Opener, External, Sessions, Controls>external: External,sessions: Sessions,controls: Controls,+ apps: Apps,) -> Self {Self {bots,@@ -41,15 +43,17 @@ impl<Bots, Opener, External, Sessions, Controls>external,sessions,controls,+ apps,}}}-impl<Bots, Opener, External, Sessions, Controls>- RoutineSessionsService<Bots, Opener, External, Sessions, Controls>+impl<Bots, Opener, External, Sessions, Controls, Apps>+ RoutineSessionsService<Bots, Opener, External, Sessions, Controls, Apps>whereBots: BotDirectory,Sessions: AgentSessionService,+ Apps: ConnectedApps,{async fn select(&self,@@ -62,7 +66,7 @@ where{return Err(RoutineSessionError::InvalidCommand);}- persona_for_owner(+ let persona = persona_for_owner(&self.bots,selection.bot_id,&Owner::User(selection.owner.clone()),@@ -76,7 +80,41 @@ whereManagedPersonaError::Unknown| ManagedPersonaError::NotAgent| ManagedPersonaError::UnmanagedSystemBot => RoutineSessionError::PersonaUnavailable,- })+ })?;+ self.require_apps(selection, &persona).await?;+ Ok(persona)+ }++ /// Checked on save and again before every run, so an app disconnected+ /// since fails the run instead of leaving the agent without it.+ async fn require_apps(+ &self,+ selection: &ValidateRoutineSession,+ persona: &SelectedPersona,+ ) -> Result<(), RoutineSessionError> {+ if selection.mcp_servers.is_empty() {+ return Ok(());+ }+ if matches!(persona, SelectedPersona::External { .. }) {+ return Err(RoutineSessionError::AppsUnsupported);+ }+ let connected = self+ .apps+ .connected_app_slugs(&selection.owner)+ .await+ .map_err(|error| {+ tracing::warn!(error = ?error, "could not list a routine owner's connected apps");+ RoutineSessionError::OperationFailed+ })?;+ if selection+ .mcp_servers+ .iter()+ .all(|server| connected.contains(&server.app_slug))+ {+ Ok(())+ } else {+ Err(RoutineSessionError::AppNotConnected)+ }}async fn owned_session(@@ -102,14 +140,15 @@ where}}-impl<Bots, Opener, External, Sessions, Controls> RoutineSessions- for RoutineSessionsService<Bots, Opener, External, Sessions, Controls>+impl<Bots, Opener, External, Sessions, Controls, Apps> RoutineSessions+ for RoutineSessionsService<Bots, Opener, External, Sessions, Controls, Apps>whereBots: BotDirectory,Opener: SessionOpener,External: ExternalSessionRequester,Sessions: AgentSessionService,Controls: AgentSessionNotificationRecipient,+ Apps: ConnectedApps,{async fn validate(&self,@@ -130,7 +169,10 @@ wherelet selection = command.selection;let owner = Owner::User(selection.owner.clone());let session = match persona {- SelectedPersona::Managed(profile) => {+ SelectedPersona::Managed(mut profile) => {+ if let Some(managed) = &mut profile.profile {+ add_routine_apps(&mut managed.mcp_servers, &selection.mcp_servers);+ }self.opener.open_managed_session(OpenManagedSession {id: Some(command.session_id),@@ -271,6 +313,19 @@ where}}+/// An agent limited to selected apps also gets the routine's. One that uses+/// every app its runner connected already has them: they are required to be+/// connected.+fn add_routine_apps(servers: &mut AgentMcpServers, required: &[AgentMcpServer]) {+ if let AgentMcpServers::Selected { servers } = servers {+ for app in required {+ if !servers.iter().any(|server| server.app_slug == app.app_slug) {+ servers.push(app.clone());+ }+ }+ }+}+fn validate_session_id(id: AgentSessionId) -> Result<(), RoutineSessionError> {if id.as_uuid().get_version_num() != 7 {return Err(RoutineSessionError::InvalidCommand);diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rsindex 265665f3b4..537ba0cbf8 100644--- a/crates/agent_session/src/domain/routines/service/test.rs+++ b/crates/agent_session/src/domain/routines/service/test.rs@@ -1,7 +1,7 @@use super::*;use crate::domain::error::Result as SessionResult;use crate::domain::model::{- AgentMcpServers, ReplicaId, SandboxSize, SessionSource, SessionVisibility,+ AgentMcpServer, AgentMcpServers, ReplicaId, SandboxSize, SessionSource, SessionVisibility,};use crate::domain::ports::{AcceptedControl, BotFacts, ManagedAgentProfile, NoOpAgentSessionNameGenerator, NoOpRealtime,@@ -181,16 +181,29 @@ impl AgentSessionNotificationRecipient for Controls {}}+#[derive(Clone, Default)]+struct Apps(Arc<Mutex<Vec<String>>>);++impl ConnectedApps for Apps {+ async fn connected_app_slugs(+ &self,+ _: &MacroUserIdStr<'static>,+ ) -> anyhow::Result<Vec<String>> {+ Ok(self.0.lock().unwrap().clone())+ }+}+type Sessions = AgentSessionServiceImpl<InMemoryAgentSessionRepo,FoldedMessageService<InMemoryAgentSessionRepo>,NoOpRealtime,>;-type Service = RoutineSessionsService<Directory, Openings, Openings, Sessions, Controls>;+type Service = RoutineSessionsService<Directory, Openings, Openings, Sessions, Controls, Apps>;struct Fixture {service: Service,directory: Directory,+ apps: Apps,openings: Openings,controls: Controls,repo: InMemoryAgentSessionRepo,@@ -229,16 +242,19 @@ impl Fixture {let openings = Openings::default();*openings.response.lock().unwrap() = Some(session.clone());let controls = Controls::default();+ let apps = Apps::default();let service = RoutineSessionsService::new(directory.clone(),openings.clone(),openings.clone(),sessions,controls.clone(),+ apps.clone(),);Self {service,directory,+ apps,openings,controls,repo,@@ -251,6 +267,7 @@ impl Fixture {owner: self.session.owner_user().unwrap().clone(),bot_id: self.session.bot_id,model: None,+ mcp_servers: Vec::new(),}}@@ -586,3 +603,140 @@ fn commands_reject_malformed_owner_and_ids_at_deserialization() {value["session_id"] = serde_json::json!("not-a-uuid");assert!(serde_json::from_value::<RoutineSessionAction>(value).is_err());}++#[tokio::test]+async fn a_routine_app_must_be_connected_to_save_and_to_run() {+ let fx = Fixture::new(true);+ let mut selection = fx.selection();+ selection.mcp_servers = vec![AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }];+ *fx.apps.0.lock().unwrap() = vec!["notion".into()];+ assert_eq!(+ fx.service.validate(selection.clone()).await.unwrap_err(),+ RoutineSessionError::AppNotConnected+ );++ *fx.apps.0.lock().unwrap() = vec!["notion".into(), "linear".into()];+ fx.service.validate(selection.clone()).await.unwrap();++ // Disconnected after saving: the run fails before any session opens.+ *fx.apps.0.lock().unwrap() = vec!["notion".into()];+ assert_eq!(+ fx.service+ .prepare(PrepareRoutineSession {+ selection,+ ..fx.prepare()+ })+ .await+ .unwrap_err(),+ RoutineSessionError::AppNotConnected+ );+ assert!(fx.openings.managed.lock().unwrap().is_empty());+}++#[tokio::test]+async fn routine_apps_are_added_to_an_agent_limited_to_selected_apps() {+ let fx = Fixture::new(true);+ fx.directory+ .0+ .lock()+ .unwrap()+ .as_mut()+ .unwrap()+ .managed_profile+ .as_mut()+ .unwrap()+ .mcp_servers = AgentMcpServers::Selected {+ servers: vec![+ AgentMcpServer {+ app_slug: "notion".into(),+ server_name: "Notion".into(),+ },+ AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ },+ ],+ };+ *fx.apps.0.lock().unwrap() = vec!["linear".into(), "slack".into()];+ let mut command = fx.prepare();+ command.selection.mcp_servers = vec![+ AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ },+ AgentMcpServer {+ app_slug: "slack".into(),+ server_name: "Slack".into(),+ },+ ];+ fx.service.prepare(command).await.unwrap();+ let requests = fx.openings.managed.lock().unwrap();+ assert_eq!(+ requests[0]+ .profile+ .as_ref()+ .unwrap()+ .profile+ .as_ref()+ .unwrap()+ .mcp_servers,+ AgentMcpServers::Selected {+ servers: vec![+ AgentMcpServer {+ app_slug: "notion".into(),+ server_name: "Notion".into(),+ },+ AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ },+ AgentMcpServer {+ app_slug: "slack".into(),+ server_name: "Slack".into(),+ },+ ],+ }+ );+}++#[tokio::test]+async fn an_agent_using_every_connected_app_keeps_that_scope() {+ let fx = Fixture::new(true);+ *fx.apps.0.lock().unwrap() = vec!["linear".into()];+ let mut command = fx.prepare();+ command.selection.mcp_servers = vec![AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }];+ fx.service.prepare(command).await.unwrap();+ let requests = fx.openings.managed.lock().unwrap();+ assert_eq!(+ requests[0]+ .profile+ .as_ref()+ .unwrap()+ .profile+ .as_ref()+ .unwrap()+ .mcp_servers,+ AgentMcpServers::OwnerConnections+ );+}++#[tokio::test]+async fn an_external_agent_cannot_take_routine_apps() {+ let fx = Fixture::new(false);+ *fx.apps.0.lock().unwrap() = vec!["linear".into()];+ let mut selection = fx.selection();+ selection.mcp_servers = vec![AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }];+ assert_eq!(+ fx.service.validate(selection).await.unwrap_err(),+ RoutineSessionError::AppsUnsupported+ );+}diff --git a/crates/agent_session/src/inbound/routine_sessions.rs b/crates/agent_session/src/inbound/routine_sessions.rsindex fc6cf45011..4f8ef07a41 100644--- a/crates/agent_session/src/inbound/routine_sessions.rs+++ b/crates/agent_session/src/inbound/routine_sessions.rs@@ -109,6 +109,9 @@ impl IntoResponse for ApiError {ai_billing::inbound::admission::admission_status(error)}RoutineSessionError::InvalidCommand => StatusCode::BAD_REQUEST,+ RoutineSessionError::AppNotConnected | RoutineSessionError::AppsUnsupported => {+ StatusCode::UNPROCESSABLE_ENTITY+ }RoutineSessionError::Forbidden => StatusCode::FORBIDDEN,RoutineSessionError::PersonaUnavailable => StatusCode::NOT_FOUND,RoutineSessionError::RuntimeUnavailable => StatusCode::SERVICE_UNAVAILABLE,diff --git a/crates/routines/src/domain.rs b/crates/routines/src/domain.rsindex 22a05fac11..d6664deac0 100644--- a/crates/routines/src/domain.rs+++ b/crates/routines/src/domain.rs@@ -96,6 +96,20 @@ pub struct RoutineConfiguration {pub target: RoutineTarget,/// Time and repetition.pub schedule: RoutineSchedule,+ /// Apps every run needs, on top of the target's own. The user must already+ /// have each one connected (offer a connect link via DiscoverConnectors if+ /// not). Updates replace the list: restate it to keep the apps.+ #[serde(default)]+ pub required_apps: Vec<RoutineApp>,+}+/// A Pipedream app a routine requires.+#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct RoutineApp {+ /// Pipedream app slug, e.g. `linear`.+ pub app_slug: String,+ /// Display name, e.g. `Linear`.+ pub name: String,}impl RoutineConfiguration {/// Validate the user's intent independently of its transport representation.diff --git a/crates/routines/src/outbound.rs b/crates/routines/src/outbound.rsindex e3e9c9d263..87c06ce30c 100644--- a/crates/routines/src/outbound.rs+++ b/crates/routines/src/outbound.rs@@ -92,9 +92,12 @@ impl RoutineClient {}Ok(body)}- 400 | 422 => bail!(+ 400 => bail!("Invalid routine configuration or unavailable model/agent. Check the schedule and select an accessible agent from ListAgents using its bot.botId."),+ 422 => bail!(+ "Invalid routine configuration, or a required app is not connected or unusable by the selected agent. Ask the user to connect each app in requiredApps (DiscoverConnectors gives a link) or remove it."+ ),401 | 403 | 404 => bail!("Routine or target is unavailable to this user."),402 => bail!("The user's AI allowance is exhausted, so the routine cannot run now."),409 => bail!("Routine is running or changed. Read it again before editing."),@@ -238,7 +241,16 @@ struct WireExecution {fn configuration_body(config: &RoutineConfiguration, now: DateTime<Utc>) -> Result<Value> {config.validate(now)?;let (schedule, timezone) = config.schedule.cron(now)?;- let mut task = serde_json::json!({ "prompt": "", "user_prompt": config.instructions });+ let mcp_servers: Vec<Value> = config+ .required_apps+ .iter()+ .map(|app| serde_json::json!({ "app_slug": app.app_slug, "server_name": app.name }))+ .collect();+ let mut task = serde_json::json!({+ "prompt": "",+ "user_prompt": config.instructions,+ "mcp_servers": mcp_servers,+ });match &config.target {RoutineTarget::Model { model } => task["model"] = model.clone().into(),RoutineTarget::Agent { agent_id } => {diff --git a/crates/routines/src/outbound/test.rs b/crates/routines/src/outbound/test.rsindex 731d34d02e..b3c0087cf4 100644--- a/crates/routines/src/outbound/test.rs+++ b/crates/routines/src/outbound/test.rs@@ -1,4 +1,5 @@use super::*;+use crate::domain::RoutineApp;use crate::domain::RoutineSchedule;#[test]fn agent_tasks_do_not_silently_become_model_tasks_or_override_defaults() {@@ -11,9 +12,17 @@ fn agent_tasks_do_not_silently_become_model_tasks_or_override_defaults() {expression: "0 0 9 * * *".into(),timezone: "UTC".into(),},+ required_apps: vec![RoutineApp {+ app_slug: "linear".into(),+ name: "Linear".into(),+ }],};let body = configuration_body(&config, Utc::now()).unwrap();assert_eq!(body["task"]["agent"]["bot_id"], agent_id.to_string());+ assert_eq!(+ body["task"]["mcp_servers"],+ serde_json::json!([{ "app_slug": "linear", "server_name": "Linear" }])+ );assert!(body["task"].get("model").is_none());assert!(body.get("enabled").is_none());assert!(body.get("owner").is_none());@@ -78,6 +87,7 @@ async fn requests_forward_authenticated_identity_and_preserve_target_and_activatschedule: RoutineSchedule::Once {at: Utc::now() + chrono::Duration::hours(1),},+ required_apps: Vec::new(),};client.create(&user, &config).await.unwrap();client.update(&user, id, &config).await.unwrap();diff --git a/crates/scheduled_action/AGENTS.md b/crates/scheduled_action/AGENTS.mdindex 9df409d732..fd616c7ee5 100644--- a/crates/scheduled_action/AGENTS.md+++ b/crates/scheduled_action/AGENTS.md@@ -61,6 +61,12 @@ that listener is ready. Cancellation can stop the gate before startup finishes.## Gotchas+- A task's `mcp_servers` are apps the routine requires. The owner must have+ each connected: `TargetValidation` checks on save and+ `RoutineSessions::prepare` checks again on every run, then adds them to an+ agent limited to selected apps. An update that omits the key is rejected+ when the stored task has apps (`require_explicit_selection`).+- `TODO.md` tracks open follow-ups (unified history list, delete schedules,sharing/permissions) — check it before assuming a listed gap is unintentional.- A new configuration field needs `#[serde(default)]` in `ActionConfiguration`diff --git a/crates/scheduled_action/src/domain/models.rs b/crates/scheduled_action/src/domain/models.rsindex be596d52e9..6c0f4f2d54 100644--- a/crates/scheduled_action/src/domain/models.rs+++ b/crates/scheduled_action/src/domain/models.rs@@ -1,5 +1,6 @@use anyhow::Result;use bot_id::BotId;+use bots::domain::models::AgentMcpServer;use chrono::{DateTime, Duration, Utc};use chrono_tz::Tz;use cron::Schedule as CronSchedule;@@ -108,6 +109,10 @@ pub struct AgentTask {/// Absent when using Macro's agent-session runtime with a selected model.#[serde(default, skip_serializing_if = "Option::is_none")]pub agent: Option<AgentTaskAgent>,+ /// Apps the routine requires on top of the agent's own. The owner must+ /// have each one connected to save the routine and for it to run.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub mcp_servers: Vec<AgentMcpServer>,pub prompt: String,pub user_prompt: String,}diff --git a/crates/scheduled_action/src/domain/service.rs b/crates/scheduled_action/src/domain/service.rsindex 7c974ec2ce..999c573dfb 100644--- a/crates/scheduled_action/src/domain/service.rs+++ b/crates/scheduled_action/src/domain/service.rs@@ -24,7 +24,7 @@ use super::models::{use super::ports::{ScheduledActionExecutor, ScheduledActionRepo, ScheduledActionService, TaskTargetValidator,};-use super::target_validation::{ModelOnlyTargets, require_explicit_agent};+use super::target_validation::{ModelOnlyTargets, require_explicit_selection};#[cfg(test)]pub(crate) mod test;@@ -146,7 +146,7 @@ impl<Rpo: ScheduledActionRepo, Exe, Grants, Targets>whereTargets: TaskTargetValidator,{- require_explicit_agent(&action.task, &input.task)?;+ require_explicit_selection(&action.task, &input.task)?;let trigger_changed = !same_trigger(&action.trigger, &input.trigger);let configuration_changed = trigger_changed|| action.name != input.namediff --git a/crates/scheduled_action/src/domain/target_runner.rs b/crates/scheduled_action/src/domain/target_runner.rsindex c1fe0307fa..6a348900ed 100644--- a/crates/scheduled_action/src/domain/target_runner.rs+++ b/crates/scheduled_action/src/domain/target_runner.rs@@ -61,6 +61,7 @@ impl<Sessions: RoutineSessions, Events: RoutineEventReader> ScheduledAgentRunnerowner: identity.owner.clone(),bot_id,model: model.map(|model| model.as_str().to_owned()),+ mcp_servers: task.mcp_servers.clone(),},session_id: identity.session_id,source: SessionSource::Routine,diff --git a/crates/scheduled_action/src/domain/target_runner/test.rs b/crates/scheduled_action/src/domain/target_runner/test.rsindex 89891ea37e..7685ff1142 100644--- a/crates/scheduled_action/src/domain/target_runner/test.rs+++ b/crates/scheduled_action/src/domain/target_runner/test.rs@@ -1131,3 +1131,36 @@ async fn a_manual_run_tells_the_agent_its_owner_started_it() {})));}++#[tokio::test]+async fn preparation_carries_the_routine_apps_and_fails_when_one_is_disconnected() {+ let connected = runner(Sessions::default());+ let mut action = action();+ action.task["mcp_servers"] = json!([{"app_slug": "linear", "server_name": "Linear"}]);+ let mut handle = ExecutionHandle::default();+ connected.prepare(&action, &mut handle).await.unwrap();+ assert_eq!(+ connected.sessions.preparations.lock().unwrap()[0]+ .selection+ .mcp_servers,+ vec![bots::domain::models::AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }]+ );++ let disconnected = runner(Sessions {+ prepare_error: Some(RoutineSessionError::AppNotConnected),+ ..Default::default()+ });+ let mut handle = ExecutionHandle::default();+ let error = disconnected+ .prepare(&action, &mut handle)+ .await+ .unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&RoutineSessionError::AppNotConnected)+ );+ assert!(handle.resource.is_none());+}diff --git a/crates/scheduled_action/src/domain/target_validation.rs b/crates/scheduled_action/src/domain/target_validation.rsindex c74d2704e4..4c96a6ddaa 100644--- a/crates/scheduled_action/src/domain/target_validation.rs+++ b/crates/scheduled_action/src/domain/target_validation.rs@@ -21,6 +21,8 @@ pub enum TargetValidationError {AgentsDisabled,#[error("this routine selects an agent; reload or upgrade your client before updating")]ExplicitAgentRequired,+ #[error("this routine requires apps; reload or upgrade your client before updating")]+ ExplicitAppsRequired,}/// Default acceptance policy for composition roots that have not enabled agents.@@ -28,7 +30,10 @@ pub struct ModelOnlyTargets;impl TaskTargetValidator for ModelOnlyTargets {async fn validate_task(&self, task: &Value, _owner: &MacroUserIdStr<'static>) -> Result<()> {- parse_task(task, false)?;+ // Required apps need the session domain to check the owner's connections.+ if !parse_task(task, false)?.mcp_servers.is_empty() {+ return Err(TargetValidationError::AgentsDisabled.into());+ }Ok(())}}@@ -57,6 +62,7 @@ impl<Sessions: RoutineSessions> TaskTargetValidator for TargetValidation<Sessionowner: owner.clone(),bot_id,model: model.map(|model| model.as_str().to_owned()),+ mcp_servers: task.mcp_servers.clone(),}).await?;Ok(())@@ -77,12 +83,22 @@ fn parse_task(task: &Value, agents_enabled: bool) -> Result<AgentTask, TargetVal/// The raw JSON preserves absent versus explicit null without changing stored contracts./// Even a malformed historical selection must not be silently erased by an old client.-pub(super) fn require_explicit_agent(previous: &Value, incoming: &Value) -> Result<()> {+pub(super) fn require_explicit_selection(previous: &Value, incoming: &Value) -> Result<()> {if previous.get("agent").is_some_and(|agent| !agent.is_null())&& incoming.get("agent").is_none(){return Err(TargetValidationError::ExplicitAgentRequired.into());}+ // Same for required apps: a client that predates them omits the key, and+ // an update must not drop the apps it never showed.+ if previous+ .get("mcp_servers")+ .and_then(Value::as_array)+ .is_some_and(|servers| !servers.is_empty())+ && incoming.get("mcp_servers").is_none()+ {+ return Err(TargetValidationError::ExplicitAppsRequired.into());+ }Ok(())}diff --git a/crates/scheduled_action/src/domain/target_validation/test.rs b/crates/scheduled_action/src/domain/target_validation/test.rsindex ae74bf3c36..156bef7903 100644--- a/crates/scheduled_action/src/domain/target_validation/test.rs+++ b/crates/scheduled_action/src/domain/target_validation/test.rs@@ -168,13 +168,92 @@ fn requires_explicit_null_to_remove_even_an_unparseable_historical_selection() {agent_task(),json!({"agent":{"bot_id":"deleted-legacy-id"}}),] {- let error = require_explicit_agent(&previous, &json!({"model":"model"})).unwrap_err();+ let error = require_explicit_selection(&previous, &json!({"model":"model"})).unwrap_err();assert_eq!(error.downcast_ref(),Some(&TargetValidationError::ExplicitAgentRequired));- require_explicit_agent(&previous, &json!({"agent":null,"model":"model"})).unwrap();- require_explicit_agent(&previous, &agent_task()).unwrap();+ require_explicit_selection(&previous, &json!({"agent":null,"model":"model"})).unwrap();+ require_explicit_selection(&previous, &agent_task()).unwrap();}- require_explicit_agent(&json!({"model":"old"}), &json!({"model":"new"})).unwrap();+ require_explicit_selection(&json!({"model":"old"}), &json!({"model":"new"})).unwrap();+}++#[tokio::test]+async fn hands_the_routine_apps_to_the_session_check() {+ let sessions = Arc::new(Sessions::default());+ let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();+ TargetValidation::new(sessions.clone(), true)+ .validate_task(+ &json!({+ "agent": {"bot_id": BOT},+ "mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],+ "prompt": "instructions",+ "user_prompt": "task",+ }),+ &owner,+ )+ .await+ .unwrap();+ assert_eq!(+ sessions.validations.lock().unwrap()[0].mcp_servers,+ vec![bots::domain::models::AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }]+ );++ *sessions.error.lock().unwrap() = Some(RoutineSessionError::AppNotConnected);+ let error = TargetValidation::new(sessions.clone(), true)+ .validate_task(+ &json!({+ "model": "runtime/model",+ "mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],+ "prompt": "instructions",+ "user_prompt": "task",+ }),+ &owner,+ )+ .await+ .unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&RoutineSessionError::AppNotConnected)+ );+}++#[tokio::test]+async fn a_validator_that_cannot_check_connections_rejects_routine_apps() {+ let owner = MacroUserIdStr::parse_from_str(OWNER).unwrap();+ let error = ModelOnlyTargets+ .validate_task(+ &json!({+ "model": "runtime/model",+ "mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],+ "prompt": "instructions",+ "user_prompt": "task",+ }),+ &owner,+ )+ .await+ .unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&TargetValidationError::AgentsDisabled)+ );+}++#[test]+fn an_update_must_restate_the_routine_apps_to_keep_or_clear_them() {+ let previous = json!({+ "model": "model",+ "mcp_servers": [{"app_slug": "linear", "server_name": "Linear"}],+ });+ let error = require_explicit_selection(&previous, &json!({"model":"model"})).unwrap_err();+ assert_eq!(+ error.downcast_ref(),+ Some(&TargetValidationError::ExplicitAppsRequired)+ );+ require_explicit_selection(&previous, &json!({"model":"model","mcp_servers":[]})).unwrap();+ require_explicit_selection(&json!({"model":"old"}), &json!({"model":"new"})).unwrap();}diff --git a/crates/scheduled_action/src/inbound/axum_router.rs b/crates/scheduled_action/src/inbound/axum_router.rsindex a3f2a99746..3745cd9f91 100644--- a/crates/scheduled_action/src/inbound/axum_router.rs+++ b/crates/scheduled_action/src/inbound/axum_router.rs@@ -527,7 +527,8 @@ impl IntoResponse for ScheduledActionApiError {TargetValidationError::InvalidTask | TargetValidationError::AgentsDisabled => {StatusCode::BAD_REQUEST}- TargetValidationError::ExplicitAgentRequired => StatusCode::CONFLICT,+ TargetValidationError::ExplicitAgentRequired+ | TargetValidationError::ExplicitAppsRequired => StatusCode::CONFLICT,};return (status, validation.to_string()).into_response();}@@ -541,6 +542,9 @@ impl IntoResponse for ScheduledActionApiError {(StatusCode::NOT_FOUND, session.to_string())}RoutineSessionError::Forbidden => (StatusCode::FORBIDDEN, session.to_string()),+ RoutineSessionError::AppNotConnected | RoutineSessionError::AppsUnsupported => {+ (StatusCode::UNPROCESSABLE_ENTITY, session.to_string())+ }RoutineSessionError::Conflict => (StatusCode::CONFLICT, session.to_string()),RoutineSessionError::RuntimeUnavailable | RoutineSessionError::OperationFailed => (StatusCode::SERVICE_UNAVAILABLE,diff --git a/crates/scheduled_action/src/outbound/agent_session_client/test.rs b/crates/scheduled_action/src/outbound/agent_session_client/test.rsindex d67363cd4c..7e55f6f289 100644--- a/crates/scheduled_action/src/outbound/agent_session_client/test.rs+++ b/crates/scheduled_action/src/outbound/agent_session_client/test.rs@@ -118,6 +118,10 @@ fn selection() -> ValidateRoutineSession {owner: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),bot_id: BotId::new_from_uuid(generate_uuid_v7()),model: Some("selected/runtime-model".into()),+ mcp_servers: vec![bots::domain::models::AgentMcpServer {+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ }],}}diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex d4b089b502..b42907fbdc 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -858,8 +858,8 @@ to remove it. The routine's top bar uses the task breadcrumb layout:**Routines → routine name**, followed by the three-dot menu for duplication anddeletion. Tabs immediately beside that menu switch between **Overview** and**Run History**. Overview follows the project home layout: an editable title,-a model property chip and the **Runs hidden** / **Runs shown** chip, and a plain-prompt editor. A trigger card sits below the+a model property chip, an apps chip, and the **Runs hidden** / **Runs shown**+chip, and a plain prompt editor. A trigger card sits below themodel: trigger chips at the top left, **Run now** at the top right, and the**Enabled** / **Disabled** status with **Next run** along the bottom.The **Run options** dropdown contains@@ -873,6 +873,15 @@ couldn’t be checked**, marked **Skipped**; consecutive skips collapse into oneShift opens it in another split. **Back to routines** returns to the list in thesame pane.+The apps chip (**Add apps** in the composer and Overview) opens **Required+apps**: search the Pipedream catalog and pick the apps every run needs, on top+of the agent's own. Each picked app shows **Connected** or a **Connect** button+for the routine owner. Until every listed app is connected the composer shows+**Connect every app this routine requires.** and Overview does not save; the+server rejects the save too, and a run whose app was disconnected later fails+before a session opens. Agents whose runtime opens its own sessions (macrod,+other external runtimes) cannot take routine apps.+**Disable routine** pauses immediately, including with invalidunsaved edits. Resuming waits for valid settings to save. Settings autosave inorder without changing activation. **Run Now** waits for the latest valid editdiff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.mdindex 8ba2a949f1..76089e12e6 100644--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/README.md@@ -7,6 +7,7 @@- [ActionExecutionRecord](type-aliases/ActionExecutionRecord.md)- [ActionKind](type-aliases/ActionKind.md)- [ActionTrigger](type-aliases/ActionTrigger.md)+- [AgentMcpServer](type-aliases/AgentMcpServer.md)- [AgentTask](type-aliases/AgentTask.md)- [AgentTaskAgent](type-aliases/AgentTaskAgent.md)- [AiAdmissionErrorBody](type-aliases/AiAdmissionErrorBody.md)diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.mdnew file mode 100644index 0000000000..25d44f761a--- /dev/null+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md@@ -0,0 +1,15 @@+# Type Alias: AgentMcpServer++> **AgentMcpServer** = \{ `app_slug`: `string`; `server_name`: `string`; \}++One Pipedream app an agent lists under [`AgentMcpServers::Selected`].++Only the catalog identity is stored. Whether a given person has connected+the app is theirs, resolved at call time by the egress proxy, never here.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-app_slug"></a> `app_slug` | `string` | Pipedream app slug, e.g. `linear`. |+| <a id="property-server_name"></a> `server_name` | `string` | Display name, e.g. `Linear`. |diff --git a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentTask.md b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentTask.mdindex e8236627ec..2337da1d6e 100644--- a/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentTask.md+++ b/packages/sdk-docs/reference/generated/scheduled-action/types.gen/type-aliases/AgentTask.md@@ -1,12 +1,13 @@# Type Alias: AgentTask-> **AgentTask** = \{ `agent?`: `null` \| [`AgentTaskAgent`](AgentTaskAgent.md); `model?`: `null` \| [`RoutineModelId`](RoutineModelId.md); `prompt`: `string`; `user_prompt`: `string`; \}+> **AgentTask** = \{ `agent?`: `null` \| [`AgentTaskAgent`](AgentTaskAgent.md); `mcp_servers?`: [`AgentMcpServer`](AgentMcpServer.md)[]; `model?`: `null` \| [`RoutineModelId`](RoutineModelId.md); `prompt`: `string`; `user_prompt`: `string`; \}## Properties-| Property | Type |-| ------ | ------ |-| <a id="property-agent"></a> `agent?` | `null` \| [`AgentTaskAgent`](AgentTaskAgent.md) |-| <a id="property-model"></a> `model?` | `null` \| [`RoutineModelId`](RoutineModelId.md) |-| <a id="property-prompt"></a> `prompt` | `string` |-| <a id="property-user_prompt"></a> `user_prompt` | `string` |+| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-agent"></a> `agent?` | `null` \| [`AgentTaskAgent`](AgentTaskAgent.md) | - |+| <a id="property-mcp_servers"></a> `mcp_servers?` | [`AgentMcpServer`](AgentMcpServer.md)[] | Apps the routine requires on top of the agent's own. The owner must have each one connected to save the routine and for it to run. |+| <a id="property-model"></a> `model?` | `null` \| [`RoutineModelId`](RoutineModelId.md) | - |+| <a id="property-prompt"></a> `prompt` | `string` | - |+| <a id="property-user_prompt"></a> `user_prompt` | `string` | - |diff --git a/packages/sdk-docs/reference/src/entities/routines/routine/functions/routineBody.md b/packages/sdk-docs/reference/src/entities/routines/routine/functions/routineBody.mdindex da4920954b..7e70432f88 100644--- a/packages/sdk-docs/reference/src/entities/routines/routine/functions/routineBody.md+++ b/packages/sdk-docs/reference/src/entities/routines/routine/functions/routineBody.md@@ -1,6 +1,6 @@# Function: routineBody()-> **routineBody**(`options`): \{ `enabled`: `boolean` \| `undefined`; `kind`: `"Agent"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined`; `task`: \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \}+> **routineBody**(`options`): \{ `enabled`: `boolean` \| `undefined`; `kind`: `"Agent"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined`; `task`: \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \}Translate typed routine options into the generated wire contract.@@ -12,17 +12,18 @@ Translate typed routine options into the generated wire contract.## Returns-\{ `enabled`: `boolean` \| `undefined`; `kind`: `"Agent"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined`; `task`: \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \}+\{ `enabled`: `boolean` \| `undefined`; `kind`: `"Agent"`; `name`: `string`; `run_visibility`: [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined`; `task`: \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \}; `trigger`: [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md); \}-| Name | Type | Default value |-| ------ | ------ | ------ |-| `enabled` | `boolean` \| `undefined` | `options.enabled` |-| `kind` | `"Agent"` | - |-| `name` | `string` | `options.name` |-| `run_visibility` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined` | `options.runVisibility` |-| `task` | \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \} | - |-| `task.agent?` | [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null` | - |-| `task.model?` | `string` \| `null` | - |-| `task.prompt` | `string` | - |-| `task.user_prompt` | `string` | - |-| `trigger` | [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md) | - |+| Name | Type | Default value | Description |+| ------ | ------ | ------ | ------ |+| `enabled` | `boolean` \| `undefined` | `options.enabled` | - |+| `kind` | `"Agent"` | - | - |+| `name` | `string` | `options.name` | - |+| `run_visibility` | [`RunVisibility`](../../../../../generated/scheduled-action/types.gen/type-aliases/RunVisibility.md) \| `undefined` | `options.runVisibility` | - |+| `task` | \{ `agent?`: [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null`; `mcp_servers?`: [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[]; `model?`: `string` \| `null`; `prompt`: `string`; `user_prompt`: `string`; \} | - | - |+| `task.agent?` | [`AgentTaskAgent`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentTaskAgent.md) \| `null` | - | - |+| `task.mcp_servers?` | [`AgentMcpServer`](../../../../../generated/scheduled-action/types.gen/type-aliases/AgentMcpServer.md)[] | - | Apps the routine requires on top of the agent's own. The owner must have each one connected to save the routine and for it to run. |+| `task.model?` | `string` \| `null` | - | - |+| `task.prompt` | `string` | - | - |+| `task.user_prompt` | `string` | - | - |+| `trigger` | [`ActionTrigger`](../../../../../generated/scheduled-action/types.gen/type-aliases/ActionTrigger.md) | - | - |diff --git a/packages/sdk/generated/scheduled-action/index.ts b/packages/sdk/generated/scheduled-action/index.tsindex 10ba235bb5..bb63816cee 100644--- a/packages/sdk/generated/scheduled-action/index.ts+++ b/packages/sdk/generated/scheduled-action/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';+export type { ActionConfiguration, ActionConfigurationUpdate, ActionExecutionRecord, ActionKind, ActionTrigger, AgentMcpServer, AgentTask, AgentTaskAgent, AiAdmissionErrorBody, ClientOptions, ConditionResult, CreateScheduledAction, CreateScheduledActionData, CreateScheduledActionError, CreateScheduledActionErrors, CreateScheduledActionResponse, CreateScheduledActionResponses, DeleteScheduledActionData, DeleteScheduledActionError, DeleteScheduledActionErrors, DeleteScheduledActionResponse, DeleteScheduledActionResponses, EmptyResponse, EventFilter, EventFilters, EventName, ExecuteScheduledActionNowData, ExecuteScheduledActionNowError, ExecuteScheduledActionNowErrors, ExecuteScheduledActionNowResponse, ExecuteScheduledActionNowResponses, ExecutionResource, ExecutionResourceType, ExecutionResult, GetScheduledActionData, GetScheduledActionError, GetScheduledActionErrors, GetScheduledActionResponse, GetScheduledActionResponses, InProgressExecution, LegacyActionConfiguration, ListScheduledActionHistoryData, ListScheduledActionHistoryError, ListScheduledActionHistoryErrors, ListScheduledActionHistoryResponse, ListScheduledActionHistoryResponses, ListScheduledActionsData, ListScheduledActionsError, ListScheduledActionsErrors, ListScheduledActionsResponse, ListScheduledActionsResponses, RoutineModelId, RoutineTrigger, RoutineTriggers, RunVisibility, Schedule, ScheduledAction, ScheduledActionHealthData, ScheduledActionHealthResponse, ScheduledActionHealthResponses, ScheduledActionResponse, ScheduledActionUpdate, SetScheduledActionEnabled, SetScheduledActionEnabledData, SetScheduledActionEnabledError, SetScheduledActionEnabledErrors, SetScheduledActionEnabledResponse, SetScheduledActionEnabledResponses, UpdateScheduledAction, UpdateScheduledActionData, UpdateScheduledActionError, UpdateScheduledActionErrors, UpdateScheduledActionResponse, UpdateScheduledActionResponses } from './types.gen';diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.tsindex 44fca170da..b6510ac8d5 100644--- a/packages/sdk/generated/scheduled-action/types.gen.ts+++ b/packages/sdk/generated/scheduled-action/types.gen.ts@@ -76,8 +76,30 @@ export type ActionTrigger = {type: 'multiple';};+/**+ * One Pipedream app an agent lists under [`AgentMcpServers::Selected`].+ *+ * Only the catalog identity is stored. Whether a given person has connected+ * the app is theirs, resolved at call time by the egress proxy, never here.+ */+export type AgentMcpServer = {+ /**+ * Pipedream app slug, e.g. `linear`.+ */+ app_slug: string;+ /**+ * Display name, e.g. `Linear`.+ */+ server_name: string;+};+export type AgentTask = {agent?: null | AgentTaskAgent;+ /**+ * Apps the routine requires on top of the agent's own. The owner must+ * have each one connected to save the routine and for it to run.+ */+ mcp_servers?: Array<AgentMcpServer>;model?: null | RoutineModelId;prompt: string;user_prompt: string;diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.jsonindex 32e719b553..a1e1bd64f2 100644--- a/packages/sdk/specs/scheduled-action.json+++ b/packages/sdk/specs/scheduled-action.json@@ -762,6 +762,21 @@],"description": "A routine may run on one trigger or any of several schedules and Macro events."},+ "AgentMcpServer": {+ "type": "object",+ "description": "One Pipedream app an agent lists under [`AgentMcpServers::Selected`].\n\nOnly the catalog identity is stored. Whether a given person has connected\nthe app is theirs, resolved at call time by the egress proxy, never here.",+ "required": ["app_slug", "server_name"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "Pipedream app slug, e.g. `linear`."+ },+ "server_name": {+ "type": "string",+ "description": "Display name, e.g. `Linear`."+ }+ }+ },"AgentTask": {"type": "object","required": ["prompt", "user_prompt"],@@ -777,6 +792,13 @@}]},+ "mcp_servers": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/AgentMcpServer"+ },+ "description": "Apps the routine requires on top of the agent's own. The owner must\nhave each one connected to save the routine and for it to run."+ },"model": {"oneOf": [{diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 29150eb0fa..20c58c768b 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -1437,6 +1437,7 @@ async fn run() -> anyhow::Result<()> {draining_sessions.clone(),broker.clone(),session_repo.clone(),+ PgConnectionRepo::new(pool.clone()),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);let coding_agents = coding_agents::router(@@ -1458,6 +1459,7 @@ async fn run() -> anyhow::Result<()> {),draining_sessions.clone(),(*harness).clone(),+ routine_sessions::PipedreamConnectedApps(PgConnectionRepo::new(pool.clone())),),MacroAuthorizationState::new(Arc::new(authorization_service.clone())),);diff --git a/services/agent_harness_service/src/routine_sessions.rs b/services/agent_harness_service/src/routine_sessions.rsindex e6bca0f792..a28e0ce756 100644--- a/services/agent_harness_service/src/routine_sessions.rs+++ b/services/agent_harness_service/src/routine_sessions.rs@@ -5,22 +5,25 @@ use std::sync::Arc;use agent_session::domain::ports::{AgentSessionNotificationRecipient, AgentSessionRepo, BotDirectory, SessionOpener,};-use agent_session::domain::routines::RoutineSessionsService;+use agent_session::domain::routines::{ConnectedApps, RoutineSessionsService};use agent_session::domain::service::AgentSessionService;use agent_session::inbound::routine_sessions::{RoutineSessionsState, routine_sessions_router};use axum::Router;use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};use macro_event_broker::MacroEventBroker;+use macro_user_id::user_id::MacroUserIdStr;+use pipedream_mcp::domain::ports::ConnectionStore;use crate::external_session_requests::BrokerExternalSessionRequests;/// Reuse live harness/session instances and the existing external-request adapter.-pub fn router<Bots, Harness, Sessions, Broker, Repo, Auth>(+pub fn router<Bots, Harness, Sessions, Broker, Repo, Connections, Auth>(bots: Bots,harness: Harness,sessions: Sessions,broker: Broker,repo: Repo,+ connections: Connections,authorization: MacroAuthorizationState<Auth>,) -> Routerwhere@@ -29,6 +32,7 @@ whereSessions: AgentSessionService,Broker: MacroEventBroker,Repo: AgentSessionRepo,+ Connections: ConnectionStore,Auth: MacroAuthorizationService,{let service = RoutineSessionsService::new(@@ -37,6 +41,28 @@ whereBrokerExternalSessionRequests::new(broker, repo),sessions,harness,+ PipedreamConnectedApps(connections),);routine_sessions_router(RoutineSessionsState::new(Arc::new(service), authorization))}++/// A user's Pipedream connections, counted as connected the way the egress+/// proxy counts them: enabled rows only.+pub struct PipedreamConnectedApps<Connections>(pub Connections);++impl<Connections: ConnectionStore> ConnectedApps for PipedreamConnectedApps<Connections> {+ async fn connected_app_slugs(+ &self,+ user: &MacroUserIdStr<'static>,+ ) -> anyhow::Result<Vec<String>> {+ Ok(self+ .0+ .list(user)+ .await+ .map_err(|error| anyhow::anyhow!("could not list Pipedream connections: {error:?}"))?+ .into_iter()+ .filter(|connection| connection.enabled)+ .map(|connection| connection.app_slug)+ .collect())+ }+}