loopengine 0.3.80 → 0.3.82
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core/run-agent.d.ts +6 -0
- package/dist/core/run-agent.js +8 -6
- package/dist/core/run-callbacks.d.ts +20 -3
- package/dist/core/run-callbacks.js +13 -5
- package/dist/core/workflow-runs.d.ts +22 -6
- package/dist/core/workflow-runs.js +13 -6
- package/dist/core/workflow-triggers.d.ts +36 -1
- package/dist/core/workflow-triggers.js +60 -7
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/web/agents-config-page.js +28 -13
- package/dist/web/console-shell.js +31 -3
- package/dist/web/dev-ui-styles.js +1 -0
- package/dist/web/goals-page.js +7 -0
- package/dist/web/notifier-admin.d.ts +10 -0
- package/dist/web/notifier-admin.js +45 -0
- package/dist/web/workflow-admin.js +1 -1
- package/package.json +1 -1
package/dist/core/run-agent.d.ts
CHANGED
|
@@ -148,6 +148,12 @@ export interface RunAgentOptions {
|
|
|
148
148
|
* asks the person something is sent back for the agent to make the
|
|
149
149
|
* call (the tool, or system_ask_user) instead. */
|
|
150
150
|
unattended?: boolean;
|
|
151
|
+
/** Whoever started this run handles its decisions (a workflow run
|
|
152
|
+
* started with "decisions": "callback"): `approver` and
|
|
153
|
+
* `questionHandler` apply even on the `http` channel, the agent's
|
|
154
|
+
* messaging settings (httpNotifier) are never consulted, and their run
|
|
155
|
+
* started/finished messages aren't sent. */
|
|
156
|
+
callerDecides?: boolean;
|
|
151
157
|
/** This call's own default QuestionHandler — question-side sibling of
|
|
152
158
|
* `approver` above, same precedence (`AgentConfig.httpNotifier`, when it
|
|
153
159
|
* covers `'question'` on the `http` channel, still wins outright over
|
package/dist/core/run-agent.js
CHANGED
|
@@ -382,7 +382,9 @@ async function buildTurnContext(config, modelCall, options) {
|
|
|
382
382
|
// httpNotifier first is what lets a single agent's own httpNotifier
|
|
383
383
|
// actually take effect there, rather than being silently shadowed by
|
|
384
384
|
// that per-deployment default every time.
|
|
385
|
-
|
|
385
|
+
// A run whose caller handles its decisions never uses the agent's own.
|
|
386
|
+
const notifierApplies = options.channel === 'http' && !options.callerDecides;
|
|
387
|
+
const approver = (notifierApplies ? httpNotifier.approver : undefined) ?? options.approver ?? new ConsoleApprover();
|
|
386
388
|
const gate = new Gate(rules, approver);
|
|
387
389
|
// Exact mirror of approver's own resolution above, same reasoning and
|
|
388
390
|
// same ordering (httpNotifier checked before options.questionHandler,
|
|
@@ -391,7 +393,7 @@ async function buildTurnContext(config, modelCall, options) {
|
|
|
391
393
|
// own doc comment for the one place this still isn't a full mirror of
|
|
392
394
|
// approver (only the durable branch below actually reads this; the live
|
|
393
395
|
// branch keeps resolving independently, via onQuestionPending).
|
|
394
|
-
const questionHandler = (
|
|
396
|
+
const questionHandler = (notifierApplies ? httpNotifier.questionHandler : undefined) ?? options.questionHandler ?? new CliQuestionHandler();
|
|
395
397
|
// No explicit isSafeTool: fall back to each called tool's own `safe`
|
|
396
398
|
// flag (looked up by name) rather than defaulting every tool to unsafe
|
|
397
399
|
// outright — see ToolDefinition.safe's own doc comment for why this is
|
|
@@ -942,12 +944,12 @@ export async function runAgent(config, modelCall, userMessage, history = [], opt
|
|
|
942
944
|
const ctx = await buildTurnContext(config, modelCall, options);
|
|
943
945
|
// config.onRunStart, if set, still wins outright over notifier's own
|
|
944
946
|
// derived hook — see NotifierConfig's own doc comment on precedence.
|
|
945
|
-
const onRunStart = config.onRunStart ?? (options.channel === 'http' ? ctx.httpNotifier.onRunStart : undefined);
|
|
947
|
+
const onRunStart = config.onRunStart ?? (options.channel === 'http' && !options.callerDecides ? ctx.httpNotifier.onRunStart : undefined);
|
|
946
948
|
if (onRunStart && shouldFireLifecycleHooks(options.channel)) {
|
|
947
949
|
fireLifecycleHook('onRunStart', config.name, () => onRunStart({ agent: config.name, tenant: ctx.scope.tenant, sessionId: options.sessionId, channel: options.channel, trigger: 'message' }));
|
|
948
950
|
}
|
|
949
951
|
const result = await runLoop(ctx, [...history], [], { role: 'user', content: userMessage });
|
|
950
|
-
const onRunFinish = config.onRunFinish ?? (options.channel === 'http' ? ctx.httpNotifier.onRunFinish : undefined);
|
|
952
|
+
const onRunFinish = config.onRunFinish ?? (options.channel === 'http' && !options.callerDecides ? ctx.httpNotifier.onRunFinish : undefined);
|
|
951
953
|
if (onRunFinish && !result.pending && shouldFireLifecycleHooks(options.channel)) {
|
|
952
954
|
fireLifecycleHook('onRunFinish', config.name, () => onRunFinish({ agent: config.name, tenant: ctx.scope.tenant, sessionId: options.sessionId, channel: options.channel, text: result.text, stopReason: result.stopReason }));
|
|
953
955
|
}
|
|
@@ -976,7 +978,7 @@ export async function runAgent(config, modelCall, userMessage, history = [], opt
|
|
|
976
978
|
* of those uniformly regardless of how this turn started. */
|
|
977
979
|
export async function resumeAgent(config, modelCall, history, resolution, options = {}) {
|
|
978
980
|
const ctx = await buildTurnContext(config, modelCall, options);
|
|
979
|
-
const onRunStart = config.onRunStart ?? (options.channel === 'http' ? ctx.httpNotifier.onRunStart : undefined);
|
|
981
|
+
const onRunStart = config.onRunStart ?? (options.channel === 'http' && !options.callerDecides ? ctx.httpNotifier.onRunStart : undefined);
|
|
980
982
|
if (onRunStart && shouldFireLifecycleHooks(options.channel)) {
|
|
981
983
|
fireLifecycleHook('onRunStart', config.name, () => onRunStart({ agent: config.name, tenant: ctx.scope.tenant, sessionId: options.sessionId, channel: options.channel, trigger: 'resolution' }));
|
|
982
984
|
}
|
|
@@ -997,7 +999,7 @@ export async function resumeAgent(config, modelCall, history, resolution, option
|
|
|
997
999
|
const lastMessage = history[history.length - 1];
|
|
998
1000
|
const effectiveHistory = lastMessage?.role === 'user' && lastMessage.content === CRASH_RECOVERY_CONTINUATION ? history.slice(0, -1) : history;
|
|
999
1001
|
const result = await runLoop(ctx, [...effectiveHistory], [], { role: 'user', content: resolution });
|
|
1000
|
-
const onRunFinish = config.onRunFinish ?? (options.channel === 'http' ? ctx.httpNotifier.onRunFinish : undefined);
|
|
1002
|
+
const onRunFinish = config.onRunFinish ?? (options.channel === 'http' && !options.callerDecides ? ctx.httpNotifier.onRunFinish : undefined);
|
|
1001
1003
|
if (onRunFinish && !result.pending && shouldFireLifecycleHooks(options.channel)) {
|
|
1002
1004
|
fireLifecycleHook('onRunFinish', config.name, () => onRunFinish({ agent: config.name, tenant: ctx.scope.tenant, sessionId: options.sessionId, channel: options.channel, text: result.text, stopReason: result.stopReason }));
|
|
1003
1005
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export declare class CallbackUrlError extends Error {
|
|
2
2
|
}
|
|
3
|
-
export type RunCallbackEvent = 'run.done' | 'run.failed' | 'run.awaiting_approval';
|
|
3
|
+
export type RunCallbackEvent = 'run.started' | 'run.done' | 'run.failed' | 'run.awaiting_approval';
|
|
4
4
|
/** Whether an IP address is private, loopback, link-local or otherwise
|
|
5
5
|
* not on the public internet. */
|
|
6
6
|
export declare function isPrivateAddress(address: string): boolean;
|
|
@@ -31,9 +31,26 @@ export interface DeliverOptions {
|
|
|
31
31
|
* host is looked up first, and a private address is refused (unless
|
|
32
32
|
* local callbacks are allowed), so a public name can't lead inward. */
|
|
33
33
|
export declare function deliverCallback(url: string, event: RunCallbackEvent, payload: unknown, options?: DeliverOptions): Promise<CallbackDelivery>;
|
|
34
|
+
/** An approval or question a run waits on, as its callback shows it. */
|
|
35
|
+
export interface CallbackPending {
|
|
36
|
+
pendingId: string;
|
|
37
|
+
kind: 'approval' | 'question';
|
|
38
|
+
tool: string;
|
|
39
|
+
args: Record<string, unknown>;
|
|
40
|
+
reason: string;
|
|
41
|
+
/** For a question: what it asks, and the choices it offers, if any. */
|
|
42
|
+
question?: string;
|
|
43
|
+
options?: string[];
|
|
44
|
+
/** Where to send the decision: POST { decision, editedArgs? } to
|
|
45
|
+
* resolvePath, or { answer } to answerPath. */
|
|
46
|
+
resolvePath?: string;
|
|
47
|
+
answerPath?: string;
|
|
48
|
+
}
|
|
34
49
|
/** What a run's callback carries: the event and the run's record, without
|
|
35
|
-
* its session id, its first message or past callback deliveries
|
|
36
|
-
|
|
50
|
+
* its session id, its first message or past callback deliveries; and for
|
|
51
|
+
* run.awaiting_approval, what it waits on. */
|
|
52
|
+
export declare function runCallbackPayload(event: RunCallbackEvent, run: object, pending?: CallbackPending[]): {
|
|
37
53
|
event: RunCallbackEvent;
|
|
38
54
|
run: Record<string, unknown>;
|
|
55
|
+
pending?: CallbackPending[];
|
|
39
56
|
};
|
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
// Callbacks for workflow runs started over the API: a run started with
|
|
2
2
|
// "callback_url" has its record posted there when it finishes, fails, or
|
|
3
3
|
// stops for an approval or a question (core/workflow-runs.ts calls
|
|
4
|
-
// deliverRunCallback for each of those).
|
|
4
|
+
// deliverRunCallback for each of those). A run.awaiting_approval carries
|
|
5
|
+
// what it waits on: each approval's tool, arguments and reason, or the
|
|
6
|
+
// question, with where to send the answer.
|
|
7
|
+
//
|
|
8
|
+
// A run started with "decisions": "callback" sends its approvals and
|
|
9
|
+
// questions only here, never to the agent's messaging app, and also
|
|
10
|
+
// reports run.started, so the receiving app can show the case at once.
|
|
5
11
|
//
|
|
6
12
|
// Each POST carries
|
|
7
|
-
// X-LoopEngine-Event: run.done | run.failed | run.awaiting_approval
|
|
13
|
+
// X-LoopEngine-Event: run.started | run.done | run.failed | run.awaiting_approval
|
|
14
|
+
// (run.started only for a run whose decisions come here, see below)
|
|
8
15
|
// X-LoopEngine-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<body>">
|
|
9
16
|
// signed with the workspace's callback secret: LOOPENGINE_CALLBACK_SECRET,
|
|
10
17
|
// or one made once and kept in the scheduler's folder
|
|
@@ -118,8 +125,9 @@ export async function deliverCallback(url, event, payload, options = {}) {
|
|
|
118
125
|
return last;
|
|
119
126
|
}
|
|
120
127
|
/** What a run's callback carries: the event and the run's record, without
|
|
121
|
-
* its session id, its first message or past callback deliveries
|
|
122
|
-
|
|
128
|
+
* its session id, its first message or past callback deliveries; and for
|
|
129
|
+
* run.awaiting_approval, what it waits on. */
|
|
130
|
+
export function runCallbackPayload(event, run, pending) {
|
|
123
131
|
const { session_id: _session, message: _message, callbacks: _callbacks, ...rest } = run;
|
|
124
|
-
return { event, run: rest };
|
|
132
|
+
return { event, run: rest, ...(pending ? { pending } : {}) };
|
|
125
133
|
}
|
|
@@ -36,11 +36,22 @@ export interface WorkflowRun {
|
|
|
36
36
|
error?: string;
|
|
37
37
|
/** The approvals or questions it is waiting on. */
|
|
38
38
|
pending_ids?: string[];
|
|
39
|
-
/** Send its result
|
|
39
|
+
/** Send its result to the agent's messaging app when it ends. */
|
|
40
|
+
result_to_chat?: boolean;
|
|
41
|
+
/** The old name of result_to_chat, on runs recorded before it. */
|
|
40
42
|
notify?: boolean;
|
|
41
|
-
/** Where its record is posted when it
|
|
42
|
-
* (core/run-callbacks.ts). */
|
|
43
|
+
/** Where its record is posted when it starts (with decisions_to), stops
|
|
44
|
+
* for a decision, ends or fails (core/run-callbacks.ts). */
|
|
43
45
|
callback_url?: string;
|
|
46
|
+
/** "callback": its approvals and questions go only to callback_url,
|
|
47
|
+
* never to the agent's messaging app, and the app that gets them
|
|
48
|
+
* answers through the API. */
|
|
49
|
+
decisions_to?: 'callback';
|
|
50
|
+
/** A message posted to the agent's messaging app when it starts. */
|
|
51
|
+
chat_notice?: string;
|
|
52
|
+
/** Something asked for that couldn't be done, e.g. a chat notice with
|
|
53
|
+
* no messaging app set up. The run goes ahead without it. */
|
|
54
|
+
warnings?: string[];
|
|
44
55
|
/** Each callback delivery, oldest first (the latest 10). */
|
|
45
56
|
callbacks?: CallbackDelivery[];
|
|
46
57
|
/** Each approval decided while it ran, oldest first. */
|
|
@@ -73,6 +84,7 @@ export type RunOutcome = {
|
|
|
73
84
|
* run says which workflow, for its own model. */
|
|
74
85
|
export type ExecuteRun = (agent: string, message: string, sessionId: string, options?: {
|
|
75
86
|
workflowId?: string;
|
|
87
|
+
decisionsTo?: 'callback';
|
|
76
88
|
}) => Promise<RunOutcome>;
|
|
77
89
|
export declare class RunError extends Error {
|
|
78
90
|
}
|
|
@@ -111,8 +123,11 @@ export interface StartRunInput {
|
|
|
111
123
|
params?: Record<string, string>;
|
|
112
124
|
source: WorkflowRun['source'];
|
|
113
125
|
message: string;
|
|
114
|
-
|
|
126
|
+
result_to_chat?: boolean;
|
|
115
127
|
callback_url?: string;
|
|
128
|
+
decisions_to?: 'callback';
|
|
129
|
+
chat_notice?: string;
|
|
130
|
+
warnings?: string[];
|
|
116
131
|
trigger_id?: string;
|
|
117
132
|
job?: {
|
|
118
133
|
goal: string;
|
|
@@ -126,8 +141,9 @@ export declare class WorkflowRunner {
|
|
|
126
141
|
private readonly maxFinishedPerAgent;
|
|
127
142
|
private readonly onChange?;
|
|
128
143
|
private readonly inFlight;
|
|
129
|
-
/** `onChange`: called with the run
|
|
130
|
-
* stops for a decision (the server sends its
|
|
144
|
+
/** `onChange`: called with the run when it starts, and each time it
|
|
145
|
+
* finishes, fails or stops for a decision (the server sends its chat
|
|
146
|
+
* messages and callbacks). */
|
|
131
147
|
constructor(options: {
|
|
132
148
|
execute: ExecuteRun;
|
|
133
149
|
maxFinishedPerAgent?: number;
|
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
//
|
|
8
8
|
// A run executes the same way a scheduled task fires (supplied by the
|
|
9
9
|
// server, adapters/http.ts): an unattended agent turn whose approvals and
|
|
10
|
-
// questions go to the agent's messaging app and wait durably
|
|
11
|
-
//
|
|
10
|
+
// questions go to the agent's messaging app and wait durably (or, for a
|
|
11
|
+
// run started with "decisions": "callback", only to its callback_url). A
|
|
12
|
+
// run that pauses there is settled by settleFromResume once someone
|
|
13
|
+
// decides.
|
|
12
14
|
//
|
|
13
15
|
// Stored like scheduled tasks: one JSON file per run under
|
|
14
16
|
// `<LOOPENGINE_SCHEDULER_DIR or .scheduler>/runs/`. Each agent keeps its
|
|
@@ -104,8 +106,9 @@ export class WorkflowRunner {
|
|
|
104
106
|
maxFinishedPerAgent;
|
|
105
107
|
onChange;
|
|
106
108
|
inFlight = new Set();
|
|
107
|
-
/** `onChange`: called with the run
|
|
108
|
-
* stops for a decision (the server sends its
|
|
109
|
+
/** `onChange`: called with the run when it starts, and each time it
|
|
110
|
+
* finishes, fails or stops for a decision (the server sends its chat
|
|
111
|
+
* messages and callbacks). */
|
|
109
112
|
constructor(options) {
|
|
110
113
|
this.execute = options.execute;
|
|
111
114
|
this.maxFinishedPerAgent = options.maxFinishedPerAgent ?? MAX_FINISHED_PER_AGENT;
|
|
@@ -127,8 +130,11 @@ export class WorkflowRunner {
|
|
|
127
130
|
workflow_id: input.workflow_id,
|
|
128
131
|
...(input.params && Object.keys(input.params).length ? { params: input.params } : {}),
|
|
129
132
|
source: input.source,
|
|
130
|
-
...(input.
|
|
133
|
+
...(input.result_to_chat ? { result_to_chat: true } : {}),
|
|
131
134
|
...(input.callback_url ? { callback_url: input.callback_url } : {}),
|
|
135
|
+
...(input.decisions_to ? { decisions_to: input.decisions_to } : {}),
|
|
136
|
+
...(input.chat_notice ? { chat_notice: input.chat_notice } : {}),
|
|
137
|
+
...(input.warnings?.length ? { warnings: input.warnings } : {}),
|
|
132
138
|
...(input.trigger_id ? { trigger_id: input.trigger_id } : {}),
|
|
133
139
|
...(input.job ? { job: input.job } : {}),
|
|
134
140
|
...(input.chained_from ? { chained_from: input.chained_from, chain_depth: input.chain_depth ?? 1 } : {}),
|
|
@@ -139,6 +145,7 @@ export class WorkflowRunner {
|
|
|
139
145
|
};
|
|
140
146
|
await getRunStore().put(run);
|
|
141
147
|
await this.prune(input.agent);
|
|
148
|
+
this.changed(run);
|
|
142
149
|
const job = this.run(run).finally(() => this.inFlight.delete(job));
|
|
143
150
|
this.inFlight.add(job);
|
|
144
151
|
return run;
|
|
@@ -186,7 +193,7 @@ export class WorkflowRunner {
|
|
|
186
193
|
}
|
|
187
194
|
async run(run) {
|
|
188
195
|
try {
|
|
189
|
-
const outcome = await this.execute(run.agent, run.message, run.session_id, { workflowId: run.workflow_id });
|
|
196
|
+
const outcome = await this.execute(run.agent, run.message, run.session_id, { workflowId: run.workflow_id, ...(run.decisions_to ? { decisionsTo: run.decisions_to } : {}) });
|
|
190
197
|
if (outcome.kind === 'pending') {
|
|
191
198
|
this.changed(await getRunStore().update(run.run_id, (r) => r && { ...r, status: 'awaiting_approval', pending_ids: outcome.pendingIds }));
|
|
192
199
|
return;
|
|
@@ -50,8 +50,18 @@ export interface WorkflowTrigger {
|
|
|
50
50
|
mapping?: Record<string, string>;
|
|
51
51
|
/** A parameter that gets the whole payload, as JSON. */
|
|
52
52
|
payload_param?: string;
|
|
53
|
+
/** Send each run's result to the agent's messaging app. */
|
|
54
|
+
result_to_chat?: boolean;
|
|
55
|
+
/** The old name of result_to_chat, on triggers saved before it. */
|
|
53
56
|
notify?: boolean;
|
|
57
|
+
/** Where each run's updates are posted (core/run-callbacks.ts). */
|
|
54
58
|
callback_url?: string;
|
|
59
|
+
/** "callback": each run's approvals and questions go only to
|
|
60
|
+
* callback_url, not to the agent's messaging app. */
|
|
61
|
+
decisions_to?: 'callback';
|
|
62
|
+
/** A message posted to the agent's messaging app when a run starts;
|
|
63
|
+
* {{path}} is filled from the payload, e.g. {{data.object.amount}}. */
|
|
64
|
+
chat_notice?: string;
|
|
55
65
|
/** The latest deliveries, newest first (20). */
|
|
56
66
|
deliveries: TriggerDelivery[];
|
|
57
67
|
/** Delivery ids already handled (the latest 200), for retries. */
|
|
@@ -95,9 +105,34 @@ export interface TriggerSettings {
|
|
|
95
105
|
filter?: unknown;
|
|
96
106
|
mapping?: unknown;
|
|
97
107
|
payload_param?: unknown;
|
|
108
|
+
result_to_chat?: unknown;
|
|
109
|
+
/** The old name of result_to_chat. */
|
|
98
110
|
notify?: unknown;
|
|
99
111
|
callback_url?: unknown;
|
|
112
|
+
/** "callback" or null; given as "decisions" over the API. */
|
|
113
|
+
decisions?: unknown;
|
|
114
|
+
chat_notice?: unknown;
|
|
100
115
|
}
|
|
116
|
+
/** Whether a trigger sends its runs' results to the messaging app. */
|
|
117
|
+
export declare function resultToChat(trigger: Pick<WorkflowTrigger, 'result_to_chat' | 'notify'>): boolean;
|
|
118
|
+
/** Settings that send a run's results, decisions or a notice somewhere,
|
|
119
|
+
* shared by webhook triggers and runs started over the API. Throws
|
|
120
|
+
* `makeError` saying what's wrong. */
|
|
121
|
+
export declare function checkRunDelivery<E extends Error>(input: {
|
|
122
|
+
result_to_chat?: unknown;
|
|
123
|
+
notify?: unknown;
|
|
124
|
+
callback_url?: unknown;
|
|
125
|
+
decisions?: unknown;
|
|
126
|
+
chat_notice?: unknown;
|
|
127
|
+
}, makeError: (message: string) => E): {
|
|
128
|
+
result_to_chat?: true;
|
|
129
|
+
callback_url?: string;
|
|
130
|
+
decisions_to?: 'callback';
|
|
131
|
+
chat_notice?: string;
|
|
132
|
+
};
|
|
133
|
+
/** A chat notice with each {{path}} filled from `source` (a webhook's
|
|
134
|
+
* payload, or a run's inputs); a path with no value is left empty. */
|
|
135
|
+
export declare function fillChatNotice(template: string, source: unknown): string;
|
|
101
136
|
/** Checks settings for a trigger of `workflow`; throws TriggerError saying
|
|
102
137
|
* what's wrong. With `existing` (a change), a setting left out keeps its
|
|
103
138
|
* value and null removes it, and a sender's secret is kept when only the
|
|
@@ -107,7 +142,7 @@ export interface TriggerSettings {
|
|
|
107
142
|
* secret yet: the workflow planner makes one that way, for the person to
|
|
108
143
|
* add the secret the sender shows them. It can't be turned on until the
|
|
109
144
|
* secret is there. */
|
|
110
|
-
export declare function checkTriggerSettings(input: TriggerSettings, workflow: Workflow, existing?: WorkflowTrigger): Pick<WorkflowTrigger, 'name' | 'enabled' | 'verify' | 'filter' | 'mapping' | 'payload_param' | '
|
|
145
|
+
export declare function checkTriggerSettings(input: TriggerSettings, workflow: Workflow, existing?: WorkflowTrigger): Pick<WorkflowTrigger, 'name' | 'enabled' | 'verify' | 'filter' | 'mapping' | 'payload_param' | 'result_to_chat' | 'callback_url' | 'decisions_to' | 'chat_notice'>;
|
|
111
146
|
/** Makes a trigger for a workflow; returns it with its token (shown once). */
|
|
112
147
|
export declare function createTrigger(agent: string, workflow: Workflow, input: TriggerSettings): Promise<{
|
|
113
148
|
trigger: WorkflowTrigger;
|
|
@@ -99,6 +99,58 @@ export function publicTrigger(t) {
|
|
|
99
99
|
const { secret, ...shown } = verify;
|
|
100
100
|
return { ...rest, verify: { ...shown, secret_set: Boolean(secret) } };
|
|
101
101
|
}
|
|
102
|
+
/** Longest chat notice, before its {{paths}} are filled. */
|
|
103
|
+
const MAX_CHAT_NOTICE = 1000;
|
|
104
|
+
/** Whether a trigger sends its runs' results to the messaging app. */
|
|
105
|
+
export function resultToChat(trigger) {
|
|
106
|
+
return Boolean(trigger.result_to_chat ?? trigger.notify);
|
|
107
|
+
}
|
|
108
|
+
/** Settings that send a run's results, decisions or a notice somewhere,
|
|
109
|
+
* shared by webhook triggers and runs started over the API. Throws
|
|
110
|
+
* `makeError` saying what's wrong. */
|
|
111
|
+
export function checkRunDelivery(input, makeError) {
|
|
112
|
+
const toChat = input.result_to_chat ?? input.notify;
|
|
113
|
+
if (toChat !== undefined && toChat !== null && typeof toChat !== 'boolean')
|
|
114
|
+
throw makeError('result_to_chat must be true or false');
|
|
115
|
+
let callbackUrl;
|
|
116
|
+
if (input.callback_url !== undefined && input.callback_url !== null && input.callback_url !== '') {
|
|
117
|
+
try {
|
|
118
|
+
callbackUrl = checkCallbackUrl(input.callback_url);
|
|
119
|
+
}
|
|
120
|
+
catch (err) {
|
|
121
|
+
throw makeError(err instanceof Error ? err.message : String(err));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const decisions = input.decisions === undefined || input.decisions === null || input.decisions === '' || input.decisions === 'chat' ? undefined : input.decisions;
|
|
125
|
+
if (decisions !== undefined && decisions !== 'callback')
|
|
126
|
+
throw makeError('decisions must be "callback" (send approvals and questions to callback_url) or left out');
|
|
127
|
+
if (decisions && !callbackUrl)
|
|
128
|
+
throw makeError('decisions "callback" needs a callback_url to send the run\'s approvals and questions to');
|
|
129
|
+
let notice;
|
|
130
|
+
if (input.chat_notice !== undefined && input.chat_notice !== null) {
|
|
131
|
+
if (typeof input.chat_notice !== 'string')
|
|
132
|
+
throw makeError('chat_notice must be text');
|
|
133
|
+
notice = input.chat_notice.trim() || undefined;
|
|
134
|
+
if (notice && notice.length > MAX_CHAT_NOTICE)
|
|
135
|
+
throw makeError(`chat_notice is too long: keep it under ${MAX_CHAT_NOTICE} characters`);
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
...(toChat === true ? { result_to_chat: true } : {}),
|
|
139
|
+
...(callbackUrl ? { callback_url: callbackUrl } : {}),
|
|
140
|
+
...(decisions ? { decisions_to: 'callback' } : {}),
|
|
141
|
+
...(notice ? { chat_notice: notice } : {}),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** A chat notice with each {{path}} filled from `source` (a webhook's
|
|
145
|
+
* payload, or a run's inputs); a path with no value is left empty. */
|
|
146
|
+
export function fillChatNotice(template, source) {
|
|
147
|
+
return template.replace(/\{\{\s*([A-Za-z0-9_.\-]+)\s*\}\}/g, (_, p) => {
|
|
148
|
+
const value = valueAt(source, p);
|
|
149
|
+
if (value === undefined || value === null)
|
|
150
|
+
return '';
|
|
151
|
+
return typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
102
154
|
/** Checks settings for a trigger of `workflow`; throws TriggerError saying
|
|
103
155
|
* what's wrong. With `existing` (a change), a setting left out keeps its
|
|
104
156
|
* value and null removes it, and a sender's secret is kept when only the
|
|
@@ -110,11 +162,15 @@ export function publicTrigger(t) {
|
|
|
110
162
|
* secret is there. */
|
|
111
163
|
export function checkTriggerSettings(input, workflow, existing) {
|
|
112
164
|
if (existing) {
|
|
113
|
-
const keys = ['verify', 'filter', 'mapping', 'payload_param', '
|
|
165
|
+
const keys = ['verify', 'filter', 'mapping', 'payload_param', 'callback_url', 'chat_notice'];
|
|
114
166
|
input = { ...input };
|
|
115
167
|
for (const key of keys)
|
|
116
168
|
if (input[key] === undefined && existing[key] !== undefined)
|
|
117
169
|
input[key] = existing[key];
|
|
170
|
+
if (input.result_to_chat === undefined && input.notify === undefined && resultToChat(existing))
|
|
171
|
+
input.result_to_chat = true;
|
|
172
|
+
if (input.decisions === undefined && existing.decisions_to)
|
|
173
|
+
input.decisions = existing.decisions_to;
|
|
118
174
|
}
|
|
119
175
|
const name = typeof input.name === 'string' && input.name.trim() ? input.name.trim().slice(0, 80) : existing?.name ?? 'Webhook';
|
|
120
176
|
if (input.enabled !== undefined && typeof input.enabled !== 'boolean')
|
|
@@ -178,9 +234,7 @@ export function checkTriggerSettings(input, workflow, existing) {
|
|
|
178
234
|
throw new TriggerError(`payload_param: ${workflow.title} has no parameter "${input.payload_param}"`);
|
|
179
235
|
payloadParam = input.payload_param;
|
|
180
236
|
}
|
|
181
|
-
|
|
182
|
-
throw new TriggerError('notify must be true or false');
|
|
183
|
-
const callbackUrl = input.callback_url ? checkCallbackUrl(input.callback_url) : undefined;
|
|
237
|
+
const delivery = checkRunDelivery(input, (m) => new TriggerError(m));
|
|
184
238
|
return {
|
|
185
239
|
name,
|
|
186
240
|
enabled,
|
|
@@ -188,8 +242,7 @@ export function checkTriggerSettings(input, workflow, existing) {
|
|
|
188
242
|
...(filter ? { filter } : {}),
|
|
189
243
|
...(mapping ? { mapping } : {}),
|
|
190
244
|
...(payloadParam ? { payload_param: payloadParam } : {}),
|
|
191
|
-
...
|
|
192
|
-
...(callbackUrl ? { callback_url: callbackUrl } : {}),
|
|
245
|
+
...delivery,
|
|
193
246
|
};
|
|
194
247
|
}
|
|
195
248
|
/** Makes a trigger for a workflow; returns it with its token (shown once). */
|
|
@@ -215,7 +268,7 @@ export async function updateTrigger(id, workflow, input) {
|
|
|
215
268
|
if (!existing)
|
|
216
269
|
throw new TriggerError(`no trigger ${id}`);
|
|
217
270
|
const settings = checkTriggerSettings(input, workflow, existing);
|
|
218
|
-
const { verify: _v, filter: _f, mapping: _m, payload_param: _p, notify: _n, callback_url: _c, ...kept } = existing;
|
|
271
|
+
const { verify: _v, filter: _f, mapping: _m, payload_param: _p, notify: _n, result_to_chat: _r, callback_url: _c, decisions_to: _d, chat_notice: _t, ...kept } = existing;
|
|
219
272
|
const next = { ...kept, ...settings };
|
|
220
273
|
await getTriggerStore().put(next);
|
|
221
274
|
return next;
|
package/dist/index.d.ts
CHANGED
|
@@ -23,7 +23,7 @@ export { parseSlackEvent, createSlackConnector, verifySlackRequest, parseSlackIn
|
|
|
23
23
|
export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs, type DecisionKind } from '#core/approval-links.js';
|
|
24
24
|
export { renderDecidePage, renderDecideGonePage, renderDecideInvalidPage, type DecidePageItem } from './web/decide-page.js';
|
|
25
25
|
export { sendTestWebhook, publicBaseUrl } from '#core/http-notify-triggers/webhook.js';
|
|
26
|
-
export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier, type DefaultWebhook } from './web/notifier-admin.js';
|
|
26
|
+
export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier, announceToChat, hasChatApp, hasNotifier, type DefaultWebhook } from './web/notifier-admin.js';
|
|
27
27
|
export { clickAllowed, conversationsOn, jobsOn, jobAllowed, connectionPublicUrl, telegramCredentialsFor, telegramHomeChat, listAgentTelegramPeople, setupAgentTelegramWebhook, agentTelegramWebhookInfo, agentMessagingIdentities, type TwoWayApp } from './web/notifier-admin.js';
|
|
28
28
|
export { createTelegramConnector, parseTelegramUpdate, verifyTelegramRequest, telegramCallbackData, answerTelegramClick, editTelegramMessage, telegramBotUsername, setTelegramWebhook, telegramWebhookInfo, callTelegram, recordTelegramMessage, readTelegramThread, telegramRootOf, telegramPeople, toTelegramHtml, telegramEscape, telegramArgs, type TelegramUpdate, type TelegramButton, type TelegramPerson, } from '#core/messaging/connectors/telegram/index.js';
|
|
29
29
|
export type * from './core/loop-events.js';
|
|
@@ -90,8 +90,8 @@ export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, create
|
|
|
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
|
-
export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, 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
|
-
export { checkCallbackUrl, callbackSecret, signCallback, deliverCallback, runCallbackPayload, isPrivateAddress, CallbackUrlError, type CallbackDelivery, type RunCallbackEvent } from './core/run-callbacks.js';
|
|
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
|
+
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
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';
|
|
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';
|
package/dist/index.js
CHANGED
|
@@ -24,7 +24,7 @@ export { parseSlackEvent, createSlackConnector, verifySlackRequest, parseSlackIn
|
|
|
24
24
|
export { createDecisionToken, verifyDecisionToken, decidePath, decideLinkMaker, decisionLinkTtlMs } from '#core/approval-links.js';
|
|
25
25
|
export { renderDecidePage, renderDecideGonePage, renderDecideInvalidPage } from './web/decide-page.js';
|
|
26
26
|
export { sendTestWebhook, publicBaseUrl } from '#core/http-notify-triggers/webhook.js';
|
|
27
|
-
export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier } from './web/notifier-admin.js';
|
|
27
|
+
export { describeAgentNotifier, saveAgentNotifier, removeAgentNotifier, setAgentPrimaryNotifier, testAgentNotifier, listAgentPending, slackCredentialsFor, slackConversationsOn, slackClickAllowed, agentApprovers, setAgentApprovers, listAgentSlackMembers, listAgentSlackChannels, announceToNotifier, announceToChat, hasChatApp, hasNotifier } from './web/notifier-admin.js';
|
|
28
28
|
export { clickAllowed, conversationsOn, jobsOn, jobAllowed, connectionPublicUrl, telegramCredentialsFor, telegramHomeChat, listAgentTelegramPeople, setupAgentTelegramWebhook, agentTelegramWebhookInfo, agentMessagingIdentities } from './web/notifier-admin.js';
|
|
29
29
|
export { createTelegramConnector, parseTelegramUpdate, verifyTelegramRequest, telegramCallbackData, answerTelegramClick, editTelegramMessage, telegramBotUsername, setTelegramWebhook, telegramWebhookInfo, callTelegram, recordTelegramMessage, readTelegramThread, telegramRootOf, telegramPeople, toTelegramHtml, telegramEscape, telegramArgs, } from '#core/messaging/connectors/telegram/index.js';
|
|
30
30
|
// The framework-agnostic browser client for adapters/http.ts's own wire
|
|
@@ -83,7 +83,7 @@ export { WorkflowError, checkWorkflowForAgent, checkWorkflowRequirements, create
|
|
|
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
|
-
export { createTrigger, updateTrigger, rotateTrigger, listTriggers, findTriggerByToken, publicTrigger, checkTriggerSettings, verifySenderSignature, parsePayload, valueAt, deliveryId, passesFilter, paramsFromPayload, recordDelivery as recordTriggerDelivery, FileTriggerStore, getTriggerStore, setTriggerStore, TriggerError } from './core/workflow-triggers.js';
|
|
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
89
|
export { readWorkflows, readWorkflow, setWorkflowFields, clearWorkflowFields, validateParams, workflowRunMessage, workflowPreviewMessage, migrateWorkflowsFile, WorkflowParamsError, readWorkspacePolicies, writeWorkspacePolicies } from './core/workflows.js';
|
|
@@ -1013,7 +1013,7 @@ ${consoleShellScript}
|
|
|
1013
1013
|
return '<div class="wf-api">' +
|
|
1014
1014
|
'<pre>POST ' + escapeHtml(apiUrl) + String.fromCharCode(10) + escapeHtml(example) + '</pre>' +
|
|
1015
1015
|
'<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; <code>"
|
|
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>' +
|
|
1017
1017
|
'</div>';
|
|
1018
1018
|
}
|
|
1019
1019
|
|
|
@@ -1174,9 +1174,10 @@ ${consoleShellScript}
|
|
|
1174
1174
|
var result = [];
|
|
1175
1175
|
if (w.output) result.push(escapeHtml(w.output));
|
|
1176
1176
|
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.
|
|
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
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>');
|
|
1179
|
-
if ((w.triggers || []).some(function (t) { return t.callback; })) result.push('posted to the webhook' + RSQ + 's
|
|
1179
|
+
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>');
|
|
1180
1181
|
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>';
|
|
1181
1182
|
var row = function (k, lines) { return '<div class="wf-cb-k">' + k + '</div><div class="wf-cb-v">' + contractLinesHtml(lines) + '</div>'; };
|
|
1182
1183
|
return '<div class="wf-cb">' + row('trigger', trigger) + row('inputs', inputs) + row('tools', tools) + row('result', result) + row('model', [model]) + '</div>' +
|
|
@@ -1585,8 +1586,10 @@ ${consoleShellScript}
|
|
|
1585
1586
|
if (t.filter) rules.push('only when ' + escapeHtml(t.filter.path) + ' is ' + t.filter.values.map(escapeHtml).join(' or '));
|
|
1586
1587
|
if (t.mapping) rules.push(Object.keys(t.mapping).map(function (p) { return escapeHtml(p) + ' ' + String.fromCharCode(8592) + ' ' + escapeHtml(t.mapping[p]); }).join(', '));
|
|
1587
1588
|
if (t.payload_param) rules.push('the whole payload goes to ' + escapeHtml(t.payload_param));
|
|
1588
|
-
if (t.
|
|
1589
|
-
if (t.
|
|
1589
|
+
if (t.chat_notice) rules.push('posts a notice to the messaging app when it starts');
|
|
1590
|
+
if (t.result_to_chat || t.notify) rules.push('<span class="workflow-option-value">Send result to messaging app</span>');
|
|
1591
|
+
if (t.callback_url) rules.push('sends run updates to ' + escapeHtml(t.callback_url));
|
|
1592
|
+
if (t.decisions_to === 'callback') rules.push('approvals and questions go there too, not to the messaging app');
|
|
1590
1593
|
// Made by the workflow planner without its secret: it turns on once
|
|
1591
1594
|
// the sender's signing secret is added.
|
|
1592
1595
|
var needsSecret = t.verify && !t.verify.secret_set;
|
|
@@ -1657,9 +1660,13 @@ ${consoleShellScript}
|
|
|
1657
1660
|
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>', '')
|
|
1658
1661
|
: '<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>') +
|
|
1659
1662
|
'</section>' +
|
|
1660
|
-
'<section class="hd-section"><h4>
|
|
1661
|
-
'<
|
|
1662
|
-
|
|
1663
|
+
'<section class="hd-section"><h4>Messaging app</h4>' +
|
|
1664
|
+
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.') +
|
|
1665
|
+
'<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>' +
|
|
1666
|
+
'</section>' +
|
|
1667
|
+
'<section class="hd-section"><h4>Your app</h4>' +
|
|
1668
|
+
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.') +
|
|
1669
|
+
'<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>' +
|
|
1663
1670
|
'</section>' +
|
|
1664
1671
|
'</div>' +
|
|
1665
1672
|
'<footer class="hd-foot"><span class="hook-form-result" role="status"></span>' +
|
|
@@ -1693,6 +1700,12 @@ ${consoleShellScript}
|
|
|
1693
1700
|
}
|
|
1694
1701
|
form.sender.addEventListener('change', senderChanged);
|
|
1695
1702
|
form.filter_values.addEventListener('input', function () { form.name.placeholder = defaultName(); });
|
|
1703
|
+
// Decisions can only go to an address that's given.
|
|
1704
|
+
function callbackChanged() {
|
|
1705
|
+
form.decisions_callback.disabled = !form.callback_url.value.trim();
|
|
1706
|
+
if (form.decisions_callback.disabled) form.decisions_callback.checked = false;
|
|
1707
|
+
}
|
|
1708
|
+
form.callback_url.addEventListener('input', callbackChanged);
|
|
1696
1709
|
senderChanged();
|
|
1697
1710
|
form.addEventListener('submit', function (ev) {
|
|
1698
1711
|
ev.preventDefault();
|
|
@@ -1715,8 +1728,10 @@ ${consoleShellScript}
|
|
|
1715
1728
|
for (var j = 0; j < inputs.length; j++) if (inputs[j].value.trim()) mapping[inputs[j].name.slice(4)] = inputs[j].value.trim();
|
|
1716
1729
|
if (Object.keys(mapping).length) body.mapping = mapping;
|
|
1717
1730
|
if (form.payload_param && form.payload_param.value) body.payload_param = form.payload_param.value;
|
|
1718
|
-
if (form.
|
|
1731
|
+
if (form.result_to_chat.checked) body.result_to_chat = true;
|
|
1719
1732
|
if (form.callback_url.value.trim()) body.callback_url = form.callback_url.value.trim();
|
|
1733
|
+
if (body.callback_url && form.decisions_callback.checked) body.decisions = 'callback';
|
|
1734
|
+
if (form.chat_notice.value.trim()) body.chat_notice = form.chat_notice.value.trim();
|
|
1720
1735
|
result.textContent = 'Making it' + String.fromCharCode(8230);
|
|
1721
1736
|
var submit = form.querySelector('button[type="submit"]');
|
|
1722
1737
|
submit.disabled = true;
|
|
@@ -1921,7 +1936,7 @@ ${consoleShellScript}
|
|
|
1921
1936
|
notifyToggle.disabled = true;
|
|
1922
1937
|
btn.disabled = true;
|
|
1923
1938
|
result.textContent = 'Starting' + String.fromCharCode(8230);
|
|
1924
|
-
fetchJsonRetryOnce(base + '/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ params: params, source: 'console',
|
|
1939
|
+
fetchJsonRetryOnce(base + '/run', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ params: params, source: 'console', result_to_chat: notifyResult }) }).then(function (r) {
|
|
1925
1940
|
btn.disabled = false;
|
|
1926
1941
|
notifyToggle.disabled = false;
|
|
1927
1942
|
if (!r.ok) { result.textContent = r.body.error || 'Could not start it.'; return; }
|
|
@@ -3371,8 +3386,8 @@ ${consoleShellScript}
|
|
|
3371
3386
|
notifyToggles[n].addEventListener('change', function (ev) {
|
|
3372
3387
|
var box = ev.currentTarget;
|
|
3373
3388
|
box.disabled = true;
|
|
3374
|
-
fetchJsonRetryOnce('/schedules/' + encodeURIComponent(box.dataset.id) + '/
|
|
3375
|
-
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({
|
|
3389
|
+
fetchJsonRetryOnce('/schedules/' + encodeURIComponent(box.dataset.id) + '/result-to-chat', {
|
|
3390
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ result_to_chat: box.checked }),
|
|
3376
3391
|
}).then(function (r) {
|
|
3377
3392
|
box.disabled = false;
|
|
3378
3393
|
if (!r.ok) { box.checked = !box.checked; alert('Could not change it: ' + (r.body.error || 'unknown error')); }
|
|
@@ -3438,7 +3453,7 @@ ${consoleShellScript}
|
|
|
3438
3453
|
method: 'POST', headers: { 'content-type': 'application/json' },
|
|
3439
3454
|
body: JSON.stringify(Object.assign(
|
|
3440
3455
|
runsWorkflow ? { workflow_id: data.get('workflow_id'), params: scheduleParams(data) } : { message: data.get('message') },
|
|
3441
|
-
{ schedule: schedule, task_name: data.get('task_name'),
|
|
3456
|
+
{ schedule: schedule, task_name: data.get('task_name'), result_to_chat: data.get('notify') === 'on' }
|
|
3442
3457
|
)),
|
|
3443
3458
|
}).then(function (r) {
|
|
3444
3459
|
if (!r.ok) { result.textContent = r.body.error || 'Could not schedule'; return; }
|
|
@@ -37,6 +37,7 @@ export const consoleSidebarHtml = `<aside class="le-sidebar" aria-label="Console
|
|
|
37
37
|
<div class="le-nav-label"><a class="le-nav-head" href="/goals" data-le-nav-head="goals">${GOALS_ICON}Goals</a><a href="/goals?new=1" data-le-goal-new>+ New</a></div>
|
|
38
38
|
<ul class="le-agent-list le-goal-list" id="leGoalList"></ul>
|
|
39
39
|
<div class="le-nav-label"><a class="le-nav-head" href="/jobs" data-le-nav-head="jobs">${JOBS_ICON}Jobs</a><a href="/jobs?new=1" data-le-job-new>+ New</a></div>
|
|
40
|
+
<ul class="le-agent-list le-goal-list" id="leJobList"></ul>
|
|
40
41
|
<div class="le-nav-label"><a class="le-nav-head" href="/agents" data-le-nav-head="agents">${AGENTS_ICON}Agents</a><a href="/agents?new=1">+ New</a></div>
|
|
41
42
|
<ul class="le-agent-list" id="leAgentList"></ul>
|
|
42
43
|
<a class="le-find" href="/interview" data-le-nav="interview">Find your first agent</a>
|
|
@@ -145,8 +146,6 @@ export const consoleShellScript = `<script>
|
|
|
145
146
|
var creating = page === 'goals' && !onJobs && !current && (location.pathname === '/' || new URLSearchParams(location.search).has('new'));
|
|
146
147
|
var head = document.querySelector('[data-le-nav-head="goals"]');
|
|
147
148
|
if (head) { if (page === 'goals' && !onJobs && !current && !creating) head.setAttribute('aria-current', 'page'); else head.removeAttribute('aria-current'); }
|
|
148
|
-
var jobsHead = document.querySelector('[data-le-nav-head="jobs"]');
|
|
149
|
-
if (jobsHead) { if (onJobs) jobsHead.setAttribute('aria-current', 'page'); else jobsHead.removeAttribute('aria-current'); }
|
|
150
149
|
if (newLink) { if (creating) newLink.setAttribute('aria-current', 'page'); else newLink.removeAttribute('aria-current'); }
|
|
151
150
|
goalList.innerHTML = goals.length ? goals.map(function (g) {
|
|
152
151
|
return '<li><a class="le-agent-item le-goal-item" href="/goals?goal=' + enc(g.id) + '" title="' + esc(g.goal) + '"' + (g.id === current ? ' aria-current="page"' : '') + '>' +
|
|
@@ -157,6 +156,35 @@ export const consoleShellScript = `<script>
|
|
|
157
156
|
}
|
|
158
157
|
reloadGoals();
|
|
159
158
|
|
|
159
|
+
// ---- Jobs, listed under Goals: the person's own jobs (GET /jobs), newest
|
|
160
|
+
// added first, each opening on the Jobs page; its dot says whether it's
|
|
161
|
+
// running, waiting for them, or not started. The Jobs page reloads the
|
|
162
|
+
// list when it changes (leShell.reloadJobs).
|
|
163
|
+
var jobList = document.getElementById('leJobList');
|
|
164
|
+
function reloadJobs() {
|
|
165
|
+
if (!jobList) return Promise.resolve();
|
|
166
|
+
var onJobs = location.pathname === '/jobs';
|
|
167
|
+
var current = onJobs ? new URLSearchParams(location.search).get('job') : null;
|
|
168
|
+
var jobsHead = document.querySelector('[data-le-nav-head="jobs"]');
|
|
169
|
+
if (jobsHead) { if (onJobs && !current) jobsHead.setAttribute('aria-current', 'page'); else jobsHead.removeAttribute('aria-current'); }
|
|
170
|
+
return fetch('/jobs', { headers: { accept: 'application/json' } })
|
|
171
|
+
.then(function (r) { return r.ok ? r.json() : { jobs: [] }; })
|
|
172
|
+
.then(function (data) {
|
|
173
|
+
var jobs = data.jobs || [];
|
|
174
|
+
jobList.innerHTML = jobs.length ? jobs.map(function (x) {
|
|
175
|
+
var j = x.job;
|
|
176
|
+
var t = j.tries && j.tries.length ? j.tries[j.tries.length - 1] : null;
|
|
177
|
+
var dot = t && (t.status === 'awaiting_approval' || t.status === 'done') && j.state === 'active' ? ' warn'
|
|
178
|
+
: j.state === 'active' ? '' : ' idle';
|
|
179
|
+
var label = j.state === 'done' ? 'Done' : j.state === 'active' ? (dot === ' warn' ? 'Needs you' : 'Running') : 'Not started';
|
|
180
|
+
return '<li><a class="le-agent-item le-goal-item" href="/jobs?job=' + enc(j.id) + '" title="' + esc(j.title) + ' (' + label + ')"' + (j.id === current ? ' aria-current="page"' : '') + '>' +
|
|
181
|
+
'<span class="le-dot' + dot + '" aria-hidden="true"></span><span class="le-name">' + esc(j.title) + '</span></a></li>';
|
|
182
|
+
}).join('') : '<li class="le-agent-item"><span></span><span class="le-meta">No jobs yet</span><span></span></li>';
|
|
183
|
+
})
|
|
184
|
+
.catch(function () { jobList.innerHTML = ''; });
|
|
185
|
+
}
|
|
186
|
+
reloadJobs();
|
|
187
|
+
|
|
160
188
|
var loadError = null;
|
|
161
189
|
var ready = fetch('/agents', { headers: { accept: 'application/json' } })
|
|
162
190
|
.then(function (r) {
|
|
@@ -500,6 +528,6 @@ export const consoleShellScript = `<script>
|
|
|
500
528
|
}
|
|
501
529
|
|
|
502
530
|
|
|
503
|
-
window.leShell = { loadError: function () { return loadError; }, ready: ready, reloadGoals: reloadGoals, renderHead: renderHead, setTab: setTab, setActive: setActive, setDisplayName: setDisplayName, displayNameOf: displayNameOf, esc: esc, tabHref: tabHref, envCountHtml: envCountHtml, setCount: setCount, wireModelPicker: wireModelPicker, loadProviderKeys: loadProviderKeys, applyProviderKeys: applyProviderKeys, abilityOriginBadge: abilityOriginBadge, toggleAbilityDetails: toggleAbilityDetails };
|
|
531
|
+
window.leShell = { loadError: function () { return loadError; }, ready: ready, reloadGoals: reloadGoals, reloadJobs: reloadJobs, renderHead: renderHead, setTab: setTab, setActive: setActive, setDisplayName: setDisplayName, displayNameOf: displayNameOf, esc: esc, tabHref: tabHref, envCountHtml: envCountHtml, setCount: setCount, wireModelPicker: wireModelPicker, loadProviderKeys: loadProviderKeys, applyProviderKeys: applyProviderKeys, abilityOriginBadge: abilityOriginBadge, toggleAbilityDetails: toggleAbilityDetails };
|
|
504
532
|
})();
|
|
505
533
|
</script>`;
|
|
@@ -148,6 +148,7 @@ export const devUiCss = `
|
|
|
148
148
|
.le-agent-item .le-meta { font-size: 12px; color: var(--ink-faint); }
|
|
149
149
|
.le-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--good); }
|
|
150
150
|
.le-dot.warn { background: var(--warn); }
|
|
151
|
+
.le-dot.idle { background: var(--ink-faint); }
|
|
151
152
|
.le-foot { border-top: 1px solid var(--line); padding: 8px; display: grid; gap: 2px; }
|
|
152
153
|
.le-foot a { padding: 7px 8px; border-radius: 6px; color: var(--ink-muted); text-decoration: none; }
|
|
153
154
|
.le-foot a:hover { background: var(--surface-2); color: var(--ink); }
|
package/dist/web/goals-page.js
CHANGED
|
@@ -202,10 +202,16 @@ ${consoleShellScript}
|
|
|
202
202
|
function loadJobs() {
|
|
203
203
|
api('GET', '/jobs').then(function (r) {
|
|
204
204
|
if (!r.ok) { page.innerHTML = '<p class="error">Could not load jobs: ' + esc(r.body.error || 'unknown error') + '</p>'; return; }
|
|
205
|
+
var first = !state.jobsLoaded;
|
|
205
206
|
state.jobs = r.body.jobs || [];
|
|
206
207
|
state.jobsLoaded = true;
|
|
207
208
|
state.jobsStale = false;
|
|
209
|
+
// A job picked in the sidebar (?job=): open, and brought into view.
|
|
210
|
+
var picked = first ? new URLSearchParams(location.search).get('job') : null;
|
|
211
|
+
if (picked) state.openJobs[picked] = true;
|
|
212
|
+
if (!first) reloadSidebar();
|
|
208
213
|
render();
|
|
214
|
+
if (picked) { var el = page.querySelector('.gl-job[data-wf="' + picked.replace(/[^a-z0-9-]/gi, '') + '"]'); if (el) el.scrollIntoView({ block: 'center' }); }
|
|
209
215
|
});
|
|
210
216
|
}
|
|
211
217
|
|
|
@@ -257,6 +263,7 @@ ${consoleShellScript}
|
|
|
257
263
|
}
|
|
258
264
|
function reloadSidebar() {
|
|
259
265
|
if (window.leShell && window.leShell.reloadGoals) window.leShell.reloadGoals();
|
|
266
|
+
if (window.leShell && window.leShell.reloadJobs) window.leShell.reloadJobs();
|
|
260
267
|
}
|
|
261
268
|
function replaceGoal(goal) {
|
|
262
269
|
// On the Jobs page, a job's goal coming back means the list changed.
|
|
@@ -162,6 +162,16 @@ export declare function setAgentPrimaryNotifier(config: AgentConfig, channel: un
|
|
|
162
162
|
* `run_finish` payload with `data` merged in; the apps get `text`.
|
|
163
163
|
* Returns whether any notifier took it. */
|
|
164
164
|
export declare function announceToNotifier(config: AgentConfig, text: string, data: Record<string, unknown>, defaultWebhook?: DefaultWebhook): boolean;
|
|
165
|
+
/** Posts `text` to the agent's messaging apps only (Slack, Lark,
|
|
166
|
+
* Telegram), not to a webhook: a run's chat notice. Whether any app got
|
|
167
|
+
* it. */
|
|
168
|
+
export declare function announceToChat(config: AgentConfig, text: string): boolean;
|
|
169
|
+
/** Whether announceToNotifier has anywhere to send: a messaging app or a
|
|
170
|
+
* webhook. */
|
|
171
|
+
export declare function hasNotifier(config: AgentConfig, defaultWebhook?: DefaultWebhook): boolean;
|
|
172
|
+
/** Whether the agent has a messaging app (Slack, Lark or Telegram) to
|
|
173
|
+
* post to. */
|
|
174
|
+
export declare function hasChatApp(config: AgentConfig): boolean;
|
|
165
175
|
/** Sends a test through one app's saved connection when `channel` is
|
|
166
176
|
* given (primary or not, so it can be tried before it's made primary),
|
|
167
177
|
* else through whichever notifier applies to this agent; reports what
|
|
@@ -324,6 +324,51 @@ export function announceToNotifier(config, text, data, defaultWebhook) {
|
|
|
324
324
|
}
|
|
325
325
|
return sent;
|
|
326
326
|
}
|
|
327
|
+
/** Posts `text` to the agent's messaging apps only (Slack, Lark,
|
|
328
|
+
* Telegram), not to a webhook: a run's chat notice. Whether any app got
|
|
329
|
+
* it. */
|
|
330
|
+
export function announceToChat(config, text) {
|
|
331
|
+
let targets;
|
|
332
|
+
try {
|
|
333
|
+
targets = activeNotifierTargets(config);
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
let sent = false;
|
|
339
|
+
for (const target of targets) {
|
|
340
|
+
if (target.channel === 'slack')
|
|
341
|
+
new SlackNotifier({ botToken: target.config.botToken, channelId: target.config.channelId }).postMessage(text);
|
|
342
|
+
else if (target.channel === 'lark')
|
|
343
|
+
new LarkNotifier({ appId: target.config.appId, appSecret: target.config.appSecret, chatId: target.config.chatId }).postMessage(text);
|
|
344
|
+
else if (target.channel === 'telegram')
|
|
345
|
+
new TelegramNotifier({ botToken: target.config.botToken, chatId: target.config.chatId }).postMessage(text);
|
|
346
|
+
else
|
|
347
|
+
continue;
|
|
348
|
+
sent = true;
|
|
349
|
+
}
|
|
350
|
+
return sent;
|
|
351
|
+
}
|
|
352
|
+
/** Whether announceToNotifier has anywhere to send: a messaging app or a
|
|
353
|
+
* webhook. */
|
|
354
|
+
export function hasNotifier(config, defaultWebhook) {
|
|
355
|
+
try {
|
|
356
|
+
return activeNotifierTargets(config, defaultWebhook).length > 0;
|
|
357
|
+
}
|
|
358
|
+
catch {
|
|
359
|
+
return false;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** Whether the agent has a messaging app (Slack, Lark or Telegram) to
|
|
363
|
+
* post to. */
|
|
364
|
+
export function hasChatApp(config) {
|
|
365
|
+
try {
|
|
366
|
+
return activeNotifierTargets(config).some((t) => t.channel === 'slack' || t.channel === 'lark' || t.channel === 'telegram');
|
|
367
|
+
}
|
|
368
|
+
catch {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
327
372
|
/** Sends a test through one app's saved connection when `channel` is
|
|
328
373
|
* given (primary or not, so it can be tried before it's made primary),
|
|
329
374
|
* else through whichever notifier applies to this agent; reports what
|
|
@@ -464,7 +464,7 @@ async function makePlannedWebhook(plan, agent, agentDir) {
|
|
|
464
464
|
verify: { sender: webhook.sender, ...(webhook.header ? { header: webhook.header } : {}) },
|
|
465
465
|
...(webhook.filter ? { filter: webhook.filter } : {}),
|
|
466
466
|
...(webhook.mapping ? { mapping: webhook.mapping } : {}),
|
|
467
|
-
...(plan.notify?.on && plan.trigger.kind === 'webhook' ? {
|
|
467
|
+
...(plan.notify?.on && plan.trigger.kind === 'webhook' ? { result_to_chat: true } : {}),
|
|
468
468
|
});
|
|
469
469
|
return {
|
|
470
470
|
webhook: { trigger: publicTrigger(trigger), token, ...(webhook.setup ? { setup: webhook.setup } : {}) },
|