@restregular/dsh-powerup 0.6.1 → 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.
package/index.js CHANGED
@@ -14,19 +14,27 @@
14
14
  * removed
15
15
  * POST /dsh-powerup/api/job-kill → stops one background job with an
16
16
  * optional human reason
17
+ * tool powerup_step_read → resolves a `dsh-step:` reference
18
+ * copied from the Trajectory menu into
19
+ * the raw session events it identifies
17
20
  *
18
21
  * The Client half drives other plugins' installation through the built-in
19
22
  * `pluginManager` Remote. Only the process restart, the self-update handoff,
20
23
  * and the stop-with-reason kill need Host code: the built-in `job.kill` Remote
21
24
  * hard-codes `cancelled by the user`, while the registry's own `kill` accepts
22
25
  * a reason that settlement merges into the job's `detail` line.
26
+ *
27
+ * The step-reference tool reads `ctx.sessionQuery`; both the reference codec
28
+ * and the tool spec live in `lib/` so offline tests can exercise them.
23
29
  */
24
30
 
25
31
  import { randomUUID } from 'node:crypto';
26
32
  import { appendFileSync, mkdirSync, readFileSync, statSync } from 'node:fs';
27
33
  import { dirname, join } from 'node:path';
28
34
  import { homedir } from 'node:os';
35
+ import { defineTool } from '@deepseek-ai/dsh-tools';
29
36
  import { describeRestart, requestRestart } from './lib/restart.js';
37
+ import { createStepReadTool } from './lib/step-tool.js';
30
38
 
31
39
  /** Prefix owned by this plugin. */
32
40
  const ROUTE = '/dsh-powerup/api';
@@ -451,7 +459,9 @@ async function handle(req, res, ctx) {
451
459
  }
452
460
 
453
461
  /**
454
- * Mount the restart and self-update routes once the Web server exists.
462
+ * Mount the restart and self-update routes once the Web server exists, and
463
+ * register the step-reference reader once both the tool registry and the
464
+ * session-query service are composed.
455
465
  * @param {import('@deepseek-ai/cordis').Context} ctx
456
466
  */
457
467
  export function apply(ctx) {
@@ -468,6 +478,17 @@ export function apply(ctx) {
468
478
  'dsh-powerup: restart and self-update routes',
469
479
  );
470
480
  });
481
+ ctx.inject(['tools', 'sessionQuery'], (scope) => {
482
+ const tools = scope.get('tools');
483
+ if (tools === undefined || typeof tools.register !== 'function') return;
484
+ scope.effect(
485
+ () => tools.register(createStepReadTool(defineTool, {
486
+ // Re-read the service at call time: the scope owns the live instance.
487
+ getSessionQuery: () => scope.get('sessionQuery'),
488
+ })),
489
+ 'dsh-powerup: step reference reader',
490
+ );
491
+ });
471
492
  }
472
493
 
473
494
  /** Exported for tests only; the Host never reads this. */
@@ -0,0 +1,484 @@
1
+ /**
2
+ * Power-Up step references.
3
+ *
4
+ * A reference copied from the Trajectory context menu has the shape
5
+ *
6
+ * dsh-step:<session-id>/<step-id>
7
+ *
8
+ * and identifies one unit of a session log:
9
+ *
10
+ * turn.<turn>.step.<step> one assistant step: every raw event between
11
+ * `step/start` and `step/end` (assistant message,
12
+ * tool calls, tool results, attempts)
13
+ * call.<call-id> one tool call plus its result
14
+ * seq.<n> one raw event
15
+ * index.<n> a synthetic ledger row with no stable identity
16
+ *
17
+ * The model-facing `powerup_step_read` tool resolves a reference through
18
+ * `ctx.sessionQuery`, so an agent only needs the copied string.
19
+ */
20
+
21
+ /** Reference scheme, including the trailing colon. */
22
+ export const STEP_REF_PREFIX = 'dsh-step:';
23
+
24
+ /** Reference scheme without the separator. */
25
+ export const STEP_REF_SCHEME = 'dsh-step';
26
+
27
+ /** Model-facing tool that resolves these references. */
28
+ export const STEP_READ_TOOL_NAME = 'powerup_step_read';
29
+
30
+ /** Neighbor bound; matches the session-query default `readWindowMax`. */
31
+ export const MAX_CONTEXT_EVENTS = 50;
32
+
33
+ /** The raw event types that snapshot the whole request envelope. */
34
+ const REQUEST_EVENT_TYPES = new Set(['request/header']);
35
+
36
+ /** A reference that cannot be parsed or resolved. */
37
+ export class StepReferenceError extends Error {
38
+ /**
39
+ * @param {string} code stable machine code, included in the message
40
+ * @param {string} message model-readable explanation
41
+ * @param {{ cause?: unknown }} [options]
42
+ */
43
+ constructor(code, message, options = {}) {
44
+ super(`${code}: ${message}`);
45
+ this.name = 'StepReferenceError';
46
+ this.code = code;
47
+ if (options.cause !== undefined) this.cause = options.cause;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Build the reference an agent can paste back into `powerup_step_read`.
53
+ * @param {string} sessionId
54
+ * @param {string} stepId normalized step id
55
+ * @returns {string}
56
+ */
57
+ export function formatStepReference(sessionId, stepId) {
58
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') {
59
+ throw new StepReferenceError('STEP_REF_INVALID', 'a step reference needs a session id');
60
+ }
61
+ if (typeof stepId !== 'string' || stepId.trim() === '') {
62
+ throw new StepReferenceError('STEP_REF_INVALID', 'a step reference needs a step id');
63
+ }
64
+ return `${STEP_REF_PREFIX}${sessionId.trim()}/${stepId.trim()}`;
65
+ }
66
+
67
+ /**
68
+ * Split a reference into its session id and step id.
69
+ * @param {string} ref
70
+ * @returns {{ sessionId: string, stepId: string }}
71
+ */
72
+ export function parseStepReference(ref) {
73
+ if (typeof ref !== 'string') {
74
+ throw new StepReferenceError('STEP_REF_INVALID', 'a step reference is a string copied from the Trajectory menu');
75
+ }
76
+ const text = ref.trim();
77
+ if (!text.toLowerCase().startsWith(STEP_REF_PREFIX)) {
78
+ throw new StepReferenceError(
79
+ 'STEP_REF_INVALID',
80
+ `a step reference starts with ${STEP_REF_PREFIX} (use Copy step reference in the Trajectory menu)`,
81
+ );
82
+ }
83
+ const rest = text.slice(STEP_REF_PREFIX.length);
84
+ const slash = rest.indexOf('/');
85
+ if (slash <= 0 || slash === rest.length - 1) {
86
+ throw new StepReferenceError('STEP_REF_INVALID', 'a step reference is dsh-step:<sessionId>/<stepId>');
87
+ }
88
+ const sessionId = rest.slice(0, slash).trim();
89
+ const stepId = rest.slice(slash + 1).trim();
90
+ if (sessionId === '' || stepId === '') {
91
+ throw new StepReferenceError('STEP_REF_INVALID', 'a step reference is dsh-step:<sessionId>/<stepId>');
92
+ }
93
+ return { sessionId, stepId };
94
+ }
95
+
96
+ /** @param {string} text */
97
+ function canonicalStepId(text) {
98
+ let match = /^turn\.(\d+)\.step\.(\d+)$/u.exec(text);
99
+ if (match !== null) return `turn.${Number(match[1])}.step.${Number(match[2])}`;
100
+ match = /^call\.(.+)$/u.exec(text);
101
+ if (match !== null) {
102
+ let callId = match[1];
103
+ try {
104
+ callId = decodeURIComponent(callId);
105
+ } catch {
106
+ /* Keep the literal text. */
107
+ }
108
+ return `call.${encodeURIComponent(callId)}`;
109
+ }
110
+ match = /^seq\.(\d+)$/u.exec(text);
111
+ if (match !== null) return `seq.${Number(match[1])}`;
112
+ match = /^index\.(\d+)$/u.exec(text);
113
+ if (match !== null) return `index.${Number(match[1])}`;
114
+ return '';
115
+ }
116
+
117
+ /**
118
+ * Turn anything a row exposes — the DOM row key (`encodeURIComponent` of the
119
+ * trajectory record id, optionally with a `\0summary\0` fold suffix), a raw
120
+ * record id, or an already-normalized step id — into the canonical step id.
121
+ * @param {string} value
122
+ * @returns {string} canonical id, or `''` when the value carries no usable identity
123
+ */
124
+ export function normalizeStepId(value) {
125
+ if (typeof value !== 'string') return '';
126
+ const text = value.trim();
127
+ if (text === '') return '';
128
+ const known = canonicalStepId(text);
129
+ if (known !== '') return known;
130
+ let decoded = text;
131
+ try {
132
+ decoded = decodeURIComponent(text);
133
+ } catch {
134
+ /* The value is already raw. */
135
+ }
136
+ const summaryCut = decoded.indexOf('\u0000summary\u0000');
137
+ if (summaryCut !== -1) decoded = decoded.slice(0, summaryCut);
138
+ const parts = decoded.split('\u0000');
139
+ if (parts.length < 3) return '';
140
+ if (parts[0] === 'assistant') {
141
+ // `assistant\0turn\0T\0step\0S` (older shape) and `assistant\0T\0S`.
142
+ const turn = Number(parts[1] === 'turn' ? parts[2] : parts[1]);
143
+ const step = Number(parts[1] === 'turn' ? parts[4] : parts[2]);
144
+ if (Number.isInteger(turn) && Number.isInteger(step) && turn >= 0 && step >= 0) {
145
+ return `turn.${turn}.step.${step}`;
146
+ }
147
+ return '';
148
+ }
149
+ if (parts[1] === 'call' && parts[2] !== '') return `call.${encodeURIComponent(parts[2])}`;
150
+ if (parts[1] === 'seq' && Number.isInteger(Number(parts[2]))) return `seq.${Number(parts[2])}`;
151
+ if (parts[1] === 'index' && Number.isInteger(Number(parts[2]))) return `index.${Number(parts[2])}`;
152
+ return '';
153
+ }
154
+
155
+ /**
156
+ * Parse a canonical step id into the descriptor the resolver understands.
157
+ * @param {string} stepId
158
+ * @returns {{ kind: 'step', turn: number, step: number }
159
+ * | { kind: 'call', callId: string }
160
+ * | { kind: 'seq', seq: number }
161
+ * | { kind: 'index', index: number }
162
+ * | null}
163
+ */
164
+ export function parseStepId(stepId) {
165
+ const normalized = normalizeStepId(stepId);
166
+ if (normalized === '') return null;
167
+ let match = /^turn\.(\d+)\.step\.(\d+)$/u.exec(normalized);
168
+ if (match !== null) return { kind: 'step', turn: Number(match[1]), step: Number(match[2]) };
169
+ match = /^call\.(.+)$/u.exec(normalized);
170
+ if (match !== null) {
171
+ let callId = match[1];
172
+ try {
173
+ callId = decodeURIComponent(callId);
174
+ } catch {
175
+ /* Keep the literal text. */
176
+ }
177
+ return { kind: 'call', callId };
178
+ }
179
+ match = /^seq\.(\d+)$/u.exec(normalized);
180
+ if (match !== null) return { kind: 'seq', seq: Number(match[1]) };
181
+ match = /^index\.(\d+)$/u.exec(normalized);
182
+ if (match !== null) return { kind: 'index', index: Number(match[1]) };
183
+ return null;
184
+ }
185
+
186
+ /**
187
+ * Canonical id for a parsed step descriptor.
188
+ * @param {ReturnType<typeof parseStepId>} step
189
+ * @returns {string}
190
+ */
191
+ export function stepIdOf(step) {
192
+ if (step === null || step === undefined) return '';
193
+ if (step.kind === 'step') return `turn.${step.turn}.step.${step.step}`;
194
+ if (step.kind === 'call') return `call.${encodeURIComponent(step.callId)}`;
195
+ if (step.kind === 'seq') return `seq.${step.seq}`;
196
+ if (step.kind === 'index') return `index.${step.index}`;
197
+ return '';
198
+ }
199
+
200
+ /** @param {unknown} event @param {number} turn @param {number} step */
201
+ function belongsToStep(event, turn, step) {
202
+ const data = event?.data;
203
+ return data !== null && typeof data === 'object' && data.turn === turn && data.step === step;
204
+ }
205
+
206
+ /**
207
+ * The toolCallId a `tool/result` event answers.
208
+ * @param {any} data
209
+ * @returns {string}
210
+ */
211
+ function resultCallId(data) {
212
+ const message = data?.message;
213
+ if (message !== null && typeof message === 'object') {
214
+ if (typeof message.toolCallId === 'string' && message.toolCallId !== '') return message.toolCallId;
215
+ const callId = message.source?.callId;
216
+ if (typeof callId === 'string' && callId !== '') return callId;
217
+ }
218
+ if (typeof data?.callId === 'string' && data.callId !== '') return data.callId;
219
+ return '';
220
+ }
221
+
222
+ /**
223
+ * Depth-bounded scan for a call id, used only for nested sub-calls that never
224
+ * become their own raw `tool/call` event.
225
+ * @param {unknown} value
226
+ * @param {string} callId
227
+ * @param {Set<unknown>} seen
228
+ * @param {number} depth
229
+ * @returns {boolean}
230
+ */
231
+ function mentionsCallId(value, callId, seen, depth) {
232
+ if (depth > 9 || value === null || typeof value !== 'object') return false;
233
+ if (seen.has(value)) return false;
234
+ seen.add(value);
235
+ if (value.callId === callId || value.toolCallId === callId) return true;
236
+ for (const key of Object.keys(value)) {
237
+ if (key === 'schema' || key === 'tools' || key === 'system') continue;
238
+ if (mentionsCallId(value[key], callId, seen, depth + 1)) return true;
239
+ }
240
+ return false;
241
+ }
242
+
243
+ /**
244
+ * Index range of every raw event that belongs to one turn/step.
245
+ * @param {readonly any[]} events
246
+ * @param {number} turn
247
+ * @param {number} step
248
+ * @returns {{ startIndex: number, endIndex: number, resolved: object } | null}
249
+ */
250
+ function findStepRange(events, turn, step) {
251
+ let first = -1;
252
+ let start = -1;
253
+ let end = -1;
254
+ let last = -1;
255
+ for (let index = 0; index < events.length; index += 1) {
256
+ const event = events[index];
257
+ if (!belongsToStep(event, turn, step)) continue;
258
+ if (first === -1) first = index;
259
+ last = index;
260
+ if (event.type === 'step/start' && start === -1) start = index;
261
+ if (event.type === 'step/end') end = index;
262
+ }
263
+ if (first === -1) return null;
264
+ const from = start === -1 ? first : start;
265
+ const to = end === -1 ? last : end;
266
+ return {
267
+ startIndex: Math.min(from, to),
268
+ endIndex: Math.max(from, to),
269
+ resolved: { kind: 'step', turn, step },
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Locate the raw event range behind a parsed step id.
275
+ * @param {readonly any[]} events raw session events, ascending by seq
276
+ * @param {ReturnType<typeof parseStepId>} step
277
+ * @returns {{ startIndex: number, endIndex: number, resolved: object } | null}
278
+ */
279
+ export function resolveStepRange(events, step) {
280
+ if (!Array.isArray(events) || events.length === 0) return null;
281
+ if (step === null || step === undefined) return null;
282
+ if (step.kind === 'index') {
283
+ throw new StepReferenceError(
284
+ 'STEP_REF_SYNTHETIC',
285
+ 'this ledger row has a synthetic index id (no stable event or call identity), so it cannot be resolved',
286
+ );
287
+ }
288
+ if (step.kind === 'seq') {
289
+ const index = events.findIndex((event) => event?.seq === step.seq);
290
+ return index === -1 ? null : { startIndex: index, endIndex: index, resolved: { kind: 'seq', seq: step.seq } };
291
+ }
292
+ if (step.kind === 'call') {
293
+ let callIndex = -1;
294
+ let resultIndex = -1;
295
+ for (let index = 0; index < events.length; index += 1) {
296
+ const event = events[index];
297
+ if (event?.type === 'tool/call' && event.data?.callId === step.callId) {
298
+ if (callIndex === -1) callIndex = index;
299
+ continue;
300
+ }
301
+ if (event?.type === 'tool/result' && resultCallId(event.data) === step.callId) resultIndex = index;
302
+ }
303
+ if (callIndex !== -1 || resultIndex !== -1) {
304
+ const from = callIndex === -1 ? resultIndex : callIndex;
305
+ const to = resultIndex === -1 ? callIndex : Math.max(resultIndex, callIndex);
306
+ const owner = events[from]?.data;
307
+ const resolved = { kind: 'call', callId: step.callId };
308
+ if (Number.isInteger(owner?.turn)) resolved.turn = owner.turn;
309
+ if (Number.isInteger(owner?.step)) resolved.step = owner.step;
310
+ return {
311
+ startIndex: Math.min(from, to),
312
+ endIndex: Math.max(from, to),
313
+ resolved,
314
+ };
315
+ }
316
+ // A nested sub-call (PTC/run_code child) is not its own raw event; fall
317
+ // back to the step that owns it so the step still answers the reference.
318
+ for (let index = 0; index < events.length; index += 1) {
319
+ const event = events[index];
320
+ if (!mentionsCallId(event, step.callId, new Set(), 0)) continue;
321
+ const data = event?.data;
322
+ if (Number.isInteger(data?.turn) && Number.isInteger(data?.step)) {
323
+ const range = findStepRange(events, data.turn, data.step);
324
+ if (range !== null) {
325
+ return {
326
+ startIndex: range.startIndex,
327
+ endIndex: range.endIndex,
328
+ resolved: { kind: 'step', turn: data.turn, step: data.step, viaCallId: step.callId },
329
+ };
330
+ }
331
+ }
332
+ return {
333
+ startIndex: index,
334
+ endIndex: index,
335
+ resolved: { kind: 'event', seq: event.seq, viaCallId: step.callId },
336
+ };
337
+ }
338
+ return null;
339
+ }
340
+ return findStepRange(events, step.turn, step.step);
341
+ }
342
+
343
+ /** @param {unknown} value @param {number} fallback */
344
+ function neighborCount(value, fallback = 0) {
345
+ const number = typeof value === 'number' ? value : Number(value);
346
+ if (!Number.isFinite(number)) return fallback;
347
+ return Math.max(0, Math.min(MAX_CONTEXT_EVENTS, Math.trunc(number)));
348
+ }
349
+
350
+ /**
351
+ * JSON-safe copy: bigint becomes a string and cycles become `[circular]`.
352
+ * @param {unknown} value
353
+ * @param {Set<unknown>} [seen]
354
+ * @returns {unknown}
355
+ */
356
+ export function toJsonSafe(value, seen = new Set()) {
357
+ if (value === null || typeof value !== 'object') {
358
+ return typeof value === 'bigint' ? String(value) : value;
359
+ }
360
+ if (seen.has(value)) return '[circular]';
361
+ seen.add(value);
362
+ if (Array.isArray(value)) return value.map((entry) => toJsonSafe(entry, seen));
363
+ if (value instanceof Map) {
364
+ const out = {};
365
+ for (const [key, entry] of value.entries()) out[String(key)] = toJsonSafe(entry, seen);
366
+ return out;
367
+ }
368
+ if (value instanceof Set) return [...value].map((entry) => toJsonSafe(entry, seen));
369
+ const out = {};
370
+ for (const key of Object.keys(value)) {
371
+ const entry = value[key];
372
+ if (typeof entry === 'function') continue;
373
+ out[key] = toJsonSafe(entry, seen);
374
+ }
375
+ return out;
376
+ }
377
+
378
+ /**
379
+ * Read everything one step reference points at.
380
+ *
381
+ * @param {any} sessionQuery `ctx.sessionQuery`
382
+ * @param {string} ref the copied `dsh-step:` reference
383
+ * @param {{ before?: number, after?: number, requests?: boolean }} [options]
384
+ * @param {AbortSignal} [signal]
385
+ * @returns {Promise<object>} the JSON payload the tool renders
386
+ */
387
+ export async function readStepReference(sessionQuery, ref, options = {}, signal) {
388
+ const { sessionId, stepId } = parseStepReference(ref);
389
+ const normalized = normalizeStepId(stepId);
390
+ const step = parseStepId(normalized);
391
+ if (step === null) {
392
+ throw new StepReferenceError(
393
+ 'STEP_REF_INVALID_STEP_ID',
394
+ `"${stepId}" is not a known step id (expected turn.<t>.step.<s>, call.<id>, seq.<n>, or index.<n>)`,
395
+ );
396
+ }
397
+ if (step.kind === 'index') {
398
+ throw new StepReferenceError('STEP_REF_SYNTHETIC', 'synthetic index rows cannot be resolved');
399
+ }
400
+ if (sessionQuery === null || sessionQuery === undefined || typeof sessionQuery.readSession !== 'function') {
401
+ throw new StepReferenceError('STEP_REF_SESSION_QUERY_UNAVAILABLE', 'this host does not expose ctx.sessionQuery');
402
+ }
403
+ signal?.throwIfAborted?.();
404
+
405
+ let snapshot;
406
+ try {
407
+ snapshot = await sessionQuery.readSession(sessionId);
408
+ } catch (error) {
409
+ const detail = String(error?.message ?? error);
410
+ throw new StepReferenceError(
411
+ 'STEP_REF_SESSION_UNAVAILABLE',
412
+ `could not read session "${sessionId}" (${detail})`,
413
+ { cause: error },
414
+ );
415
+ }
416
+ signal?.throwIfAborted?.();
417
+
418
+ const events = Array.isArray(snapshot?.events) ? snapshot.events : [];
419
+ if (events.length === 0) {
420
+ throw new StepReferenceError('STEP_REF_EMPTY_SESSION', `session "${sessionId}" has no raw events`);
421
+ }
422
+ const range = resolveStepRange(events, step);
423
+ if (range === null) {
424
+ throw new StepReferenceError(
425
+ 'STEP_REF_UNRESOLVED',
426
+ `no event in session "${sessionId}" matches ${stepIdOf(step)}`,
427
+ );
428
+ }
429
+
430
+ const before = neighborCount(options.before);
431
+ const after = neighborCount(options.after);
432
+ const start = Math.max(0, range.startIndex - before);
433
+ const end = Math.min(events.length - 1, range.endIndex + after);
434
+ const includeRequests = options.requests === true;
435
+ const selected = [];
436
+ for (let index = start; index <= end; index += 1) {
437
+ const event = events[index];
438
+ if (!includeRequests && REQUEST_EVENT_TYPES.has(event?.type)) continue;
439
+ selected.push(toJsonSafe(event));
440
+ }
441
+
442
+ let title = '';
443
+ if (typeof sessionQuery.readTitle === 'function') {
444
+ try {
445
+ const snapshotTitle = await sessionQuery.readTitle(sessionId);
446
+ if (typeof snapshotTitle?.title === 'string') title = snapshotTitle.title;
447
+ } catch {
448
+ /* A missing title never fails the read. */
449
+ }
450
+ }
451
+ signal?.throwIfAborted?.();
452
+
453
+ const payload = {
454
+ reference: formatStepReference(String(snapshot?.session?.id ?? sessionId), stepIdOf(step)),
455
+ session: {
456
+ id: String(snapshot?.session?.id ?? sessionId),
457
+ ...(typeof snapshot?.session?.cwd === 'string' && snapshot.session.cwd !== '' ? { cwd: snapshot.session.cwd } : {}),
458
+ ...(title === '' ? {} : { title }),
459
+ },
460
+ target: { kind: step.kind, id: stepIdOf(step), ...describeStep(step) },
461
+ resolved: range.resolved,
462
+ range: {
463
+ startSeq: events[start].seq,
464
+ endSeq: events[end].seq,
465
+ eventCount: end - start + 1,
466
+ returned: selected.length,
467
+ before,
468
+ after,
469
+ },
470
+ events: selected,
471
+ };
472
+ if (!includeRequests && selected.length !== end - start + 1) {
473
+ payload.note = 'request/header snapshots (the full system prompt and tool schemas) are omitted; pass requests=true to include them';
474
+ }
475
+ return payload;
476
+ }
477
+
478
+ /** @param {Exclude<ReturnType<typeof parseStepId>, null>} step */
479
+ function describeStep(step) {
480
+ if (step.kind === 'step') return { turn: step.turn, step: step.step };
481
+ if (step.kind === 'call') return { callId: step.callId };
482
+ if (step.kind === 'seq') return { seq: step.seq };
483
+ return { index: step.index };
484
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The model-facing half of step references: one read-only tool that turns a
3
+ * `dsh-step:` reference copied from the Trajectory menu into raw session data.
4
+ *
5
+ * The factory takes the Host's `defineTool` so this module stays importable by
6
+ * the offline tests without resolving a DSH package import.
7
+ */
8
+
9
+ import { readStepReference, STEP_READ_TOOL_NAME } from './step-reference.js';
10
+
11
+ /** Default cooperative deadline for one read. */
12
+ export const STEP_READ_TIMEOUT_MS = 30_000;
13
+
14
+ export const STEP_READ_DESCRIPTION = [
15
+ 'Read the complete raw data behind a Power-Up step reference copied from the Trajectory ledger.',
16
+ 'The reference looks like dsh-step:<sessionId>/<stepId>; copy one with the Trajectory right-click menu (Copy step reference).',
17
+ 'A turn/step reference returns every raw session event of that assistant step (message, tool calls, tool results, attempts);',
18
+ 'a call reference returns the tool call and its result; a seq reference returns that single event.',
19
+ 'Raw events are returned as JSON. System-prompt/tool-schema request snapshots are omitted by default; pass requests=true to include them.',
20
+ ].join(' ');
21
+
22
+ /**
23
+ * @param {(definition: unknown) => any} defineTool the Host's tool DSL
24
+ * @param {{ getSessionQuery: () => any }} options
25
+ * @returns {any} a ToolDefinition for `ctx.tools.register`
26
+ */
27
+ export function createStepReadTool(defineTool, options) {
28
+ if (typeof defineTool !== 'function') throw new TypeError('createStepReadTool requires defineTool');
29
+ const getSessionQuery = options?.getSessionQuery;
30
+ if (typeof getSessionQuery !== 'function') throw new TypeError('createStepReadTool requires getSessionQuery');
31
+
32
+ return defineTool({
33
+ name: STEP_READ_TOOL_NAME,
34
+ description: STEP_READ_DESCRIPTION,
35
+ parameters: {
36
+ ref: {
37
+ type: 'string',
38
+ required: true,
39
+ description: 'The dsh-step:<sessionId>/<stepId> reference exactly as copied from the Trajectory menu.',
40
+ },
41
+ before: {
42
+ type: 'integer',
43
+ description: `Extra raw events to include before the step (0-50, default 0).`,
44
+ },
45
+ after: {
46
+ type: 'integer',
47
+ description: `Extra raw events to include after the step (0-50, default 0).`,
48
+ },
49
+ requests: {
50
+ type: 'boolean',
51
+ description: 'Include request/header snapshots (the full system prompt and tool schemas). Default false.',
52
+ },
53
+ },
54
+ output: {
55
+ schema: { type: 'string' },
56
+ render: (_args, value) => [{ type: 'text', text: value }],
57
+ },
58
+ isConcurrencySafe: () => true,
59
+ timeoutMs: STEP_READ_TIMEOUT_MS,
60
+ async execute(args, exec) {
61
+ const sessionQuery = getSessionQuery();
62
+ const payload = await readStepReference(
63
+ sessionQuery,
64
+ args.ref,
65
+ { before: args.before, after: args.after, requests: args.requests === true },
66
+ exec?.signal,
67
+ );
68
+ return JSON.stringify(payload, null, 2);
69
+ },
70
+ });
71
+ }
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Power-Up",
4
- "description": "Adds a right-click action menu to the Trajectory ledger: copy a record, copy a Markdown quote, quote it into the composer, open the record inspector, fork the session at that record, export the trajectory snapshot, and copy the session ID. The session header's background jobs panel gains an optional stop reason when a job is stopped by hand; the reason is appended to the completion notice injected into the session. The Plugins page gains an install control on every third-party installed plugin: read versions from the registry, install the version in the input through the Add plugin path (removing the old copy first), then enable and optionally restart DSH. The install panel also offers a one-click install that installs the input version without the enable and restart questions, enabling and restarting automatically by default; both defaults are configurable on the Power-Up page."
4
+ "description": "Adds a right-click action menu to the Trajectory ledger: copy a record, copy a Markdown quote, quote it into the composer, open the record inspector, fork the session at that record, copy a step reference (session id + step id) that the read-only powerup_step_read tool resolves back into the raw session data, export the trajectory snapshot, and copy the session ID. The session header background jobs panel gains an optional stop reason when a job is stopped by hand; the reason is appended to the completion notice injected into the session. The Plugins page gains an install control on every third-party installed plugin: read versions from the registry, install the version in the input through the Add plugin path (removing the old copy first), then enable and optionally restart DSH. The install panel also offers a one-click install that installs the input version without the enable and restart questions, enabling and restarting automatically by default; both defaults are configurable on the Power-Up page. A sidebar launcher turns the left sidebar panel buttons into an adaptive icon grid (icon above label) with drag sorting and folders: drop an icon onto the middle of another to fold them into a folder like a Windows Start menu folder, click a folder to open its icons in a flyout, and switch the whole grid off on the Power-Up page."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Power-Up",
4
- "description": "在轨迹页面为记录增加右键操作菜单:复制内容、复制 Markdown 引用、引用到输入框、查看记录详情、从该记录 Fork 会话、导出轨迹快照、复制会话 ID。在会话顶部的后台任务面板手动停止任务时可以填写停止原因,原因会附加在任务结束后注入会话的提示里。插件页为每个第三方已安装插件增加安装按钮:从安装源读取版本,按输入框中的版本先卸载旧版再按「添加插件」流程安装,完成后可立即启用并选择是否重启 DSH。安装面板还提供「一键安装」:按输入框版本安装并跳过启用与重启的询问,默认自动启用并重启,可在 Power-Up 页面调整默认行为。"
4
+ "description": "在轨迹页面为记录增加右键操作菜单:复制内容、复制 Markdown 引用、引用到输入框、查看记录详情、从该记录 Fork 会话、复制「会话 ID + 步骤 ID」的步骤引用(Agent 用只读工具 powerup_step_read 取回该步骤完整数据)、导出轨迹快照、复制会话 ID。在会话顶部的后台任务面板手动停止任务时可以填写停止原因,原因会附加在任务结束后注入会话的提示里。插件页为每个第三方已安装插件增加安装按钮:从安装源读取版本,按输入框中的版本先卸载旧版再按「添加插件」流程安装,完成后可立即启用并选择是否重启 DSH。安装面板还提供「一键安装」:按输入框版本安装并跳过启用与重启的询问,默认自动启用并重启,可在 Power-Up 页面调整默认行为。侧边栏启动器把左侧边栏的面板按钮变成随宽度自适应的图标网格(图标在上、文字在下),支持拖拽排序与分组:把一个图标拖到另一个图标的中间即可合并成分组(像 Windows 开始菜单的文件夹),点击分组会以浮层弹出其中的图标;可在 Power-Up 页面整体关闭。"
5
5
  }
6
6
  }