loopengine 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,23 @@
1
+ export const INBOX_VIEWS = ['all', 'needs', 'completed', 'failed', 'archived', 'recent'];
1
2
  export const RECENT_DAYS = 7;
3
+ const SUMMARY_MAX = 240;
4
+ // The last thing the agent said in its own words, from its history.
5
+ function lastAgentText(history) {
6
+ for (let i = history.length - 1; i > 0; i--) {
7
+ const m = history[i];
8
+ if (m.role !== 'assistant')
9
+ continue;
10
+ const blocks = typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : m.content;
11
+ const text = blocks.filter((b) => b.type === 'text' && b.text?.trim()).map((b) => b.text.trim()).join(' ');
12
+ if (text)
13
+ return text;
14
+ }
15
+ return '';
16
+ }
17
+ // Markdown left out, for a line of plain text.
18
+ function plain(text) {
19
+ return text.replace(/```[\s\S]*?```/g, ' ').replace(/\*\*|__|`/g, '').replace(/\*([^*\n]+)\*/g, '$1').replace(/^\s*(#+|>)\s*/gm, '').replace(/\[([^\]]*)\]\(([^)]*)\)/g, '$1');
20
+ }
2
21
  // A case's outcome in words, from its status and the last decision.
3
22
  function outcomeOf(run, waiting) {
4
23
  if (waiting)
@@ -33,6 +52,8 @@ function questionOf(p) {
33
52
  * when anything waits, else recent). `open` is the older name for needs. */
34
53
  export async function listInbox(deps, filter = {}) {
35
54
  const [runs, pending] = await Promise.all([deps.runs(), deps.pending()]);
55
+ const archived = deps.archived?.() ?? {};
56
+ const label = (agent) => deps.agentLabel?.(agent) ?? agent;
36
57
  const bySession = new Map();
37
58
  for (const p of pending)
38
59
  bySession.set(p.sessionId, [...(bySession.get(p.sessionId) ?? []), p]);
@@ -44,37 +65,71 @@ export async function listInbox(deps, filter = {}) {
44
65
  const lastBy = decided.at(-1)?.by;
45
66
  const since = waits.map((p) => p.createdAt).filter((t) => Boolean(t)).sort()[0];
46
67
  const lastActivity = [run.started_at, run.finished_at, decided.at(-1)?.at].filter((t) => Boolean(t)).sort().at(-1);
68
+ const state = waits.length ? 'needs' : run.status === 'error' ? 'failed' : run.status === 'done' ? 'completed' : 'running';
69
+ const question = waits.find((p) => p.kind === 'question');
70
+ const summary = question ? questionOf(question)
71
+ : state === 'failed' ? run.error ?? 'It failed.'
72
+ : state === 'completed' ? run.result ?? outcomeOf(run, false)
73
+ : state === 'running' ? 'Working on it…'
74
+ : `Wants to run ${waits[0].tool}.`;
47
75
  return {
48
- id: run.run_id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, status: run.status,
76
+ id: run.run_id, title: titleOf(run, wfTitle), agent: run.agent, agentLabel: label(run.agent), workflowId: run.workflow_id, workflowTitle: wfTitle, status: run.status, state,
49
77
  waiting: [...new Set(waits.map((p) => p.kind))], startedAt: run.started_at, ...(run.finished_at ? { finishedAt: run.finished_at } : {}), ...(lastBy ? { lastBy } : {}),
50
- ...(waits.length ? { waitingSince: since ?? run.started_at } : {}), lastActivity, outcome: outcomeOf(run, waits.length > 0),
78
+ ...(waits.length ? { waitingSince: since ?? run.started_at } : {}), lastActivity: waits.length && since && since > lastActivity ? since : lastActivity, outcome: outcomeOf(run, waits.length > 0),
79
+ summary: short(plain(summary), SUMMARY_MAX), ...(archived[run.run_id] && !waits.length ? { archived: archived[run.run_id] } : {}),
51
80
  };
52
81
  });
82
+ // An approval it waits on reads best in the agent's own words, from
83
+ // just before it asked ("The content is ready. Please review…").
84
+ await Promise.all(items.map(async (item, i) => {
85
+ if (item.state !== 'needs' || item.waiting.includes('question'))
86
+ return;
87
+ try {
88
+ const said = lastAgentText(await deps.history(runs[i]));
89
+ if (said)
90
+ item.summary = short(plain(said), SUMMARY_MAX);
91
+ }
92
+ catch { }
93
+ }));
53
94
  for (const p of pending) {
54
95
  if (runSessions.has(p.sessionId))
55
96
  continue;
56
97
  const at = p.createdAt ?? new Date(0).toISOString();
57
98
  items.push({
58
- id: OUTSIDE + p.pendingId, title: short(p.kind === 'question' ? questionOf(p) : `Approve ${p.tool}`, 120), agent: p.agent, workflowId: '', workflowTitle: 'Chat',
59
- status: 'awaiting_approval', waiting: [p.kind], startedAt: at, waitingSince: at, lastActivity: at, outcome: 'Waiting',
99
+ id: OUTSIDE + p.pendingId, title: short(p.kind === 'question' ? questionOf(p) : `Approve ${p.tool}`, 120), agent: p.agent, agentLabel: label(p.agent), workflowId: '', workflowTitle: 'Chat',
100
+ status: 'awaiting_approval', state: 'needs', waiting: [p.kind], startedAt: at, waitingSince: at, lastActivity: at, outcome: 'Waiting',
101
+ summary: short(plain(p.kind === 'question' ? questionOf(p) : `Wants to run ${p.tool}.`), SUMMARY_MAX),
60
102
  });
61
103
  }
62
104
  const open = items.filter((i) => i.waiting.length).length;
63
- const view = filter.open || filter.view === 'needs' ? 'needs' : filter.view === 'recent' ? 'recent' : open ? 'needs' : 'recent';
105
+ // None asked: Needs attention when anything waits, else All.
106
+ const view = filter.open ? 'needs' : filter.view && filter.view !== 'auto' ? filter.view : open ? 'needs' : 'all';
107
+ const inView = (i, v) => v === 'needs' ? i.state === 'needs'
108
+ : v === 'archived' ? Boolean(i.archived)
109
+ : v === 'recent' ? !i.waiting.length && i.lastActivity >= recentSince
110
+ : !i.archived && (v === 'all' || (v === 'completed' && i.state === 'completed') || (v === 'failed' && i.state === 'failed'));
64
111
  const recentSince = new Date((filter.now ?? Date.now()) - RECENT_DAYS * 24 * 60 * 60 * 1000).toISOString();
65
112
  const q = filter.q?.trim().toLowerCase();
66
113
  const runParams = new Map(runs.map((r) => [r.run_id, Object.values(r.params ?? {}).join(' ')]));
114
+ const matches = (i) => (!filter.workflow || i.workflowId === filter.workflow) &&
115
+ (!q || `${i.title} ${i.agent} ${i.agentLabel} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''} ${i.outcome} ${i.summary}`.toLowerCase().includes(q));
116
+ const counts = { all: 0, needs: 0, completed: 0, failed: 0, archived: 0 };
117
+ for (const i of items.filter(matches))
118
+ for (const v of Object.keys(counts))
119
+ if (inView(i, v))
120
+ counts[v]++;
67
121
  const shown = items
68
- .filter((i) => (view === 'needs' ? i.waiting.length > 0 : !i.waiting.length && i.lastActivity >= recentSince))
69
- .filter((i) => !filter.workflow || i.workflowId === filter.workflow)
70
- .filter((i) => !q || `${i.title} ${i.agent} ${i.workflowTitle} ${runParams.get(i.id) ?? ''} ${i.lastBy ?? ''} ${i.outcome}`.toLowerCase().includes(q))
71
- // Waiting: the longest-waiting first. Recent: the latest first.
72
- .sort((a, b) => (view === 'needs' ? (a.waitingSince ?? '').localeCompare(b.waitingSince ?? '') : b.lastActivity.localeCompare(a.lastActivity)));
122
+ .filter((i) => inView(i, view) && matches(i))
123
+ // Needs attention: the longest-waiting first. All: what waits on a
124
+ // person first, then the latest. The rest: the latest first.
125
+ .sort((a, b) => view === 'needs' ? (a.waitingSince ?? '').localeCompare(b.waitingSince ?? '')
126
+ : view === 'all' ? Number(b.state === 'needs') - Number(a.state === 'needs') || b.lastActivity.localeCompare(a.lastActivity)
127
+ : b.lastActivity.localeCompare(a.lastActivity));
73
128
  // Every workflow with a case, whatever the filter, for the workflow picker.
74
129
  const workflows = [...new Map(items.filter((i) => i.workflowId).map((i) => [i.workflowId, i.workflowTitle])).entries()]
75
130
  .map(([id, title]) => ({ id, title }))
76
131
  .sort((a, b) => a.title.localeCompare(b.title));
77
- return { items: shown.slice(0, filter.limit ?? 200), open, view, workflows };
132
+ return { items: shown.slice(0, filter.limit ?? 200), open, view, counts, workflows };
78
133
  }
79
134
  /** What the agent did, in order: its words, the tools it used with what
80
135
  * came back, and the questions it asked with their answers. The run's
@@ -178,5 +233,9 @@ export async function getInboxCase(deps, id) {
178
233
  }
179
234
  const { session_id: _s, message: _m, callbacks: _c, ...shown } = run;
180
235
  const totals = totalsOf(run, usage);
181
- return { id, title: titleOf(run, wfTitle), agent: run.agent, workflowId: run.workflow_id, workflowTitle: wfTitle, run: shown, pending: waits, steps, ...(totals ? { totals } : {}) };
236
+ const archived = waits.length ? undefined : deps.archived?.()[id];
237
+ return {
238
+ id, title: titleOf(run, wfTitle), agent: run.agent, agentLabel: deps.agentLabel?.(run.agent) ?? run.agent, ...(archived ? { archived } : {}),
239
+ workflowId: run.workflow_id, workflowTitle: wfTitle, run: shown, pending: waits, steps, ...(totals ? { totals } : {}),
240
+ };
182
241
  }
@@ -0,0 +1,4 @@
1
+ import type { InboxArchived } from './inbox-admin.js';
2
+ export declare function readArchived(projectDir: string): Record<string, InboxArchived>;
3
+ /** Archives the cases (`archived` true) or brings them back. */
4
+ export declare function setArchived(projectDir: string, ids: string[], archived: boolean, by?: string): Record<string, InboxArchived>;
@@ -0,0 +1,36 @@
1
+ // The Inbox's archive: the cases a person put away, so All, Completed and
2
+ // Failed show what's still worth a look. Shared by the workspace, kept in
3
+ // the project at .loopengine/inbox-archive.json as { <case id>: { at, by } }.
4
+ // A case that's waiting on a person is never hidden: it shows in Needs
5
+ // attention archived or not.
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ const archivePath = (projectDir) => join(projectDir, '.loopengine', 'inbox-archive.json');
9
+ export function readArchived(projectDir) {
10
+ const path = archivePath(projectDir);
11
+ if (!existsSync(path))
12
+ return {};
13
+ try {
14
+ const data = JSON.parse(readFileSync(path, 'utf8'));
15
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
16
+ }
17
+ catch {
18
+ return {};
19
+ }
20
+ }
21
+ /** Archives the cases (`archived` true) or brings them back. */
22
+ export function setArchived(projectDir, ids, archived, by) {
23
+ const all = readArchived(projectDir);
24
+ const at = new Date().toISOString();
25
+ for (const id of ids) {
26
+ if (archived)
27
+ all[id] = { at, ...(by ? { by } : {}) };
28
+ else
29
+ delete all[id];
30
+ }
31
+ const path = archivePath(projectDir);
32
+ mkdirSync(dirname(path), { recursive: true });
33
+ writeFileSync(`${path}.tmp`, JSON.stringify(all, null, 2) + '\n');
34
+ renameSync(`${path}.tmp`, path);
35
+ return all;
36
+ }