@thready-web/dsh-bot-plugin 0.1.0-beta.7 → 0.1.0-beta.8

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/context.js CHANGED
@@ -25,6 +25,7 @@ export const CHAT = [
25
25
  'The host attaches recent main-session dialogue to the ticket, and the worker reads that log directly with no authorization prompt. Write the task in the briefing. Do not paste the transcript.',
26
26
  'Workers usually have file tools (read, write, edit, working_directory) and foundations_report. They often do not have bash or other command tools. Assign work the worker can actually do. If a worker reports it is blocked because it has no command tools, do not dispatch that same command-only task to another worker with the same tools, and do not silently finish the job in the main session; tell the user the blockage.',
27
27
  'foundations_dispatch may return status=accepted (received, and possibly waiting for a slot), status=enqueued (placed on the execution queue, not started), or a BUDGET error when both the slot cap and the queue cap are full. accepted or enqueued is not completion and not started. Say in one sentence that the work is in the background, then end the turn. Do not sleep, poll, or keep calling tools while waiting.',
28
+ "When the user asks how an unfinished ticket is progressing, call foundations_worker_history once and answer from that excerpt. Do not call it in a loop and do not sleep. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files or finish the task. If the excerpt is empty, say there is no execution record yet.",
28
29
  "A ticket notice is not something the user said. On progress or artifact notices, do not take over the work and do not poll. On a question, answer or call foundations_supply. On a budget-extension notice, call foundations_grant with enough to exceed current usage, then end the turn. You cannot refuse a worker budget. Do not take over the worker's task: do not inspect, edit, or build its files, and do not run its commands. On a successful result, call foundations_publish, then write the user-visible reply. On a failed result, tell the user the reason and stop. Do not take over the task. Do not treat a later failed status after a published result as if the worker never delivered. Do not invent a final answer or accept the work on the user's behalf before a result. Do not call foundations_retry unless the user explicitly asks.",
29
30
  'If dispatch returns BUDGET, do not start the job yourself and do not keep opening tickets to bypass the cap. Tell the user the host is at its limit.',
30
31
  `On a budget-wait notice, call foundations_grant and add at least one standard slice (${DEFAULT_WORK_BUDGET.workerMaxTokens} tokens and ${DEFAULT_WORK_BUDGET.workerWallMs} ms), or more when current usage is already past granted plus that slice. Grant every time the notice arrives. There is no limit on how many grants and no cumulative ceiling. Do not refuse because earlier grants were many or large. A grant that does not exceed current usage leaves the worker paused, so do not add a token or two. A terminal failed or cancelled ticket cannot be revived by a grant. Do not foundations_dispatch a replacement ticket for the same work. Do not cancel unless the user asks to stop.`,
@@ -278,6 +279,7 @@ export function renderTickets(rows) {
278
279
  return [
279
280
  '[foundations:tickets]',
280
281
  'These are ticket summaries, not the execution transcript, and not a reply the user has already been given.',
282
+ 'Ticket summaries are not the execution record. To see how far a worker has gotten, call foundations_worker_history.',
281
283
  'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
282
284
  'A ticket notice is not something the user said. accepted is not enqueued, and enqueued is not started.',
283
285
  'publish only records an intent to deliver. The words you write next are the reply to the user. Tell the user the result. Do not say accepted, enqueued, or publish.',
@@ -89,6 +89,35 @@ export function renderMainHistory(events, limits = {}) {
89
89
  ...kept,
90
90
  ].join('\n');
91
91
  }
92
+ /**
93
+ * Recent worker activity for the owning main session. Assistant prose and a
94
+ * one-line tool hint are kept. File bodies, command text, and tool results
95
+ * are left out. An empty log returns ''.
96
+ * @param {readonly Record<string, any>[] | null | undefined} events
97
+ * @param {{ maxMessages?: number, maxLine?: number, maxChars?: number }} [limits]
98
+ */
99
+ export function renderWorkerHistory(events, limits = {}) {
100
+ if (!Array.isArray(events) || events.length === 0)
101
+ return '';
102
+ const maxMessages = clampHistory(limits.maxMessages, HISTORY_MESSAGES, 1, 40);
103
+ const maxLine = clampHistory(limits.maxLine, HISTORY_LINE, 200, 4000);
104
+ const maxChars = clampHistory(limits.maxChars, HISTORY_TOTAL, 500, 24000);
105
+ const lines = [];
106
+ for (const event of events) {
107
+ const line = workerHistoryLine(event, maxLine);
108
+ if (line)
109
+ lines.push(line);
110
+ }
111
+ const kept = tailHistory(lines, maxMessages, maxChars);
112
+ if (kept.length === 0)
113
+ return '';
114
+ return [
115
+ '[foundations:worker-history]',
116
+ 'This execution record was read directly from the worker session log. The worker was not notified, and no authorization prompt was raised.',
117
+ "This is not a result. Do not call foundations_publish from it. Do not read, edit, or build the worker's files, and do not finish the task from this excerpt.",
118
+ ...kept,
119
+ ].join('\n');
120
+ }
92
121
  /**
93
122
  * @param {unknown} value
94
123
  * @param {number} fallback
@@ -132,6 +161,100 @@ function isHostNoise(text) {
132
161
  text.startsWith('Current runtime context.') ||
133
162
  text.startsWith('Time sampled'));
134
163
  }
164
+ /**
165
+ * @param {Record<string, any> | null | undefined} event
166
+ * @param {number} maxLine
167
+ */
168
+ function workerHistoryLine(event, maxLine) {
169
+ if (!event)
170
+ return '';
171
+ if (event.type === 'assistant/message') {
172
+ const text = messageBody(event).replace(/\r/g, '').trim();
173
+ if (text === '' || isHostNoise(text))
174
+ return '';
175
+ const line = `assistant: ${text}`;
176
+ return line.length > maxLine ? `${line.slice(0, maxLine)}…` : line;
177
+ }
178
+ if (event.type !== 'tool/call')
179
+ return '';
180
+ const data = event.data;
181
+ if (!data || typeof data !== 'object')
182
+ return '';
183
+ const name = callName(data);
184
+ if (name === '')
185
+ return '';
186
+ const hint = toolHint(name, callArguments(data)).replace(/\s+/g, ' ').trim();
187
+ const line = hint === '' ? `tool ${name}` : `tool ${name} ${hint}`;
188
+ return line.length > maxLine ? `${line.slice(0, maxLine)}…` : line;
189
+ }
190
+ /**
191
+ * @param {Record<string, any>} data
192
+ */
193
+ function callName(data) {
194
+ if (typeof data.name === 'string' && data.name.trim() !== '')
195
+ return data.name.trim();
196
+ if (typeof data.tool === 'string' && data.tool.trim() !== '')
197
+ return data.tool.trim();
198
+ return '';
199
+ }
200
+ /**
201
+ * @param {Record<string, any>} data
202
+ */
203
+ function callArguments(data) {
204
+ const raw = data.arguments ?? data.args ?? data.input;
205
+ if (typeof raw === 'string') {
206
+ try {
207
+ const parsed = JSON.parse(raw);
208
+ return parsed && typeof parsed === 'object' ? parsed : {};
209
+ }
210
+ catch {
211
+ return {};
212
+ }
213
+ }
214
+ return raw && typeof raw === 'object' ? raw : {};
215
+ }
216
+ /**
217
+ * A path, or a bash description. Never the file body or the command text.
218
+ * @param {string} name
219
+ * @param {Record<string, any>} args
220
+ */
221
+ function toolHint(name, args) {
222
+ const path = firstString(args.file_path, args.filePath, args.path);
223
+ if (path !== '')
224
+ return path;
225
+ if (name === 'bash' || typeof args.command === 'string')
226
+ return firstString(args.description);
227
+ return '';
228
+ }
229
+ /**
230
+ * @param {unknown[]} values
231
+ */
232
+ function firstString(...values) {
233
+ for (const value of values) {
234
+ if (typeof value === 'string' && value.trim() !== '')
235
+ return value.trim();
236
+ }
237
+ return '';
238
+ }
239
+ /**
240
+ * @param {string[]} lines
241
+ * @param {number} maxMessages
242
+ * @param {number} maxChars
243
+ */
244
+ function tailHistory(lines, maxMessages, maxChars) {
245
+ const tail = lines.slice(-maxMessages);
246
+ const kept = [];
247
+ let used = 0;
248
+ for (let index = tail.length - 1; index >= 0; index -= 1) {
249
+ const line = tail[index] ?? '';
250
+ const next = used + line.length + (kept.length > 0 ? 1 : 0);
251
+ if (kept.length > 0 && next > maxChars)
252
+ break;
253
+ kept.unshift(line);
254
+ used = next;
255
+ }
256
+ return kept;
257
+ }
135
258
  /**
136
259
  * @param {string[]} lines
137
260
  */
package/dist/work-mock.js CHANGED
@@ -53,6 +53,9 @@ export function createMockWorld() {
53
53
  const slot = session(sessionId);
54
54
  return append(slot, 'tool/call', { name, arguments: args });
55
55
  },
56
+ record(sessionId, type, data) {
57
+ return append(session(sessionId), type, data);
58
+ },
56
59
  assistant(sessionId, text) {
57
60
  const slot = session(sessionId);
58
61
  return append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
@@ -106,6 +106,25 @@ export function workToolDefinitions(work, engine) {
106
106
  },
107
107
  required: ['resultEventId'],
108
108
  }, (args, hostId) => work.reject(hostId, args), 'bot'),
109
+ tool('foundations_worker_history', "Read the worker session log for a ticket this main session owns. The host queries that log directly. The worker is not notified and no authorization prompt is raised. Call it once when the user asks how an unfinished ticket is progressing. The excerpt is not a result: do not call foundations_publish from it, and do not read, edit, or build the worker's files. Omit ticketId only when this session has one unfinished ticket. When several are unfinished, the result lists their ids and does not include a log.", {
110
+ type: 'object',
111
+ properties: {
112
+ ticketId: {
113
+ type: 'string',
114
+ description: 'Ticket to read. Omit only when one unfinished ticket is open.',
115
+ },
116
+ maxChars: {
117
+ type: 'integer',
118
+ description: 'Optional cap for the returned excerpt, from 500 to 24000. Omit it for the default excerpt.',
119
+ },
120
+ },
121
+ }, async (args, hostId) => {
122
+ const maxChars = Number(args.maxChars);
123
+ return work.workerHistory(hostId, {
124
+ ...(typeof args.ticketId === 'string' ? { ticketId: args.ticketId } : {}),
125
+ ...(Number.isFinite(maxChars) ? { maxChars } : {}),
126
+ });
127
+ }, 'bot'),
109
128
  tool('foundations_main_history', 'Read the main session that owns this ticket. The host queries the session log directly and does not raise an authorization prompt. Use it when the attached excerpt is missing a line you need. Do not write the main session.', {
110
129
  type: 'object',
111
130
  properties: {
@@ -3,8 +3,9 @@ import { sha256 } from "./fs-safe.js";
3
3
  import { toolError } from "./errors.js";
4
4
  import { createTicketBook } from "./work-tickets.js";
5
5
  import { decideAdmission, budgetTrip, estimateWorkerBudget, DEFAULT_WORK_BUDGET, effectiveWorkLimits, } from "./work-admit.js";
6
- import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, } from "./work-ledger.js";
6
+ import { messageIdOf, pushInput, pushNotice, reasonKindOf, reconcileInputs, reconcileNotices, renderMainHistory, renderNotice, renderWorkerHistory, } from "./work-ledger.js";
7
7
  const KINDS = new Set(['progress', 'question', 'artifact', 'result', 'failure']);
8
+ const OPEN_TICKET_STATUSES = ['accepted', 'enqueued', 'started', 'needs_user', 'ready'];
8
9
  const LABEL = {
9
10
  accepted: 'accepted',
10
11
  enqueued: 'enqueued',
@@ -80,6 +81,7 @@ export function createWorkRuntime(store, engine, options = {}) {
80
81
  reject,
81
82
  report,
82
83
  mainHistory,
84
+ workerHistory,
83
85
  holdNotices,
84
86
  releaseHold,
85
87
  tick,
@@ -135,6 +137,76 @@ export function createWorkRuntime(store, engine, options = {}) {
135
137
  const events = await options.snapshot(ownerSessionId);
136
138
  return renderMainHistory(events);
137
139
  }
140
+ /**
141
+ * Direct read of a worker session owned by this main bot. No inbox write,
142
+ * and the worker is not notified.
143
+ * @param {string} sessionId
144
+ * @param {{ ticketId?: unknown, maxChars?: number }} [args]
145
+ */
146
+ async function workerHistory(sessionId, args = {}) {
147
+ if (!engine.isBot(sessionId))
148
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
149
+ const requested = typeof args.ticketId === 'string' ? args.ticketId.trim() : '';
150
+ let ticket = null;
151
+ if (requested !== '') {
152
+ ticket = book.ticket(requested);
153
+ if (!ticket)
154
+ return toolError('NOT_FOUND', 'No such ticket.');
155
+ if (ticket.owner_session_id !== sessionId)
156
+ return toolError('FORBIDDEN', 'Only the main session that owns the ticket can read the worker log.');
157
+ }
158
+ else {
159
+ const rows = openTickets(sessionId);
160
+ if (rows.length === 0)
161
+ return toolError('NOT_FOUND', 'No unfinished ticket.');
162
+ if (rows.length > 1) {
163
+ return {
164
+ ok: true,
165
+ direct: true,
166
+ tickets: rows.map(row => ({ ticketId: row.id, status: row.status })),
167
+ text: '',
168
+ };
169
+ }
170
+ ticket = rows[0] ?? null;
171
+ }
172
+ if (!ticket)
173
+ return toolError('NOT_FOUND', 'No such ticket.');
174
+ const child = typeof ticket.child_session_id === 'string' ? ticket.child_session_id : '';
175
+ if (child === '') {
176
+ return {
177
+ ok: true,
178
+ direct: true,
179
+ ticketId: ticket.id,
180
+ status: ticket.status,
181
+ childSessionId: null,
182
+ text: '',
183
+ };
184
+ }
185
+ if (!options.snapshot)
186
+ return toolError('UNAVAILABLE', 'The host cannot read the worker session log.');
187
+ const events = await options.snapshot(child);
188
+ const limits = Number.isFinite(args.maxChars) ? { maxChars: args.maxChars } : undefined;
189
+ return {
190
+ ok: true,
191
+ direct: true,
192
+ ticketId: ticket.id,
193
+ status: ticket.status,
194
+ childSessionId: child,
195
+ text: renderWorkerHistory(events, limits),
196
+ };
197
+ }
198
+ /**
199
+ * @param {string} owner
200
+ */
201
+ function openTickets(owner) {
202
+ return store.db
203
+ .prepare(`
204
+ SELECT * FROM work_tickets
205
+ WHERE owner_session_id = ? AND status IN (${OPEN_TICKET_STATUSES.map(() => '?').join(',')})
206
+ ORDER BY updated_at DESC
207
+ `)
208
+ .all(owner, ...OPEN_TICKET_STATUSES);
209
+ }
138
210
  /**
139
211
  * A running slot is free when both the per-bot and global running caps have room.
140
212
  * needs_user does not occupy a running slot.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thready-web/dsh-bot-plugin",
3
- "version": "0.1.0-beta.7",
3
+ "version": "0.1.0-beta.8",
4
4
  "type": "module",
5
5
  "description": "DSH bot plugin: session persona, memory, work, hash routing, and the workbench. Pinned to @deepseek-ai/dsh 0.2.2-rc.1.",
6
6
  "license": "MIT",