loopengine 0.3.83 → 0.3.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -164,7 +164,7 @@ export declare class WorkflowRunner {
164
164
  task_name?: string;
165
165
  message: string;
166
166
  session_id: string;
167
- }): Promise<RunOutcome>;
167
+ } & Pick<StartRunInput, 'callback_url' | 'decisions_to' | 'chat_notice' | 'warnings'>): Promise<RunOutcome>;
168
168
  /** Waits for the runs this process has started (tests, shutdown). */
169
169
  idle(): Promise<void>;
170
170
  /** How many runs are executing right now (for idle-shutdown checks). */
@@ -163,6 +163,10 @@ export class WorkflowRunner {
163
163
  source: 'schedule',
164
164
  task_id: input.task_id,
165
165
  ...(input.task_name ? { task_name: input.task_name } : {}),
166
+ ...(input.callback_url ? { callback_url: input.callback_url } : {}),
167
+ ...(input.decisions_to ? { decisions_to: input.decisions_to } : {}),
168
+ ...(input.chat_notice ? { chat_notice: input.chat_notice } : {}),
169
+ ...(input.warnings?.length ? { warnings: input.warnings } : {}),
166
170
  status: 'running',
167
171
  started_at: new Date().toISOString(),
168
172
  message: input.message,
@@ -170,8 +174,9 @@ export class WorkflowRunner {
170
174
  };
171
175
  await getRunStore().put(run);
172
176
  await this.prune(input.agent);
177
+ this.changed(run);
173
178
  try {
174
- const outcome = await this.execute(run.agent, run.message, run.session_id, { workflowId: run.workflow_id });
179
+ const outcome = await this.execute(run.agent, run.message, run.session_id, { workflowId: run.workflow_id, ...(run.decisions_to ? { decisionsTo: run.decisions_to } : {}) });
175
180
  if (outcome.kind === 'pending')
176
181
  this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
177
182
  else
@@ -31,6 +31,21 @@ export interface Workflow {
31
31
  model?: WorkflowModel;
32
32
  /** What its result must look like. */
33
33
  output?: string;
34
+ /** Where every run's updates, decisions and start notice go, however
35
+ * it starts. A webhook or API call with its own callback_url overrides
36
+ * the address and decisions for its run. */
37
+ delivery?: WorkflowDelivery;
38
+ }
39
+ export interface WorkflowDelivery {
40
+ /** Gets each run's updates (core/run-callbacks.ts). */
41
+ callback_url?: string;
42
+ /** "callback": approvals and questions go only to callback_url. */
43
+ decisions_to?: 'callback';
44
+ /** Posted to the messaging app when a run starts; {{name}} is filled
45
+ * from the run's inputs. */
46
+ chat_notice?: string;
47
+ /** Post each run's result to the messaging app too. */
48
+ result_to_chat?: boolean;
34
49
  }
35
50
  /** The front matter that makes a skill a workflow: `instructions` (the
36
51
  * new way) replaces the body and drops any start message and label;
@@ -48,9 +63,14 @@ export interface WorkflowFields {
48
63
  /** null (or empty) clears it; left out keeps what's saved. */
49
64
  model?: WorkflowModel | null;
50
65
  output?: string | null;
66
+ delivery?: WorkflowDelivery | null;
51
67
  }
52
68
  export declare class WorkflowParamsError extends Error {
53
69
  }
70
+ /** Sets where a workflow's runs send their updates, decisions, start
71
+ * notice and result (null: the messaging app's defaults); nothing else
72
+ * changes. */
73
+ export declare function setWorkflowDelivery(agentDir: string, id: string, delivery: WorkflowDelivery | null): void;
54
74
  /** Writes a skill file: its front matter (name and description first) and
55
75
  * body. */
56
76
  export declare function writeSkillFile(path: string, frontmatter: Record<string, unknown>, body: string): void;
@@ -27,8 +27,17 @@
27
27
  // workflow's schedules and webhook triggers themselves.
28
28
  //
29
29
  // A workflow's contract can also set, in its front matter: `model` (its
30
- // own provider and model, instead of the agent's) and `output` (what its
31
- // result must look like, said to the agent last). The workspace's shared
30
+ // own provider and model, instead of the agent's), `output` (what its
31
+ // result must look like, said to the agent last) and `delivery` (an app
32
+ // that gets every run's updates, and maybe its approvals and questions
33
+ // instead of the messaging app, and a message posted to the messaging app
34
+ // when a run starts):
35
+ //
36
+ // delivery:
37
+ // callback_url: https://ops.example.com/loopengine
38
+ // decisions: callback
39
+ // chat_notice: New dispute {{dispute_id}}
40
+ // result_to_chat: true The workspace's shared
32
41
  // policies (policies.md in the project) go into every run, after the
33
42
  // instructions.
34
43
  //
@@ -48,13 +57,55 @@ const PARAMETER_NAME = /^[a-z_][a-z0-9_]*$/;
48
57
  const WORKFLOW_KEYS = ['workflow', 'title', 'start_message', 'trigger', 'parameters', 'original_request'];
49
58
  /** The contract's keys: kept when a save doesn't give them. `gather`
50
59
  * (lookups done before the agent, since removed) is dropped. */
51
- const CONTRACT_KEYS = ['model', 'output', 'gather'];
60
+ const CONTRACT_KEYS = ['model', 'output', 'delivery', 'gather'];
52
61
  function modelFrom(value) {
53
62
  if (!value || typeof value !== 'object')
54
63
  return undefined;
55
64
  const m = value;
56
65
  return typeof m.provider === 'string' && m.provider.trim() && typeof m.model === 'string' && m.model.trim() ? { provider: m.provider.trim(), model: m.model.trim() } : undefined;
57
66
  }
67
+ function deliveryFrom(value) {
68
+ if (!value || typeof value !== 'object')
69
+ return undefined;
70
+ const d = value;
71
+ const callbackUrl = typeof d.callback_url === 'string' && d.callback_url.trim() ? d.callback_url.trim() : undefined;
72
+ const notice = typeof d.chat_notice === 'string' && d.chat_notice.trim() ? d.chat_notice.trim() : undefined;
73
+ const delivery = {
74
+ ...(callbackUrl ? { callback_url: callbackUrl } : {}),
75
+ ...(callbackUrl && d.decisions === 'callback' ? { decisions_to: 'callback' } : {}),
76
+ ...(notice ? { chat_notice: notice } : {}),
77
+ ...(d.result_to_chat === true ? { result_to_chat: true } : {}),
78
+ };
79
+ return Object.keys(delivery).length ? delivery : undefined;
80
+ }
81
+ /** A delivery as its front matter, `decisions` named as in the API. */
82
+ function deliveryFrontmatter(delivery) {
83
+ const d = delivery ? deliveryFrom({ ...delivery, decisions: delivery.decisions_to }) : undefined;
84
+ if (!d)
85
+ return undefined;
86
+ return {
87
+ ...(d.callback_url ? { callback_url: d.callback_url } : {}),
88
+ ...(d.decisions_to ? { decisions: d.decisions_to } : {}),
89
+ ...(d.chat_notice ? { chat_notice: d.chat_notice } : {}),
90
+ ...(d.result_to_chat ? { result_to_chat: true } : {}),
91
+ };
92
+ }
93
+ /** Sets where a workflow's runs send their updates, decisions, start
94
+ * notice and result (null: the messaging app's defaults); nothing else
95
+ * changes. */
96
+ export function setWorkflowDelivery(agentDir, id, delivery) {
97
+ const path = skillPath(agentDir, id);
98
+ const skill = readSkillFile(path, id);
99
+ if (!skill || !workflowFrom(id, skill.frontmatter, skill.body))
100
+ throw new Error(`No workflow ${id}.`);
101
+ const frontmatter = { ...skill.frontmatter };
102
+ const saved = deliveryFrontmatter(delivery);
103
+ if (saved)
104
+ frontmatter.delivery = saved;
105
+ else
106
+ delete frontmatter.delivery;
107
+ writeSkillFile(path, frontmatter, skill.body);
108
+ }
58
109
  function skillsDir(agentDir) {
59
110
  return join(agentDir, 'skills');
60
111
  }
@@ -123,6 +174,7 @@ function workflowFrom(id, frontmatter, body) {
123
174
  instructions: combineInstructions(startMessage, body),
124
175
  ...(modelFrom(frontmatter.model) ? { model: modelFrom(frontmatter.model) } : {}),
125
176
  ...(typeof frontmatter.output === 'string' && frontmatter.output.trim() ? { output: frontmatter.output.trim() } : {}),
177
+ ...(deliveryFrom(frontmatter.delivery) ? { delivery: deliveryFrom(frontmatter.delivery) } : {}),
126
178
  };
127
179
  }
128
180
  /** The agent's workflows: its skills that have a start message. */
@@ -174,6 +226,13 @@ export function setWorkflowFields(agentDir, id, fields) {
174
226
  else
175
227
  delete frontmatter.output;
176
228
  }
229
+ if (fields.delivery !== undefined) {
230
+ const saved = deliveryFrontmatter(fields.delivery);
231
+ if (saved)
232
+ frontmatter.delivery = saved;
233
+ else
234
+ delete frontmatter.delivery;
235
+ }
177
236
  // Lookups done before the agent (removed): a save drops the old key.
178
237
  delete frontmatter.gather;
179
238
  if (fields.description)
package/dist/index.d.ts CHANGED
@@ -86,14 +86,14 @@ export { templatesPageHtml } from './web/templates-page.js';
86
86
  export { TemplateError, createFromTemplate, createFromTemplateObject, describeTemplateSchedule, listTemplates, previewTemplate, templateChecklist, type CreatedTemplateAgent, type LegacyTemplateCreateDeps, type TemplateChecklistItem, type TemplateCreateDeps, type TemplatePreview, type TemplateSummary, } from './web/templates-admin.js';
87
87
  export { STARTER_TEMPLATES, starterTemplate, templateScheduleStart, type StarterTemplate, type TemplateRule, type TemplateSchedule, type TemplateSetup, type TemplateSkill, } from './core/system-agents/templates.js';
88
88
  export { workflowPageHtml } from './web/workflow-page.js';
89
- export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, createWorkflow, forgetWorkflow, forgetAgent, type ForgottenAgent, migrateAgentWorkflows, getPlanJob, listAgentWorkflows, noteForExistingAgent, planWorkflow, resolveConnections, prepareWorkflowRun, updateWorkflow, startPlanJob, type AgentWorkflowView, type CreatedWorkflow, type PlanJob, type PlannedWorkflow, type WorkflowAgentInfo, type WorkflowAppStatus, type WorkflowCheck, type WorkflowPlanDeps, type WorkflowRequirement, type WorkflowConflict, type WorkflowCreateDeps, type WorkflowMcpDeps, type WorkflowMcpCreateDeps, resolveMcpServers, prepareMcpAbilities, } from './web/workflow-admin.js';
89
+ export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, createWorkflow, forgetWorkflow, forgetAgent, type ForgottenAgent, migrateAgentWorkflows, getPlanJob, listAgentWorkflows, noteForExistingAgent, planWorkflow, resolveConnections, prepareWorkflowRun, updateWorkflow, updateWorkflowMessages, startPlanJob, type AgentWorkflowView, type CreatedWorkflow, type PlanJob, type PlannedWorkflow, type WorkflowAgentInfo, type WorkflowAppStatus, type WorkflowCheck, type WorkflowPlanDeps, type WorkflowRequirement, type WorkflowConflict, type WorkflowCreateDeps, type WorkflowMcpDeps, type WorkflowMcpCreateDeps, resolveMcpServers, prepareMcpAbilities, } from './web/workflow-admin.js';
90
90
  export { WORKFLOW_PLANNER_PROMPT, planParameters, planWorkflowWithModel, validateWorkflowPlan, workflowTemplate, type WorkflowPlan, type WorkflowPlannerTools, type WorkflowStep } from './core/system-agents/workflow-planner.js';
91
91
  export { WORKFLOW_EXAMPLES, workflowExample, type WorkflowExample } from './core/system-agents/workflow-examples.js';
92
92
  export { WORKFLOW_EXAMPLE_MESSAGES, type WorkflowExampleMessage } from './core/system-agents/workflow-example-messages.js';
93
93
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError, type WorkflowTrigger, type PublicTrigger, type TriggerSettings, type TriggerVerify, type TriggerFilter, type TriggerSender, type SignatureAlgorithm, type TriggerDelivery, type TriggerOutcome, type TriggerStore } from './core/workflow-triggers.js';
94
94
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type CallbackPending, type RunCallbackEvent } from './core/run-callbacks.js';
95
95
  export { WorkflowRunner, FileRunStore, getRunStore, setRunStore, listRuns, getRun, isUnderWay, RunError, type WorkflowRun, type WorkflowRunStatus, type RunStore, type ExecuteRun, type RunOutcome, type StartRunInput } from './core/workflow-runs.js';
96
- export { readWorkflows, readWorkflow, setWorkflowFields, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type RunMessageExtras } from './core/workflows.js';
96
+ export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies, type Workflow, type WorkflowFields, type WorkflowParameter, type WorkflowModel, type WorkflowDelivery, type RunMessageExtras } from './core/workflows.js';
97
97
  export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, judgeEvalResult, startEvalRound, EVAL_JUDGE_PROMPT, type WorkflowScores, type EvalCase, type EvalCaseResult, type EvalRound, type WorkflowEvals, type EvalRunDeps } from './web/workflow-evidence.js';
98
98
  export { globalConfigPageHtml } from './web/global-config-page.js';
99
99
  export { playgroundHtml } from './web/playground.js';
package/dist/index.js CHANGED
@@ -79,14 +79,14 @@ export { templatesPageHtml } from './web/templates-page.js';
79
79
  export { TemplateError, createFromTemplate, createFromTemplateObject, describeTemplateSchedule, listTemplates, previewTemplate, templateChecklist, } from './web/templates-admin.js';
80
80
  export { STARTER_TEMPLATES, starterTemplate, templateScheduleStart, } from './core/system-agents/templates.js';
81
81
  export { workflowPageHtml } from './web/workflow-page.js';
82
- export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, createWorkflow, forgetWorkflow, forgetAgent, migrateAgentWorkflows, getPlanJob, listAgentWorkflows, noteForExistingAgent, planWorkflow, resolveConnections, prepareWorkflowRun, updateWorkflow, startPlanJob, resolveMcpServers, prepareMcpAbilities, } from './web/workflow-admin.js';
82
+ export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, createWorkflow, forgetWorkflow, forgetAgent, migrateAgentWorkflows, getPlanJob, listAgentWorkflows, noteForExistingAgent, planWorkflow, resolveConnections, prepareWorkflowRun, updateWorkflow, updateWorkflowMessages, startPlanJob, resolveMcpServers, prepareMcpAbilities, } from './web/workflow-admin.js';
83
83
  export { WORKFLOW_PLANNER_PROMPT, planParameters, planWorkflowWithModel, validateWorkflowPlan, workflowTemplate } from './core/system-agents/workflow-planner.js';
84
84
  export { WORKFLOW_EXAMPLES, workflowExample } from './core/system-agents/workflow-examples.js';
85
85
  export { WORKFLOW_EXAMPLE_MESSAGES } from './core/system-agents/workflow-example-messages.js';
86
86
  export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, checkRunDelivery, fillChatNotice, resultToChat, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
87
87
  export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError } from './core/run-callbacks.js';
88
88
  export { WorkflowRunner, FileRunStore, getRunStore, setRunStore, listRuns, getRun, isUnderWay, RunError } from './core/workflow-runs.js';
89
- export { readWorkflows, readWorkflow, setWorkflowFields, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
89
+ export { readWorkflows, readWorkflow, setWorkflowFields, setWorkflowDelivery, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
90
90
  export { EvidenceError, workflowScores, runFeedbackFrom, readEvals, addEvalCase, updateEvalCase, removeEvalCase, judgeEvalResult, startEvalRound, EVAL_JUDGE_PROMPT } from './web/workflow-evidence.js';
91
91
  export { globalConfigPageHtml } from './web/global-config-page.js';
92
92
  export { playgroundHtml } from './web/playground.js';
@@ -119,6 +119,15 @@ export const agentsConfigPageHtml = `<!doctype html>
119
119
  .wf-tab { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 8px 10px; margin-bottom: -1px; font-size: 13px; font-weight: 600; color: var(--ink-muted); }
120
120
  .wf-tab:hover:not(:disabled) { background: none; color: var(--ink); }
121
121
  .wf-tab[aria-selected="true"] { color: var(--accent-ink); border-bottom-color: var(--accent); }
122
+ .wf-msg-form { display: flex; flex-direction: column; gap: 14px; max-width: 760px; }
123
+ .wf-msg-row { display: grid; grid-template-columns: 190px 1fr; gap: 12px; align-items: start; }
124
+ .wf-msg-k { font-weight: 600; font-size: 13px; padding-top: 7px; }
125
+ .wf-msg-v { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
126
+ .wf-msg-check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; }
127
+ .wf-msg-check input { width: auto; margin: 0; }
128
+ .wf-msg-own { display: flex; flex-direction: column; gap: 6px; padding: 10px 12px; border-radius: 8px; background: var(--surface-2); }
129
+ .wf-msg-foot { display: flex; justify-content: flex-end; align-items: center; gap: 12px; }
130
+ @media (max-width: 640px) { .wf-msg-row { grid-template-columns: 1fr; gap: 4px; } .wf-msg-k { padding-top: 0; } }
122
131
  .wf-tab-count { margin-left: 4px; font-size: 11px; padding: 0 6px; border-radius: 999px; background: var(--surface-2); color: var(--ink-muted); }
123
132
  .wf-row .workflow-steps-text { margin: 0; padding: 12px 14px; border-radius: 8px; background: var(--surface); font-size: 13px; line-height: 1.6; max-height: 420px; overflow: auto; white-space: pre-wrap; }
124
133
  .wf-original { margin-top: 10px; }
@@ -998,7 +1007,6 @@ ${consoleShellScript}
998
1007
  return '<div class="wf-run-bar">' +
999
1008
  (paramsHtml ? '<div class="workflow-params">' + paramsHtml + '</div>' : '') +
1000
1009
  '<div class="wf-run-bar-controls">' +
1001
- '<label class="workflow-run-notify" title="Sends the completed result through this agent' + String.fromCharCode(8217) + 's configured notifier"><input type="checkbox" class="workflow-run-notify-toggle"> Send result to messaging app</label>' +
1002
1010
  '<button type="button" class="workflow-run primary">Run now</button></div>' +
1003
1011
  '</div>';
1004
1012
  }
@@ -1013,7 +1021,7 @@ ${consoleShellScript}
1013
1021
  return '<div class="wf-api">' +
1014
1022
  '<pre>POST ' + escapeHtml(apiUrl) + String.fromCharCode(10) + escapeHtml(example) + '</pre>' +
1015
1023
  '<p class="hint" style="margin:0">' + (paramNames.length ? '<code>params</code>: ' + paramNames.map(function (p) { return '<code>' + escapeHtml(p) + '</code>' + (w.parameters[p].required ? ' (required)' : '') + (w.parameters[p].description ? ', ' + escapeHtml(w.parameters[p].description) : ''); }).join('; ') + '. ' : 'It takes no params. ') +
1016
- 'Optional: <code>"wait": true</code> answers with the result once the run finishes; <code>"result_to_chat": true</code> sends the result to the messaging app; <code>"callback_url"</code> tells your app when the run stops for a decision, finishes or fails. Add <code>"decisions": "callback"</code> to send the run' + String.fromCharCode(8217) + 's approvals and questions to that address instead of the messaging app, and <code>"chat_notice"</code> to post a message to the messaging app when it starts (<code>{{input}}</code> is filled in). Without <code>wait</code>, you get the run' + String.fromCharCode(8217) + 's id back at once.</p>' +
1024
+ 'Optional: <code>"wait": true</code> answers with the result once the run finishes; <code>"result_to_chat": true</code> sends the result to the messaging app; <code>"callback_url"</code> tells your app when the run stops for a decision, finishes or fails. Add <code>"decisions": "callback"</code> to send the run' + String.fromCharCode(8217) + 's approvals and questions to that address instead of the messaging app, and <code>"chat_notice"</code> to post a message to the messaging app when it starts (<code>{{input}}</code> is filled in). These override the workflow' + String.fromCharCode(8217) + 's Messages tab for that run. Without <code>wait</code>, you get the run' + String.fromCharCode(8217) + 's id back at once.</p>' +
1017
1025
  '</div>';
1018
1026
  }
1019
1027
 
@@ -1123,6 +1131,59 @@ ${consoleShellScript}
1123
1131
  function contractLinesHtml(lines) {
1124
1132
  return lines.map(function (l) { return '<div class="wf-cb-line">' + l + '</div>'; }).join('');
1125
1133
  }
1134
+ // Where a workflow's approvals and questions go, as a phrase: its app
1135
+ // (the contract's address), or the agent's messaging app.
1136
+ function workflowDecisionsTo(w) {
1137
+ if (w.delivery && w.delivery.decisions_to === 'callback') return 'your app (' + escapeHtml(w.delivery.callback_url) + ')';
1138
+ return 'the agent' + String.fromCharCode(8217) + 's messaging app';
1139
+ }
1140
+
1141
+ // Where the agent's approvals go by name ("Telegram", "Webhook"), or
1142
+ // null with none.
1143
+ function workflowChatName() {
1144
+ return workflowsMeta.messaging ? (APP_NAMES[workflowsMeta.messaging] || workflowsMeta.messaging) : null;
1145
+ }
1146
+ // Its chat app by name, for messages people read (Slack, Telegram or
1147
+ // Lark), or null.
1148
+ function workflowChatAppName() {
1149
+ return ['slack', 'telegram', 'lark'].indexOf(workflowsMeta.messaging) !== -1 ? workflowChatName() : null;
1150
+ }
1151
+
1152
+ // Its Messages tab: where every run's updates go, however it starts:
1153
+ // your app's address, a chat message when it starts, where approvals
1154
+ // and questions go, and whether the result is posted to chat.
1155
+ function workflowMessagesHtml(w, agentName) {
1156
+ var d = w.delivery || {};
1157
+ var chat = workflowChatAppName();
1158
+ var chatLabel = escapeHtml(chat || 'chat');
1159
+ var decisionsLabel = escapeHtml(workflowChatName() || 'the messaging app');
1160
+ var noChat = chat ? '' : ' disabled';
1161
+ var RSQ = String.fromCharCode(8217);
1162
+ var row = function (label, body) { return '<div class="wf-msg-row"><div class="wf-msg-k">' + label + '</div><div class="wf-msg-v">' + body + '</div></div>'; };
1163
+ // Webhooks saved with settings of their own: their runs use those.
1164
+ var own = (w.triggers || []).filter(function (t) { return t.callback || t.decisions_to || t.chat_notice || t.result_to_chat; });
1165
+ return '<form class="wf-msg-form">' +
1166
+ '<p class="hint" style="margin:0 0 12px">For every run, whether it' + RSQ + 's started by Run now, a schedule, a webhook or the API.' +
1167
+ (chat ? '' : ' This agent has no chat app (Slack, Telegram or Lark): <a href="?agent=' + encodeURIComponent(agentName) + '&amp;tab=messaging">set one up in Messaging</a> to post to chat.') + '</p>' +
1168
+ row('Your app', '<input name="msgUrl" inputmode="url" placeholder="https://example.com/hooks/loopengine" value="' + escapeHtml(d.callback_url || '') + '">' +
1169
+ '<span class="hint">Optional. Gets every run' + RSQ + 's updates as signed JSON: when it stops for a decision, finishes or fails.</span>') +
1170
+ row('When a run starts', '<label class="wf-msg-check"><input type="checkbox" name="msgNoticeOn"' + (d.chat_notice ? ' checked' : noChat) + '> Post to ' + chatLabel + '</label>' +
1171
+ '<input name="msgNotice" maxlength="1000" placeholder="New dispute {{dispute_id}}" value="' + escapeHtml(d.chat_notice || '') + '"' + (d.chat_notice ? '' : ' disabled') + '>' +
1172
+ '<span class="hint">{{name}} puts in an input' + RSQ + 's value.</span>') +
1173
+ row('Approvals and questions', '<label class="wf-msg-check"><input type="radio" name="msgDecisions" value="chat"' + (d.decisions_to === 'callback' ? '' : ' checked') + '> ' + decisionsLabel + '</label>' +
1174
+ '<label class="wf-msg-check"><input type="radio" name="msgDecisions" value="callback"' + (d.decisions_to === 'callback' ? ' checked' : '') + (d.callback_url ? '' : ' disabled') + '> Your app <span class="hint">(it shows them and answers through the API; needs the address above)</span></label>') +
1175
+ row('When a run finishes', '<label class="wf-msg-check"><input type="checkbox" name="msgResult"' + (d.result_to_chat ? ' checked' : noChat) + '> Post the result to ' + chatLabel + '</label>' +
1176
+ '<span class="hint">Your app gets it too, when an address is set.</span>') +
1177
+ (own.length
1178
+ ? '<div class="wf-msg-own">' + own.map(function (t) {
1179
+ return '<p class="hint" style="margin:0">The ' + escapeHtml(t.name) + ' webhook has settings of its own, so its runs use those instead. ' +
1180
+ '<button type="button" class="wf-msg-clear-hook" data-trigger="' + escapeHtml(t.trigger_id) + '">Use these instead</button></p>';
1181
+ }).join('') + '</div>'
1182
+ : '') +
1183
+ '<div class="wf-msg-foot"><span class="hint wf-msg-result" role="status"></span><button type="submit" class="primary">Save</button></div>' +
1184
+ '</form>';
1185
+ }
1186
+
1126
1187
  // Its Triggers tab: the four ways a run starts, each in its own box
1127
1188
  // with what it is: Run now, a schedule, a webhook, the API.
1128
1189
  function workflowTriggersHtml(w, name, params) {
@@ -1133,7 +1194,7 @@ ${consoleShellScript}
1133
1194
  };
1134
1195
  return '<div class="wf-ways">' +
1135
1196
  way('run', 'Run now', 'Starts a run right away, from here. It shows under Evidence as it goes.', workflowRunBarHtml(w, params)) +
1136
- way('schedule', 'Schedule', 'Runs it on a timer, like every day at 9:00. Approvals and questions go to the agent' + RSQ + 's messaging app.',
1197
+ way('schedule', 'Schedule', 'Runs it on a timer, like every day at 9:00. Approvals and questions go to ' + workflowDecisionsTo(w) + '.',
1137
1198
  (schedules || '<p class="hint" style="margin:0">None yet.</p>') +
1138
1199
  '<div><button type="button" class="workflow-add-schedule">+ Schedule</button></div>') +
1139
1200
  way('webhook', 'Webhook', 'Another app (Stripe, GitHub, Shopify or your own) calls a private address when something happens, and each call starts a run.',
@@ -1174,14 +1235,15 @@ ${consoleShellScript}
1174
1235
  var result = [];
1175
1236
  if (w.output) result.push(escapeHtml(w.output));
1176
1237
  result.push('returned to whoever starts it <span class="hint">(Run now, or the app' + RSQ + 's API call)</span>');
1177
- var notified = (w.schedules || []).some(function (x) { return x.notify && x.status !== 'cancelled'; }) || (w.triggers || []).some(function (t) { return t.result_to_chat; });
1178
- if (notified) result.push(escapeHtml(workflowsMeta.messaging ? (APP_NAMES[workflowsMeta.messaging] || workflowsMeta.messaging) : 'messaging app') + ' report <span class="hint">(for the schedules and webhooks set to send it)</span>');
1238
+ var notified = (w.delivery && w.delivery.result_to_chat) || (w.schedules || []).some(function (x) { return x.notify && x.status !== 'cancelled'; }) || (w.triggers || []).some(function (t) { return t.result_to_chat; });
1239
+ if (notified) result.push(escapeHtml(workflowsMeta.messaging ? (APP_NAMES[workflowsMeta.messaging] || workflowsMeta.messaging) : 'messaging app') + ' report' + (w.delivery && w.delivery.result_to_chat ? '' : ' <span class="hint">(for the schedules and webhooks set to send it)</span>'));
1179
1240
  if ((w.triggers || []).some(function (t) { return t.callback; })) result.push('posted to the webhook' + RSQ + 's update address');
1180
- if ((w.triggers || []).some(function (t) { return t.decisions_to === 'callback'; })) result.push('approvals and questions go to the webhook' + RSQ + 's update address <span class="hint">(not the messaging app)</span>');
1241
+ if (w.delivery && w.delivery.callback_url) result.push('run updates posted to ' + escapeHtml(w.delivery.callback_url));
1242
+ var decisions = [(w.delivery && w.delivery.decisions_to === 'callback' ? 'your app' : escapeHtml(workflowChatName() || 'the agent' + RSQ + 's messaging app')) + ' <span class="hint">(see Messages)</span>'];
1181
1243
  var model = w.model ? escapeHtml(w.model.provider + ' ' + w.model.model) : escapeHtml(workflowsMeta.agentModel || 'the agent' + RSQ + 's') + ' <span class="hint">(the agent' + RSQ + 's model)</span>';
1182
1244
  var row = function (k, lines) { return '<div class="wf-cb-k">' + k + '</div><div class="wf-cb-v">' + contractLinesHtml(lines) + '</div>'; };
1183
- return '<div class="wf-cb">' + row('trigger', trigger) + row('inputs', inputs) + row('tools', tools) + row('result', result) + row('model', [model]) + '</div>' +
1184
- '<p class="hint" style="margin:0">Change the inputs, result and model with Edit, and what tools may do in Permissions.</p>';
1245
+ return '<div class="wf-cb">' + row('trigger', trigger) + row('inputs', inputs) + row('tools', tools) + row('result', result) + row('approvals', decisions) + row('model', [model]) + '</div>' +
1246
+ '<p class="hint" style="margin:0">Change the inputs, result and model with Edit, where updates and approvals go in Messages, and what tools may do in Permissions.</p>';
1185
1247
  }
1186
1248
 
1187
1249
  function workflowBriefHtml(w) {
@@ -1296,9 +1358,10 @@ ${consoleShellScript}
1296
1358
  '<div class="wf-row-body"' + (open ? '' : ' hidden') + '>' +
1297
1359
  // What it does, in full, once it's open (the row shows just its name).
1298
1360
  (w.description && w.description !== w.title ? '<p class="wf-desc">' + escapeHtml(w.description) + '</p>' : '') +
1299
- '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Brief') + tabBtn('contract', 'Contract') + tabBtn('triggers', 'Triggers') + tabBtn('evidence', 'Evidence' + (runs ? ' <span class="wf-tab-count">' + w.recentRuns.length + '</span>' : '')) + '</div>' +
1361
+ '<div class="wf-tabs" role="tablist">' + tabBtn('brief', 'Brief') + tabBtn('contract', 'Contract') + tabBtn('triggers', 'Triggers') + tabBtn('messages', 'Messages') + tabBtn('evidence', 'Evidence' + (runs ? ' <span class="wf-tab-count">' + w.recentRuns.length + '</span>' : '')) + '</div>' +
1300
1362
  panel('contract', workflowContractHtml(w, name, params)) +
1301
1363
  panel('triggers', workflowTriggersHtml(w, name, params)) +
1364
+ panel('messages', workflowMessagesHtml(w, name)) +
1302
1365
  panel('brief', workflowBriefHtml(w)) +
1303
1366
  panel('evidence', workflowEvidenceHtml(w, runs)) +
1304
1367
  '<div class="hint workflow-result"></div>' +
@@ -1665,14 +1728,7 @@ ${consoleShellScript}
1665
1728
  field('Or give the whole payload to', '<select name="payload_param"><option value="">(none)</option>' + params.map(function (p) { return '<option>' + escapeHtml(p) + '</option>'; }).join('') + '</select>', '')
1666
1729
  : '<p class="hd-hint">This workflow takes no inputs, so what the app sends isn' + RSQ + 't passed on. Add one with Edit to use it.</p>') +
1667
1730
  '</section>' +
1668
- '<section class="hd-section"><h4>Messaging app</h4>' +
1669
- field('Message the chat when it starts <span class="hd-optional">(optional)</span>', '<input name="chat_notice" maxlength="1000" placeholder="New dispute: {{data.object.amount}} {{data.object.currency}}, {{data.object.reason}}">', 'Posted when each run starts. <code>{{data.object.id}}</code> is filled from what the app sends.') +
1670
- '<label class="hd-check"><input type="checkbox" name="result_to_chat"><span><strong>Send the result to the messaging app</strong><span class="hd-hint">Through the agent' + RSQ + 's Messaging tab: Slack, Telegram, Lark or another you set up.</span></span></label>' +
1671
- '</section>' +
1672
- '<section class="hd-section"><h4>Your app</h4>' +
1673
- field('Send run updates to <span class="hd-optional">(optional)</span>', '<input name="callback_url" placeholder="https://example.com/hooks/loopengine" inputmode="url">', 'An https address in your own app. It' + RSQ + 's told when each run stops for a decision, finishes or fails.') +
1674
- '<label class="hd-check"><input type="checkbox" name="decisions_callback" disabled><span><strong>Send approvals and questions here instead of the messaging app</strong><span class="hd-hint">Your app shows them and answers through the API. Needs the address above.</span></span></label>' +
1675
- '</section>' +
1731
+ '<p class="hd-hint">Where its runs' + RSQ + ' updates, approvals and questions go is set once for the workflow, in its Messages tab.</p>' +
1676
1732
  '</div>' +
1677
1733
  '<footer class="hd-foot"><span class="hook-form-result" role="status"></span>' +
1678
1734
  '<div class="hd-actions"><button type="button" class="hook-dialog-cancel">Cancel</button><button type="submit" class="primary">' + (t ? 'Save' : 'Create webhook') + '</button></div></footer>' +
@@ -1698,10 +1754,6 @@ ${consoleShellScript}
1698
1754
  form.name.value = t.name || '';
1699
1755
  Object.keys(t.mapping || {}).forEach(function (p) { var input = form.querySelector('input[name="map:' + p + '"]'); if (input) input.value = t.mapping[p]; });
1700
1756
  if (form.payload_param && t.payload_param) form.payload_param.value = t.payload_param;
1701
- form.chat_notice.value = t.chat_notice || '';
1702
- form.result_to_chat.checked = Boolean(t.result_to_chat || t.notify);
1703
- form.callback_url.value = t.callback_url || '';
1704
- form.decisions_callback.checked = t.decisions_to === 'callback';
1705
1757
  }
1706
1758
 
1707
1759
  // existing: a webhook to change instead of making one; onDone then gets
@@ -1732,15 +1784,7 @@ ${consoleShellScript}
1732
1784
  }
1733
1785
  form.sender.addEventListener('change', senderChanged);
1734
1786
  form.filter_values.addEventListener('input', function () { form.name.placeholder = defaultName(); });
1735
- // Decisions can only go to an address that's given.
1736
- function callbackChanged() {
1737
- form.decisions_callback.disabled = !form.callback_url.value.trim();
1738
- if (form.decisions_callback.disabled) form.decisions_callback.checked = false;
1739
- }
1740
- form.callback_url.addEventListener('input', callbackChanged);
1741
1787
  if (existing) fillHookForm(form, existing);
1742
- callbackChanged();
1743
- if (existing) form.decisions_callback.checked = existing.decisions_to === 'callback' && !form.decisions_callback.disabled;
1744
1788
  senderChanged();
1745
1789
  form.addEventListener('submit', function (ev) {
1746
1790
  ev.preventDefault();
@@ -1765,15 +1809,11 @@ ${consoleShellScript}
1765
1809
  for (var j = 0; j < inputs.length; j++) if (inputs[j].value.trim()) mapping[inputs[j].name.slice(4)] = inputs[j].value.trim();
1766
1810
  if (Object.keys(mapping).length) body.mapping = mapping;
1767
1811
  if (form.payload_param && form.payload_param.value) body.payload_param = form.payload_param.value;
1768
- if (form.result_to_chat.checked) body.result_to_chat = true;
1769
- if (form.callback_url.value.trim()) body.callback_url = form.callback_url.value.trim();
1770
- if (body.callback_url && form.decisions_callback.checked) body.decisions = 'callback';
1771
- if (form.chat_notice.value.trim()) body.chat_notice = form.chat_notice.value.trim();
1772
- // A change says what's cleared too; a setting left out is kept.
1812
+ // A change says what's cleared too; a setting left out is kept (its
1813
+ // own message settings, from before: the Messages tab clears them).
1773
1814
  if (existing) {
1774
- ['verify', 'filter', 'mapping', 'callback_url', 'decisions', 'chat_notice'].forEach(function (k) { if (!(k in body)) body[k] = null; });
1815
+ ['verify', 'filter', 'mapping'].forEach(function (k) { if (!(k in body)) body[k] = null; });
1775
1816
  if (!('payload_param' in body)) body.payload_param = '';
1776
- if (!body.result_to_chat) body.result_to_chat = false;
1777
1817
  }
1778
1818
  var failed = existing ? 'Could not save it' : 'Could not make it';
1779
1819
  result.textContent = (existing ? 'Saving' : 'Making it') + String.fromCharCode(8230);
@@ -1910,6 +1950,49 @@ ${consoleShellScript}
1910
1950
  if (!card.classList.contains('is-open')) setWorkflowOpen(card, true);
1911
1951
  showWorkflowTab(card, 'triggers');
1912
1952
  });
1953
+ // Messages: where every run's updates and decisions go.
1954
+ var msgForm = card.querySelector('.wf-msg-form');
1955
+ if (msgForm) {
1956
+ var msgResult = msgForm.querySelector('.wf-msg-result');
1957
+ var appRadio = msgForm.querySelector('input[name="msgDecisions"][value="callback"]');
1958
+ // Decisions can only go to an address that's given.
1959
+ msgForm.msgUrl.addEventListener('input', function () {
1960
+ appRadio.disabled = !msgForm.msgUrl.value.trim();
1961
+ if (appRadio.disabled && appRadio.checked) msgForm.querySelector('input[name="msgDecisions"][value="chat"]').checked = true;
1962
+ });
1963
+ msgForm.msgNoticeOn.addEventListener('change', function () {
1964
+ msgForm.msgNotice.disabled = !msgForm.msgNoticeOn.checked;
1965
+ if (msgForm.msgNoticeOn.checked) msgForm.msgNotice.focus();
1966
+ });
1967
+ var reloadOnMessages = function () { workflowTabs[id] = 'messages'; loadWorkflowsSection(name); };
1968
+ msgForm.addEventListener('submit', function (ev) {
1969
+ ev.preventDefault();
1970
+ var url = msgForm.msgUrl.value.trim();
1971
+ var body = {};
1972
+ if (url) body.callback_url = url;
1973
+ if (url && appRadio.checked) body.decisions = 'callback';
1974
+ if (msgForm.msgNoticeOn.checked && msgForm.msgNotice.value.trim()) body.chat_notice = msgForm.msgNotice.value.trim();
1975
+ if (msgForm.msgResult.checked) body.result_to_chat = true;
1976
+ msgResult.textContent = 'Saving' + String.fromCharCode(8230);
1977
+ fetchJsonRetryOnce(base + '/messages', { method: 'PUT', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }).then(function (r) {
1978
+ if (!r.ok) { msgResult.textContent = r.body.error || 'Could not save'; return; }
1979
+ reloadOnMessages();
1980
+ });
1981
+ });
1982
+ var clearButtons = msgForm.querySelectorAll('.wf-msg-clear-hook');
1983
+ for (var cb = 0; cb < clearButtons.length; cb++) {
1984
+ clearButtons[cb].addEventListener('click', function (ev) {
1985
+ var tid = ev.currentTarget.dataset.trigger;
1986
+ fetchJsonRetryOnce(base + '/triggers/' + encodeURIComponent(tid), {
1987
+ method: 'PUT', headers: { 'content-type': 'application/json' },
1988
+ body: JSON.stringify({ callback_url: null, decisions: null, chat_notice: null, result_to_chat: false }),
1989
+ }).then(function (r) {
1990
+ if (!r.ok) { msgResult.textContent = r.body.error || 'Could not change the webhook'; return; }
1991
+ reloadOnMessages();
1992
+ });
1993
+ });
1994
+ }
1995
+ }
1913
1996
  // Evidence: save a run as an eval case, change or remove a case, run them.
1914
1997
  card.querySelector('.wf-row-body').addEventListener('click', function (ev) {
1915
1998
  var btn = ev.target.closest('.wf-save-case, .wf-case-remove, .wf-case-save, .wf-evals-run');
@@ -1981,16 +2064,14 @@ ${consoleShellScript}
1981
2064
  if (!value && inputs[i].required) { result.textContent = 'Fill in ' + inputs[i].name + ' first.'; inputs[i].focus(); return; }
1982
2065
  if (value) params[inputs[i].name] = value;
1983
2066
  }
1984
- var notifyToggle = card.querySelector('.workflow-run-notify-toggle');
1985
- var notifyResult = notifyToggle.checked;
1986
- notifyToggle.disabled = true;
1987
2067
  btn.disabled = true;
1988
2068
  result.textContent = 'Starting' + String.fromCharCode(8230);
1989
- fetchJsonRetryOnce(base + '/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ params: params, source: 'console', result_to_chat: notifyResult }) }).then(function (r) {
2069
+ fetchJsonRetryOnce(base + '/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ params: params, source: 'console' }) }).then(function (r) {
1990
2070
  btn.disabled = false;
1991
- notifyToggle.disabled = false;
1992
2071
  if (!r.ok) { result.textContent = r.body.error || 'Could not start it.'; return; }
1993
- result.textContent = 'Started. Questions and approvals go to this agent' + String.fromCharCode(8217) + 's messaging app; the result shows under History.' + (notifyResult ? ' The result will also be sent to the messaging app when it finishes.' : '');
2072
+ var started = workflowsById[id];
2073
+ result.innerHTML = 'Started. Questions and approvals go to ' + workflowDecisionsTo(started || {}) + '; the result shows under Evidence.' + (started && started.delivery && started.delivery.result_to_chat ? ' The result will also be posted to the messaging app when it finishes.' : '') +
2074
+ (r.body.warnings ? ' ' + escapeHtml(r.body.warnings.join(' ')) : '');
1994
2075
  setTimeout(function () { loadWorkflowsSection(name); }, 800);
1995
2076
  });
1996
2077
  });
@@ -3334,7 +3415,9 @@ ${consoleShellScript}
3334
3415
  : t.workflow_missing
3335
3416
  ? '<div><span class="le-pill bad">Workflow removed</span> <span class="hint">' + escapeHtml(t.workflow_id) + '</span></div>'
3336
3417
  : '<div class="schedule-result hint">' + escapeHtml(t.message) + '</div>') +
3337
- (t.status !== 'cancelled' && t.status !== 'done'
3418
+ // A workflow's schedule follows its Messages tab; one ticked from
3419
+ // before can still be turned off here.
3420
+ (t.status !== 'cancelled' && t.status !== 'done' && (!t.workflow_id || t.notify)
3338
3421
  ? '<label class="schedule-notify hint" title="Sent through its Messaging tab: Slack, email, Lark or a webhook"><input type="checkbox" class="schedule-notify-toggle" data-id="' + escapeHtml(t.task_id) + '"' + (t.notify ? ' checked' : '') + '> Send result to messaging app</label>'
3339
3422
  : (t.notify ? '<div><span class="workflow-option-value">Send result to messaging app</span></div>' : '')) + '</td>' +
3340
3423
  '<td>' + scheduleText(t.schedule) + (t.next_run_at ? '<div class="hint">next ' + escapeHtml(fmtScheduleTime(t.next_run_at)) + '</div>' : '') + '</td>' +
@@ -3378,7 +3461,7 @@ ${consoleShellScript}
3378
3461
  '<input type="datetime-local" name="runAt" aria-label="Date and time"></div>' +
3379
3462
  '</div>' +
3380
3463
  '<label>Name <span class="hint">(optional)</span><input name="task_name" placeholder="Daily ticket summary"></label>' +
3381
- '<label class="http-tool-inline-label"><input type="checkbox" name="notify"> Send result to messaging app <span class="hint">(through its Messaging tab: Slack, email, Lark or a webhook)</span></label>' +
3464
+ '<label class="http-tool-inline-label" id="scheduleNotifyField"' + (schedulesWorkflows.length ? ' hidden' : '') + '><input type="checkbox" name="notify"> Send result to messaging app <span class="hint">(through its Messaging tab: Slack, email, Lark or a webhook)</span></label>' +
3382
3465
  '<div style="display:flex;gap:8px"><button type="submit">Schedule</button></div>' +
3383
3466
  '<div id="scheduleResult" class="hint"></div>' +
3384
3467
  '</form></section>';
@@ -3480,6 +3563,9 @@ ${consoleShellScript}
3480
3563
  var byMessage = form.querySelector('input[name="runs"]:checked').value === 'message';
3481
3564
  messageField.hidden = !byMessage;
3482
3565
  if (paramsBox) paramsBox.hidden = byMessage;
3566
+ // A workflow's result goes where its Messages tab says.
3567
+ var notifyField = form.querySelector('#scheduleNotifyField');
3568
+ if (notifyField) notifyField.hidden = !byMessage;
3483
3569
  });
3484
3570
  }
3485
3571
  form.addEventListener('submit', function (ev) {
@@ -3503,7 +3589,7 @@ ${consoleShellScript}
3503
3589
  method: 'POST', headers: { 'content-type': 'application/json' },
3504
3590
  body: JSON.stringify(Object.assign(
3505
3591
  runsWorkflow ? { workflow_id: data.get('workflow_id'), params: scheduleParams(data) } : { message: data.get('message') },
3506
- { schedule: schedule, task_name: data.get('task_name'), result_to_chat: data.get('notify') === 'on' }
3592
+ { schedule: schedule, task_name: data.get('task_name'), result_to_chat: !runsWorkflow && data.get('notify') === 'on' }
3507
3593
  )),
3508
3594
  }).then(function (r) {
3509
3595
  if (!r.ok) { result.textContent = r.body.error || 'Could not schedule'; return; }
@@ -319,6 +319,10 @@ export declare function contractFields(input: Record<string, unknown>): {
319
319
  model?: WorkflowModel | null;
320
320
  output?: string | null;
321
321
  };
322
+ /** The Messages tab's save: where every run's updates, approvals and
323
+ * questions, start notice and result go. { callback_url, decisions,
324
+ * chat_notice, result_to_chat }; empty for the messaging app's defaults. */
325
+ export declare function updateWorkflowMessages(agentDir: string, id: string, input: Record<string, unknown>): Workflow;
322
326
  export declare function updateWorkflow(agentDir: string, id: string, input: Record<string, unknown>): Workflow;
323
327
  /** Removes a workflow: its skill stays, as a plain skill the agent can
324
328
  * still use in chat, and what started it goes: its schedules are
@@ -13,10 +13,10 @@ import { setAgentEnvVar } from './env-admin.js';
13
13
  import { installFailureReason, templateChecklist } from './templates-admin.js';
14
14
  import { templateScheduleStart } from '../core/system-agents/templates.js';
15
15
  import { planParameters, planWebhook, planWorkflowWithModel, workflowTemplate } from '../core/system-agents/workflow-planner.js';
16
- import { createTrigger, getTriggerStore, listTriggers, publicTrigger } from '../core/workflow-triggers.js';
16
+ import { checkRunDelivery, createTrigger, getTriggerStore, listTriggers, publicTrigger } from '../core/workflow-triggers.js';
17
17
  import { mcpAbilityNames } from '../core/mcp-ability-generator.js';
18
18
  import { contextToolsFor } from '../core/mcp-apps.js';
19
- import { clearWorkflowFields, migrateWorkflowsFile, readWorkflow, readWorkflows, setWorkflowFields, validateParams, workflowRunMessage } from '../core/workflows.js';
19
+ import { clearWorkflowFields, migrateWorkflowsFile, readWorkflow, readWorkflows, setWorkflowDelivery, setWorkflowFields, validateParams, workflowRunMessage } from '../core/workflows.js';
20
20
  import { readEvals, workflowScores } from './workflow-evidence.js';
21
21
  import { isUnderWay, listRuns } from '../core/workflow-runs.js';
22
22
  import { cancelScheduledTask, createScheduledTask, deleteScheduledTask, describeSchedule, getSchedulerStore, listScheduledTasks, pauseScheduledTask } from '../core/scheduler.js';
@@ -822,8 +822,32 @@ export function contractFields(input) {
822
822
  throw new WorkflowError('The result format is too long: keep it under 2000 characters.');
823
823
  fields.output = typeof input.output === 'string' ? input.output : null;
824
824
  }
825
+ // Where every run's updates and decisions go: { callback_url, decisions,
826
+ // chat_notice }, or null for the messaging app only.
827
+ if (input.delivery !== undefined) {
828
+ if (input.delivery === null)
829
+ fields.delivery = null;
830
+ else if (typeof input.delivery !== 'object' || Array.isArray(input.delivery))
831
+ throw new WorkflowError('delivery must be { callback_url, decisions, chat_notice }, or null.');
832
+ else {
833
+ fields.delivery = deliveryOf(input.delivery);
834
+ }
835
+ }
825
836
  return fields;
826
837
  }
838
+ function deliveryOf(input) {
839
+ const d = checkRunDelivery(input, (m) => new WorkflowError(m));
840
+ return Object.keys(d).length ? d : null;
841
+ }
842
+ /** The Messages tab's save: where every run's updates, approvals and
843
+ * questions, start notice and result go. { callback_url, decisions,
844
+ * chat_notice, result_to_chat }; empty for the messaging app's defaults. */
845
+ export function updateWorkflowMessages(agentDir, id, input) {
846
+ if (!readWorkflow(agentDir, id))
847
+ throw new WorkflowError(`No workflow ${id}.`);
848
+ setWorkflowDelivery(agentDir, id, deliveryOf(input));
849
+ return readWorkflow(agentDir, id);
850
+ }
827
851
  export function updateWorkflow(agentDir, id, input) {
828
852
  if (!readWorkflow(agentDir, id))
829
853
  throw new WorkflowError(`No workflow ${id}.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.3.83",
3
+ "version": "0.3.85",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",