@kadaliao/dsh-bots 0.7.0 → 0.8.0

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.
@@ -0,0 +1,221 @@
1
+ /**
2
+ * What a bot is doing right now, for the panel's live status: per Session (a
3
+ * bot's home, a task's), from its `session/event`s. The tool being run with a
4
+ * short summary of its arguments (a command's first line, a file's name, a
5
+ * search's words, the bot work goes to), "thinking" between steps, the step
6
+ * count, and when the turn and the current step began. Tool results are never
7
+ * read; summaries are clipped and scrubbed of anything that looks like a secret.
8
+ *
9
+ * @module @kadaliao/dsh-bots/lib/activity
10
+ */
11
+
12
+ import { redact } from './channels.mjs';
13
+
14
+ /** The longest summary of a tool's arguments. */
15
+ export const DETAIL_MAX = 80;
16
+
17
+ /** A call's arguments as an object: Harness's raw JSON string, or an object already. */
18
+ export function argsOf(raw) {
19
+ if (raw && typeof raw === 'object') return raw;
20
+ try {
21
+ const v = JSON.parse(String(raw ?? ''));
22
+ return v && typeof v === 'object' ? v : {};
23
+ } catch {
24
+ return {};
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Text bound for the page with secrets taken out: the channel tokens it knows (`secrets`), the
30
+ * shapes of common keys and tokens, and the value of anything named like a key, token, secret or
31
+ * password (`API_KEY=…`, `--token …`, `Authorization: Bearer …`).
32
+ */
33
+ export function scrub(text, secrets = []) {
34
+ return redact(String(text ?? ''), secrets)
35
+ .replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi, '$1 <redacted>')
36
+ // `NAME=value`, `name: value`, or a flag and its value (`--token abc`); a plain word before a space is no name.
37
+ .replace(/(^|[\s"'`;&|(,{])(-{0,2}[A-Za-z0-9_.-]*?(?:key|token|secret|passw(?:or)?d|pwd|credentials?|auth(?:orization)?)["']?)(\s*[=:]\s*|\s+)("[^"]*"|'[^']*'|[^\s"'`;&|),}]+)/gi, (all, pre, name, sep, value) =>
38
+ value === '<redacted>' || (!/[=:]/.test(sep) && !name.startsWith('-')) ? all : `${pre}${name}${sep}<redacted>`,
39
+ )
40
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, '<redacted>')
41
+ .replace(/\b(?:gh[pousr]|github_pat|glpat|xox[abprs])[_-][A-Za-z0-9_-]{10,}/g, '<redacted>')
42
+ .replace(/\bAKIA[0-9A-Z]{12,}\b/g, '<redacted>')
43
+ .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, '<redacted>')
44
+ .replace(/(\/\/[^/\s:@]+:)[^@\s/]+@/g, '$1<redacted>@');
45
+ }
46
+
47
+ /** `text` on one line, at most `max` characters (an ellipsis marks a cut). */
48
+ export function clipLine(text, max = DETAIL_MAX) {
49
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
50
+ return [...s].length > max ? `${[...s].slice(0, max - 1).join('').trimEnd()}…` : s;
51
+ }
52
+
53
+ const first = (args, keys) => {
54
+ for (const k of keys) {
55
+ const v = args?.[k];
56
+ if (typeof v === 'string' && v.trim()) return v.trim();
57
+ }
58
+ return '';
59
+ };
60
+ const baseName = (path) => String(path).replace(/[\\/]+$/, '').split(/[\\/]/).pop() || String(path);
61
+ const firstLine = (text) => (String(text).split('\n').find((l) => l.trim() !== '') ?? '').trim();
62
+ function hostPath(url) {
63
+ try {
64
+ const u = new URL(url);
65
+ return `${u.host}${u.pathname === '/' ? '' : u.pathname}`;
66
+ } catch {
67
+ return String(url);
68
+ }
69
+ }
70
+
71
+ /** Tool names (or their last `__` part, for an MCP tool) by what the panel says they do. */
72
+ const SHELL = new Set(['bash', 'pwsh', 'shell', 'sh', 'terminal', 'exec', 'run_command', 'execute_command']);
73
+ const READ = new Set(['read', 'read_file', 'read_image', 'view', 'open_file', 'cat']);
74
+ const EDIT = new Set(['edit', 'str_replace', 'str_replace_editor', 'str_replace_based_edit_tool', 'multi_edit', 'multiedit', 'apply_patch', 'patch', 'notebook_edit']);
75
+ const WRITE = new Set(['write', 'write_file', 'create_file']);
76
+ const FIND = new Set(['grep', 'glob', 'ls', 'find', 'search_files', 'list_files', 'list_directory', 'ripgrep']);
77
+ const SEARCH = new Set(['web_search', 'search', 'websearch', 'tavily_search', 'exa_search', 'brave_search', 'google_search']);
78
+ const FETCH = new Set(['web_fetch', 'fetch', 'webfetch', 'browse', 'open_url']);
79
+
80
+ /**
81
+ * A tool call as the panel shows it: `{tool, detail}`, `tool` the call's name (clipped) and
82
+ * `detail` a short summary of what it works on, when the tool is one the panel knows and the
83
+ * summary tells something: a command's first line, a file's name, a search's words, a page's host
84
+ * and path, the bot work is handed to, a skill's name. Other tools get no detail (their arguments
85
+ * may hold anything). `handleOf(ref)` turns a `to` into the bot's @handle when it can.
86
+ * @param {string} name
87
+ * @param {object|string} rawArgs
88
+ * @param {{secrets?: string[], handleOf?: (ref: string) => string}} [opts]
89
+ * @returns {{tool: string, detail?: string}}
90
+ */
91
+ export function summarizeCall(name, rawArgs, opts = {}) {
92
+ const tool = clipLine(String(name ?? 'tool'), 60) || 'tool';
93
+ const args = argsOf(rawArgs);
94
+ const short = tool.toLowerCase().split('__').pop();
95
+ let detail = '';
96
+ if (SHELL.has(short)) detail = firstLine(first(args, ['command', 'cmd', 'script', 'commands']));
97
+ else if (READ.has(short) || EDIT.has(short) || WRITE.has(short)) detail = baseName(first(args, ['path', 'file_path', 'filePath', 'file', 'filename', 'notebook_path', 'target']));
98
+ else if (FIND.has(short)) detail = first(args, ['pattern', 'query', 'glob', 'path', 'dir', 'directory']);
99
+ else if (SEARCH.has(short)) detail = first(args, ['query', 'q', 'search', 'keywords']) || (Array.isArray(args.queries) ? args.queries.filter((q) => typeof q === 'string').join(' · ') : '');
100
+ else if (FETCH.has(short)) detail = hostPath(first(args, ['url', 'uri', 'href']));
101
+ else if (short === 'bot_send_message') {
102
+ const to = first(args, ['to']);
103
+ if (to) detail = opts.handleOf?.(to) || (to.startsWith('@') ? to : `@${to}`);
104
+ else if (first(args, ['ticket'])) detail = `#${first(args, ['ticket']).replace(/^(?:ticket|task)\//, '')}`;
105
+ } else if (short === 'skill' || short === 'load_skill') detail = first(args, ['name', 'skill']);
106
+ else if (short === 'memory_search') detail = first(args, ['query', 'q']);
107
+ else if (short === 'bot_recall') detail = first(args, ['ref']);
108
+ else if (short === 'subagent' || short === 'task' || short === 'agent') detail = first(args, ['description', 'title', 'name']);
109
+ detail = clipLine(scrub(detail, opts.secrets ?? []));
110
+ return detail ? { tool, detail } : { tool };
111
+ }
112
+
113
+ /**
114
+ * Activity per Session, fed with its `session/event`s (`note`) and an idle Agent (`clear`).
115
+ * `get(sessionId)` is `{kind: 'thinking'|'tool'|'writing', tool?, detail?, startedAt, stepAt, steps}`
116
+ * while a turn runs, else undefined: `startedAt` the turn's start, `stepAt` the current activity's,
117
+ * `steps` the model calls so far in the turn.
118
+ * @param {{now?: () => number, secrets?: () => string[], handleOf?: (ref: string) => string}} [opts]
119
+ */
120
+ export function createActivity(opts = {}) {
121
+ const now = opts.now ?? Date.now;
122
+ /** sessionId → {kind, tool?, detail?, startedAt, stepAt, steps, sawStep, calls: Map(callId → {tool, detail, at})} */
123
+ const live = new Map();
124
+ const summarize = (name, args) => summarizeCall(name, args, { secrets: opts.secrets?.() ?? [], handleOf: opts.handleOf });
125
+ const fresh = (at) => ({ kind: 'thinking', startedAt: at, stepAt: at, steps: 0, sawStep: false, calls: new Map() });
126
+ /** The Session's record, begun now when a turn was already under way before this process heard of it. */
127
+ const ensure = (sessionId, at) => live.get(sessionId) ?? live.set(sessionId, fresh(at)).get(sessionId);
128
+ /** Back to thinking, or to the latest call still running. */
129
+ const settle = (rec, at) => {
130
+ const calls = [...rec.calls.values()];
131
+ const last = calls.at(-1);
132
+ if (last) Object.assign(rec, { kind: 'tool', tool: last.tool, detail: last.detail, stepAt: last.at });
133
+ else {
134
+ Object.assign(rec, { kind: 'thinking', stepAt: at });
135
+ delete rec.tool;
136
+ delete rec.detail;
137
+ }
138
+ };
139
+ const call = (rec, id, name, args, at) => {
140
+ const s = summarize(name, args);
141
+ const key = id || `${name}:${rec.calls.size}:${at}`;
142
+ if (rec.calls.has(key)) return;
143
+ rec.calls.set(key, { tool: s.tool, detail: s.detail, at });
144
+ Object.assign(rec, { kind: 'tool', tool: s.tool, stepAt: at });
145
+ if (s.detail) rec.detail = s.detail;
146
+ else delete rec.detail;
147
+ };
148
+ return {
149
+ /** One event of `sessionId`; returns whether the activity changed. */
150
+ note(sessionId, event) {
151
+ if (!sessionId || !event?.type) return false;
152
+ const at = now();
153
+ const d = event.data ?? {};
154
+ switch (event.type) {
155
+ case 'turn/start':
156
+ live.set(sessionId, fresh(at));
157
+ return true;
158
+ case 'turn/end':
159
+ return live.delete(sessionId);
160
+ case 'step/start': {
161
+ const rec = ensure(sessionId, at);
162
+ rec.sawStep = true;
163
+ rec.steps += 1;
164
+ rec.calls.clear();
165
+ settle(rec, at);
166
+ return true;
167
+ }
168
+ case 'tool/call': {
169
+ const rec = ensure(sessionId, at);
170
+ call(rec, d.callId, d.name, d.arguments, at);
171
+ return true;
172
+ }
173
+ case 'tool/result': {
174
+ const rec = live.get(sessionId);
175
+ if (!rec) return false;
176
+ const id = d.message?.toolCallId ?? d.toolCallId ?? d.callId;
177
+ if (id && rec.calls.has(id)) rec.calls.delete(id);
178
+ else rec.calls.delete([...rec.calls.keys()][0]);
179
+ settle(rec, at);
180
+ return true;
181
+ }
182
+ case 'assistant/message': {
183
+ const rec = ensure(sessionId, at);
184
+ if (!rec.sawStep) rec.steps += 1;
185
+ const blocks = Array.isArray(d.message?.content) ? d.message.content : [];
186
+ const calls = blocks.filter((b) => b?.type === 'tool-call');
187
+ // Harness reports each call as a `tool/call` too; the message alone (an older Harness) is enough.
188
+ for (const b of calls) call(rec, b.id ?? b.toolCallId ?? b.callId, b.name ?? b.toolName, b.argsRaw ?? b.arguments ?? b.args ?? b.input, at);
189
+ if (calls.length === 0 && blocks.some((b) => b?.type === 'text' && String(b.text ?? '').trim())) {
190
+ Object.assign(rec, { kind: 'writing', stepAt: at });
191
+ delete rec.tool;
192
+ delete rec.detail;
193
+ }
194
+ return true;
195
+ }
196
+ case 'user/message': {
197
+ // Input that starts a turn (or joins one): the bot is about to think.
198
+ const rec = ensure(sessionId, at);
199
+ if (rec.calls.size === 0 && rec.kind !== 'thinking') settle(rec, at);
200
+ return true;
201
+ }
202
+ default:
203
+ return false;
204
+ }
205
+ },
206
+ /** The Agent went idle (or the Session is gone): nothing runs there. */
207
+ clear(sessionId) {
208
+ return live.delete(sessionId);
209
+ },
210
+ /** What `sessionId` does now, for the page; undefined when nothing runs. */
211
+ get(sessionId) {
212
+ const rec = sessionId ? live.get(sessionId) : undefined;
213
+ if (!rec) return undefined;
214
+ return { kind: rec.kind, ...(rec.tool ? { tool: rec.tool } : {}), ...(rec.detail ? { detail: rec.detail } : {}), startedAt: rec.startedAt, stepAt: rec.stepAt, steps: Math.max(1, rec.steps) };
215
+ },
216
+ /** Sessions with something running. */
217
+ sessions() {
218
+ return [...live.keys()];
219
+ },
220
+ };
221
+ }