loopengine 0.3.75 → 0.3.76

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.
@@ -7,7 +7,7 @@ import { DatabaseApprover } from './http-notify-triggers/database.js';
7
7
  import { RedisQueueApprover } from './http-notify-triggers/redis.js';
8
8
  import { agentDirFor, createAgentEnv } from './agent-env.js';
9
9
  import { notifierConfigFromFile, readActiveConnections, readNotifierFile } from './notifier-file.js';
10
- import { recordThread } from './messaging/threads.js';
10
+ import { findThreadByPending, recordThread } from './messaging/threads.js';
11
11
  import { recordTelegramMessage } from './messaging/connectors/telegram/store.js';
12
12
  const EMPTY = {};
13
13
  // Keyed by the AgentConfig object itself, not its httpNotifier field
@@ -190,6 +190,13 @@ function buildResolved(httpNotifier, agentDir) {
190
190
  recordTelegramMessage(agentDir, { chat, id: messageId, root: root ?? messageId, fromBot: true, text });
191
191
  if (pendingId && kind && !root)
192
192
  recordThread(agentDir, { app: 'telegram', conversation: chat, ts: messageId, pendingId, kind });
193
+ // Its buttons are on its last message, recorded so a decision
194
+ // made by reply can take them away.
195
+ if (pendingId && root) {
196
+ const link = findThreadByPending(agentDir, pendingId);
197
+ if (link)
198
+ recordThread(agentDir, { ...link, buttonsTs: messageId });
199
+ }
193
200
  },
194
201
  });
195
202
  return {
@@ -60,4 +60,6 @@ export interface MessagingConnector {
60
60
  /** Replaces the request message itself (and its buttons) with the
61
61
  * outcome, so nobody acts on a decision already made. Optional. */
62
62
  replaceMessage?(conversation: string, ts: string, text: string): Promise<void>;
63
+ /** Takes a message's buttons away and leaves its text. Optional. */
64
+ removeButtons?(conversation: string, ts: string): Promise<void>;
63
65
  }
@@ -92,6 +92,11 @@ export function createTelegramConnector(botToken, agentDir) {
92
92
  if (!edited.ok)
93
93
  console.error('[loopengine] Telegram editMessageText failed:', edited.description);
94
94
  },
95
+ async removeButtons(conversation, ts) {
96
+ const edited = await callTelegram(botToken, 'editMessageReplyMarkup', { chat_id: conversation, message_id: Number(ts), reply_markup: { inline_keyboard: [] } });
97
+ if (!edited.ok)
98
+ console.error('[loopengine] Telegram editMessageReplyMarkup failed:', edited.description);
99
+ },
95
100
  };
96
101
  }
97
102
  /** Stops a clicked button's spinner, with a short note when there's one. */
@@ -51,6 +51,9 @@ export interface DecisionOutcome {
51
51
  morePending?: boolean;
52
52
  /** The agent's reply once the run finished. */
53
53
  text?: string;
54
+ /** The run came from a job thread, which gets the run's own next
55
+ * request or result (core/messaging/jobs.ts), so nothing is added. */
56
+ inJob?: boolean;
54
57
  }
55
58
  /** Handles one person's message: a reply in a request's thread gets an
56
59
  * answer; anything else is left alone. */
@@ -63,12 +66,22 @@ export declare function isPlainApproval(text: string): boolean;
63
66
  /** For a decision made outside the thread (the request's own buttons):
64
67
  * replaces the thread's message with buttons, if any, with `text`. */
65
68
  export declare function settleThreadChoice(deps: MessagingDeps, pendingId: string, text: string): Promise<void>;
69
+ /** For a decision made away from the chat (the web link): replaces the
70
+ * request message, and any message with buttons in its thread, with
71
+ * `text`, so nobody acts on it there. Nothing when it wasn't posted in
72
+ * a chat. */
73
+ export declare function settleRequest(deps: MessagingDeps, pendingId: string, text: string): Promise<void>;
66
74
  /** A click on one of the engine's own buttons (Approve as changed, Keep
67
75
  * original, Confirm, Cancel) — the caller has already checked the
68
76
  * person may decide. Returns what the clicked message should now say. */
69
77
  export declare function handleMessagingAction(action: Exclude<MessagingAction, 'deny'>, pendingId: string, user: string, deps: MessagingDeps): Promise<string>;
70
78
  /** What to say in the thread once a decision is recorded. */
71
79
  export declare function outcomeText(decision: 'approve' | 'deny' | 'answer', who: string, outcome: DecisionOutcome, answer?: string): string;
80
+ /** What to add in the thread once a decision said there is in, if
81
+ * anything: nothing when the agent sent a new request, which speaks
82
+ * for itself (and is already above this), or when the run's job thread
83
+ * gets its outcome from the job. */
84
+ export declare function followUpText(outcome: DecisionOutcome): string | undefined;
72
85
  /** The thread as chat messages: the agent's own replies as `assistant`,
73
86
  * people's as `user` (with who said it), the request itself left out
74
87
  * because the prompt already describes it. The newest message is
@@ -105,9 +105,14 @@ export async function handleInboundMessage(message, deps) {
105
105
  ]);
106
106
  return;
107
107
  }
108
- const outcome = await deps.decide(link.pendingId, verdict.decision === 'answer' ? { kind: 'answer', answer: verdict.answer } : { kind: 'deny' });
109
108
  const answer = verdict.decision === 'answer' ? connector.escape(verdict.answer) : undefined;
110
- await say(outcomeText(verdict.decision, who, outcome, answer));
109
+ // Said before the decision goes in: the run carries on inside
110
+ // deps.decide and may post its next request before it returns.
111
+ await say(verdict.decision === 'deny' ? `Denied by ${who}. Letting the agent know…` : `Answered by ${who}: "${answer}". The agent is carrying on…`);
112
+ const outcome = await deps.decide(link.pendingId, verdict.decision === 'answer' ? { kind: 'answer', answer: verdict.answer } : { kind: 'deny' });
113
+ const after = followUpText(outcome);
114
+ if (after)
115
+ await say(after);
111
116
  if (!outcome.error && !outcome.alreadyResolved) {
112
117
  const what = link.kind === 'approval' ? `\`${item.tool}\`` : 'The question';
113
118
  await replaceRequest(connector, link, `${what} was ${verdict.decision === 'deny' ? 'denied' : `answered ("${answer}")`} by ${who} in the thread.`);
@@ -199,7 +204,9 @@ async function runApproved(deps, link, tool, args, who) {
199
204
  const edited = Boolean(link.proposedArgs);
200
205
  await connector.postInThread(link.conversation, link.ts, `Approved${edited ? ' as changed' : ''} by ${who}. Running \`${tool}\` with:\n${formatArgs(args, connector.escape, await deps.toolSchema(tool))}`);
201
206
  const outcome = await deps.decide(link.pendingId, { kind: 'approve', ...(edited ? { editedArgs: args } : {}) });
202
- await connector.postInThread(link.conversation, link.ts, outcomeText('approve', who, outcome));
207
+ const after = followUpText(outcome);
208
+ if (after)
209
+ await connector.postInThread(link.conversation, link.ts, after);
203
210
  if (!outcome.error && !outcome.alreadyResolved) {
204
211
  await replaceRequest(connector, link, `\`${tool}\` was approved${edited ? ' as changed' : ''} by ${who} in the thread.`);
205
212
  await settleChoice(deps, link, `Approved${edited ? ' as changed' : ''} by ${who}.`);
@@ -229,10 +236,24 @@ export async function settleThreadChoice(deps, pendingId, text) {
229
236
  if (link)
230
237
  await settleChoice(deps, link, text);
231
238
  }
239
+ /** For a decision made away from the chat (the web link): replaces the
240
+ * request message, and any message with buttons in its thread, with
241
+ * `text`, so nobody acts on it there. Nothing when it wasn't posted in
242
+ * a chat. */
243
+ export async function settleRequest(deps, pendingId, text) {
244
+ const link = findThreadByPending(deps.agentDir, pendingId);
245
+ if (!link || link.app !== deps.connector.app)
246
+ return;
247
+ await replaceRequest(deps.connector, link, text);
248
+ await settleChoice(deps, link, text);
249
+ }
232
250
  async function replaceRequest(connector, link, text) {
233
251
  if (!connector.replaceMessage)
234
252
  return;
235
253
  await connector.replaceMessage(link.conversation, link.ts, text).catch((err) => console.error('[loopengine] could not update the request message:', err));
254
+ // A long request's buttons are on its last message.
255
+ if (link.buttonsTs && connector.removeButtons)
256
+ await connector.removeButtons(link.conversation, link.buttonsTs).catch((err) => console.error('[loopengine] could not update the request message:', err));
236
257
  }
237
258
  /** A click on one of the engine's own buttons (Approve as changed, Keep
238
259
  * original, Confirm, Cancel) — the caller has already checked the
@@ -275,9 +296,24 @@ export function outcomeText(decision, who, outcome, answer) {
275
296
  if (outcome.stillWaiting)
276
297
  return `${what}. The agent is still waiting on another decision from the same step.`;
277
298
  if (outcome.morePending)
278
- return `${what}. The agent needs another decision; a new request is on its way.`;
299
+ return `${what}. The agent needed another decision and sent a new request.`;
279
300
  return `${what}.${outcome.text ? `\n> ${outcome.text.replace(/\n/g, '\n> ')}` : ''}`;
280
301
  }
302
+ /** What to add in the thread once a decision said there is in, if
303
+ * anything: nothing when the agent sent a new request, which speaks
304
+ * for itself (and is already above this), or when the run's job thread
305
+ * gets its outcome from the job. */
306
+ export function followUpText(outcome) {
307
+ if (outcome.error)
308
+ return `Couldn't record that: ${outcome.error}`;
309
+ if (outcome.alreadyResolved)
310
+ return 'This was already decided elsewhere.';
311
+ if (outcome.stillWaiting)
312
+ return 'The agent is still waiting on another decision from the same step.';
313
+ if (outcome.morePending || outcome.inJob)
314
+ return undefined;
315
+ return outcome.text ? `Done.\n> ${outcome.text.replace(/\n/g, '\n> ')}` : 'Done.';
316
+ }
281
317
  /** The thread as chat messages: the agent's own replies as `assistant`,
282
318
  * people's as `user` (with who said it), the request itself left out
283
319
  * because the prompt already describes it. The newest message is
@@ -14,6 +14,9 @@ export interface ThreadLink {
14
14
  * proposed change, a Confirm), so it can be replaced once the request
15
15
  * is decided and its buttons don't linger. */
16
16
  choiceTs?: string;
17
+ /** A long request goes out as several messages (Telegram), its
18
+ * buttons on the last: that message, when it isn't `ts`. */
19
+ buttonsTs?: string;
17
20
  }
18
21
  /** Appends one request's thread. Never throws: a request that can't be
19
22
  * mapped still works through its buttons and link. */
@@ -12,8 +12,8 @@ function threadsFile(agentDir) {
12
12
  export function recordThread(agentDir, link) {
13
13
  try {
14
14
  mkdirSync(join(agentDir, '.messaging'), { recursive: true });
15
- const { app, conversation, ts, pendingId, kind, proposedArgs, choiceTs } = link;
16
- appendFileSync(threadsFile(agentDir), JSON.stringify({ app, conversation, ts, pendingId, kind, ...(proposedArgs ? { proposedArgs } : {}), ...(choiceTs ? { choiceTs } : {}), at: new Date().toISOString() }) + '\n');
15
+ const { app, conversation, ts, pendingId, kind, proposedArgs, choiceTs, buttonsTs } = link;
16
+ appendFileSync(threadsFile(agentDir), JSON.stringify({ app, conversation, ts, pendingId, kind, ...(proposedArgs ? { proposedArgs } : {}), ...(choiceTs ? { choiceTs } : {}), ...(buttonsTs ? { buttonsTs } : {}), at: new Date().toISOString() }) + '\n');
17
17
  }
18
18
  catch (err) {
19
19
  console.error('[loopengine] could not record the thread:', err instanceof Error ? err.message : err);
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export { listDeliveries, recordDelivery, type NotifierDelivery } from '#core/not
13
13
  export { describeNotifier } from '#core/http-notifier.js';
14
14
  export { Scheduler, ScheduleError, FileSchedulerStore, getSchedulerStore, setSchedulerStore, createScheduledTask, listScheduledTasks, getScheduledTask, cancelScheduledTask, pauseScheduledTask, resumeScheduledTask, runScheduledTaskNow, setScheduledTaskNotify, deleteScheduledTask, nextScheduledWakeAt, moveScheduledTasksToTimeZone, importLegacyScheduledTasks, parseEvery, describeSchedule, type ScheduledTask, type ScheduledTaskRun, type ScheduledTaskStatus, type Schedule, type SchedulerStore, type FireTask, type CreateScheduledTaskInput } from '#core/scheduler.js';
15
15
  export { NOTIFIER_SLACK_SIGNING_SECRET_VAR } from '#core/notifier-file.js';
16
- export { firstSighting, handleInboundMessage, handleMessagingAction, settleThreadChoice, isPlainApproval, outcomeText, type MessagingDeps, type MessagingDecision, type DecisionOutcome } from '#core/messaging/engine.js';
16
+ export { firstSighting, handleInboundMessage, handleMessagingAction, settleRequest, settleThreadChoice, isPlainApproval, outcomeText, followUpText, type MessagingDeps, type MessagingDecision, type DecisionOutcome } from '#core/messaging/engine.js';
17
17
  export { handleJobMessage, isJobMessage, settleJobThread, jobSessionId, findJobFor, type JobDeps, type JobTurn } from '#core/messaging/jobs.js';
18
18
  export { formatArgs, formatChange, labelFor } from '#core/messaging/format-args.js';
19
19
  export { decideReply, proposeEdit, describeChange, type ReplyDecision, type DecisionRequest } from '#core/messaging/decide.js';
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ export { listDeliveries, recordDelivery } from '#core/notifier-deliveries.js';
15
15
  export { describeNotifier } from '#core/http-notifier.js';
16
16
  export { Scheduler, ScheduleError, FileSchedulerStore, getSchedulerStore, setSchedulerStore, createScheduledTask, listScheduledTasks, getScheduledTask, cancelScheduledTask, pauseScheduledTask, resumeScheduledTask, runScheduledTaskNow, setScheduledTaskNotify, deleteScheduledTask, nextScheduledWakeAt, moveScheduledTasksToTimeZone, importLegacyScheduledTasks, parseEvery, describeSchedule } from '#core/scheduler.js';
17
17
  export { NOTIFIER_SLACK_SIGNING_SECRET_VAR } from '#core/notifier-file.js';
18
- export { firstSighting, handleInboundMessage, handleMessagingAction, settleThreadChoice, isPlainApproval, outcomeText } from '#core/messaging/engine.js';
18
+ export { firstSighting, handleInboundMessage, handleMessagingAction, settleRequest, settleThreadChoice, isPlainApproval, outcomeText, followUpText } from '#core/messaging/engine.js';
19
19
  export { handleJobMessage, isJobMessage, settleJobThread, jobSessionId, findJobFor } from '#core/messaging/jobs.js';
20
20
  export { formatArgs, formatChange, labelFor } from '#core/messaging/format-args.js';
21
21
  export { decideReply, proposeEdit, describeChange } from '#core/messaging/decide.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "loopengine",
3
- "version": "0.3.75",
3
+ "version": "0.3.76",
4
4
  "type": "module",
5
5
  "description": "Runtime for tool-using AI agents with a transparent ReAct loop.",
6
6
  "license": "MIT",