dsh-background-task-engine 0.0.0-stage → 1.0.1

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +21 -0
  3. package/README.md +263 -2
  4. package/README.zh.md +179 -0
  5. package/cordis.patch.yml +20 -0
  6. package/dist/config.d.ts +86 -0
  7. package/dist/config.js +106 -0
  8. package/dist/domain/records.d.ts +543 -0
  9. package/dist/domain/records.js +135 -0
  10. package/dist/domain/state.d.ts +61 -0
  11. package/dist/domain/state.js +128 -0
  12. package/dist/errors.d.ts +38 -0
  13. package/dist/errors.js +99 -0
  14. package/dist/host.d.ts +165 -0
  15. package/dist/host.js +56 -0
  16. package/dist/index.d.ts +60 -0
  17. package/dist/index.js +78 -0
  18. package/dist/prompt/guidance.d.ts +30 -0
  19. package/dist/prompt/guidance.js +62 -0
  20. package/dist/services/audit.d.ts +39 -0
  21. package/dist/services/audit.js +48 -0
  22. package/dist/services/engine.d.ts +435 -0
  23. package/dist/services/engine.js +150 -0
  24. package/dist/services/run-service.d.ts +145 -0
  25. package/dist/services/run-service.js +569 -0
  26. package/dist/services/schedule-adapter.d.ts +92 -0
  27. package/dist/services/schedule-adapter.js +220 -0
  28. package/dist/services/task-service.d.ts +146 -0
  29. package/dist/services/task-service.js +490 -0
  30. package/dist/storage/repository.d.ts +65 -0
  31. package/dist/storage/repository.js +194 -0
  32. package/dist/storage/spec.d.ts +97 -0
  33. package/dist/storage/spec.js +149 -0
  34. package/dist/tools/run-tools.d.ts +14 -0
  35. package/dist/tools/run-tools.js +402 -0
  36. package/dist/tools/schedule-tool.d.ts +11 -0
  37. package/dist/tools/schedule-tool.js +238 -0
  38. package/dist/tools/shared.d.ts +108 -0
  39. package/dist/tools/shared.js +278 -0
  40. package/dist/tools/task-tools.d.ts +7 -0
  41. package/dist/tools/task-tools.js +321 -0
  42. package/dist/utils/id.d.ts +8 -0
  43. package/dist/utils/id.js +29 -0
  44. package/dist/utils/page.d.ts +36 -0
  45. package/dist/utils/page.js +71 -0
  46. package/dist/utils/text.d.ts +20 -0
  47. package/dist/utils/text.js +46 -0
  48. package/dist/utils/time.d.ts +7 -0
  49. package/dist/utils/time.js +38 -0
  50. package/docs/API-COMPATIBILITY-AUDIT.md +203 -0
  51. package/docs/DETAIL.md +1 -0
  52. package/docs/DETAIL.zh.md +1 -0
  53. package/docs/TEST-REPORT.md +232 -0
  54. package/docs/preview.svg +68 -0
  55. package/icon.svg +23 -0
  56. package/locale/en.json +7 -0
  57. package/locale/zh.json +7 -0
  58. package/package.json +71 -4
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Task template tools: task_create / task_list / task_get / task_update /
3
+ * task_archive (PRD 4.1, 4.2, 5.2, FR-001).
4
+ */
5
+ import { z } from 'zod';
6
+ import { buildTool, out, renderGeneric, taskView, TASK_FIELDS, STEPS_ARRAY_SCHEMA, isFailure } from './shared.js';
7
+ import { TASK_STATUSES } from '../domain/records.js';
8
+ import { oneLine } from '../utils/text.js';
9
+ import { shortId } from '../utils/id.js';
10
+ const stepInput = z.object({
11
+ title: z.string().trim().min(1).max(120),
12
+ instruction: z.string().trim().min(1).max(8000),
13
+ completionCriteria: z.string().trim().max(2000).optional(),
14
+ required: z.boolean().optional(),
15
+ });
16
+ const STEP_INPUT_SCHEMA = {
17
+ type: 'object',
18
+ additionalProperties: false,
19
+ properties: {
20
+ title: { type: 'string', description: '步骤名称,1–120 字符。' },
21
+ instruction: { type: 'string', description: 'Agent 应完成的明确指令,1–8000 字符。' },
22
+ completionCriteria: { type: 'string', description: '可检查的完成标准;报告 completed 前必须满足。' },
23
+ required: { type: 'boolean', description: '是否必需步骤,默认 true;必需步骤未完成时整体不能成功。' },
24
+ },
25
+ required: ['title', 'instruction'],
26
+ };
27
+ /** Shared task-list renderer: one line per task, name + status + short id. */
28
+ function renderTaskList(items, total) {
29
+ if (items.length === 0)
30
+ return [{ type: 'text', text: '(没有符合条件的任务)' }];
31
+ const lines = items.map((item) => {
32
+ const schedule = item.schedule ? ` · 定时 ${item.schedule.state}/${item.schedule.timing}` : '';
33
+ const last = item.lastRun ? ` · 最近 ${item.lastRun.status}` : ' · 尚未运行';
34
+ return `${oneLine(item.title, 40)} ${item.status} ${shortId(item.taskId)}${schedule}${last}`;
35
+ });
36
+ const header = total === undefined ? `${items.length} 个任务` : `${items.length} 个任务(共 ${total})`;
37
+ return [{ type: 'text', text: `${header}\n${lines.join('\n')}` }];
38
+ }
39
+ export function createTaskTools(engine) {
40
+ const create = buildTool({
41
+ name: 'task_create',
42
+ description: '创建一个可复用的后台任务模板(1–10 个线性步骤)。任务归属于调用方会话,其他会话不可见。'
43
+ + '创建后可用 task_run 手动执行,或用 task_schedule 关联 DSH 原生定时规则。',
44
+ parameters: {
45
+ title: { type: 'string', description: '任务标题,2–80 字符,必填。' },
46
+ description: { type: 'string', description: '任务用途说明(最多 2000 字符)。' },
47
+ steps: {
48
+ type: 'array',
49
+ description: '有序步骤列表,1–10 个;按数组顺序即为执行顺序。',
50
+ items: STEP_INPUT_SCHEMA,
51
+ },
52
+ copyFromTaskId: {
53
+ type: 'string',
54
+ description: '可选:复制一个已有任务的步骤作为模板,省略 steps 时生效。',
55
+ },
56
+ },
57
+ args: z.object({
58
+ title: z.string().trim().min(2).max(80),
59
+ description: z.string().trim().max(2000).optional(),
60
+ steps: z.array(stepInput).optional(),
61
+ copyFromTaskId: z.string().trim().min(4).max(64).optional(),
62
+ }),
63
+ output: out(TASK_FIELDS, ['taskId', 'status', 'revision']),
64
+ render: (args, value) => {
65
+ const record = value;
66
+ if (isFailure(value))
67
+ return renderGeneric(args, value);
68
+ const steps = (record.steps ?? []);
69
+ const lines = steps.map((step, index) => `${index + 1}. ${String(step.title ?? '')}`);
70
+ return [
71
+ {
72
+ type: 'text',
73
+ text: `已创建任务「${String(record.title ?? '')}」\n`
74
+ + `taskId: ${String(record.taskId ?? '')}\n`
75
+ + `revision: ${String(record.revision ?? 1)} · 步骤 ${String(record.stepCount ?? steps.length)} 个\n`
76
+ + lines.join('\n'),
77
+ },
78
+ ];
79
+ },
80
+ async execute(args, active) {
81
+ const task = await active.taskService.create({
82
+ sessionId: String(args.sessionId),
83
+ title: args.title,
84
+ description: args.description,
85
+ steps: args.steps,
86
+ copyFromTaskId: args.copyFromTaskId,
87
+ });
88
+ return taskView(task);
89
+ },
90
+ }, engine);
91
+ const list = buildTool({
92
+ name: 'task_list',
93
+ description: '列出当前会话的后台任务模板(默认按更新时间倒序,每页 20 条,最多 100 条)。'
94
+ + '可按状态筛选或按关键词匹配标题/描述。',
95
+ parameters: {
96
+ status: { type: 'string', enum: [...TASK_STATUSES], description: '按模板状态筛选。' },
97
+ query: { type: 'string', description: '关键词,匹配标题或描述(也接受完整 taskId)。' },
98
+ limit: { type: 'integer', description: '每页条数,1–100,默认 20。' },
99
+ cursor: { type: 'string', description: '上一页返回的 nextCursor;省略表示第一页。' },
100
+ },
101
+ args: z.object({
102
+ status: z.enum(TASK_STATUSES).optional(),
103
+ query: z.string().trim().max(200).optional(),
104
+ limit: z.number().int().min(1).max(100).optional(),
105
+ cursor: z.string().max(200).optional(),
106
+ }),
107
+ output: out({
108
+ items: {
109
+ type: 'array',
110
+ items: {
111
+ type: 'object',
112
+ additionalProperties: true,
113
+ properties: {
114
+ taskId: { type: 'string' },
115
+ title: { type: 'string' },
116
+ status: { type: 'string' },
117
+ revision: { type: 'integer' },
118
+ stepCount: { type: 'integer' },
119
+ updatedAt: { type: 'string' },
120
+ lastRunStatus: { type: 'string' },
121
+ lastRunId: { type: 'string' },
122
+ scheduleState: { type: 'string' },
123
+ },
124
+ },
125
+ },
126
+ nextCursor: { type: 'string' },
127
+ total: { type: 'integer' },
128
+ }, ['items']),
129
+ render: (_args, value) => {
130
+ const record = value;
131
+ if (record.success === false)
132
+ return renderGeneric(_args, value);
133
+ const items = (record.items ?? []);
134
+ const rendered = renderTaskList(items);
135
+ if (record.nextCursor) {
136
+ rendered.push({ type: 'text', text: `下一页:cursor=${String(record.nextCursor)}` });
137
+ }
138
+ return rendered;
139
+ },
140
+ execute(args, active) {
141
+ const page = active.taskService.list({
142
+ sessionId: String(args.sessionId),
143
+ status: args.status,
144
+ query: args.query,
145
+ limit: args.limit,
146
+ cursor: args.cursor,
147
+ });
148
+ return {
149
+ items: page.items.map((item) => ({
150
+ taskId: item.taskId,
151
+ title: item.title,
152
+ status: item.status,
153
+ revision: item.revision,
154
+ stepCount: item.stepCount,
155
+ updatedAt: item.updatedAt,
156
+ ...(item.lastRun ? { lastRunStatus: item.lastRun.status, lastRunId: item.lastRun.runId } : {}),
157
+ ...(item.schedule ? { scheduleState: item.schedule.state } : {}),
158
+ })),
159
+ ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),
160
+ };
161
+ },
162
+ }, engine);
163
+ const get = buildTool({
164
+ name: 'task_get',
165
+ description: '查看一个任务的完整定义(含步骤、定时关联)与最近的运行记录。',
166
+ parameters: {
167
+ taskId: { type: 'string', description: '任务 ID。' },
168
+ includeRuns: { type: 'boolean', description: '是否附带最近 5 次运行摘要,默认 true。' },
169
+ },
170
+ args: z.object({
171
+ taskId: z.string().trim().min(4).max(64),
172
+ includeRuns: z.boolean().optional(),
173
+ }),
174
+ output: out({
175
+ ...TASK_FIELDS,
176
+ recentRuns: {
177
+ type: 'array',
178
+ items: {
179
+ type: 'object',
180
+ additionalProperties: true,
181
+ properties: {
182
+ runId: { type: 'string' },
183
+ status: { type: 'string' },
184
+ progress: { type: 'integer' },
185
+ startedAt: { type: 'string' },
186
+ finishedAt: { type: 'string' },
187
+ },
188
+ },
189
+ },
190
+ }, ['taskId']),
191
+ render: (args, value) => {
192
+ const record = value;
193
+ if (isFailure(value))
194
+ return renderGeneric(args, value);
195
+ const steps = (record.steps ?? []);
196
+ const runs = (record.recentRuns ?? []);
197
+ const lines = [
198
+ `任务:${String(record.title ?? '')}`,
199
+ `状态:${String(record.status ?? '')} · revision ${String(record.revision ?? '')} · ${steps.length} 步`,
200
+ `taskId:${String(record.taskId ?? '')}`,
201
+ ];
202
+ if (record.schedule) {
203
+ const schedule = record.schedule;
204
+ lines.push(`定时:${String(schedule.state)}(${String(schedule.scheduleId)})`);
205
+ }
206
+ for (const step of steps) {
207
+ lines.push(`${String(step.order)}. ${String(step.title)}${step.required === false ? '(可选)' : ''}`);
208
+ }
209
+ if (runs.length > 0) {
210
+ lines.push('最近运行:');
211
+ for (const run of runs) {
212
+ lines.push(`· ${String(run.runId)} ${String(run.status)} ${String(run.progress ?? 0)}%`);
213
+ }
214
+ }
215
+ return [{ type: 'text', text: lines.join('\n') }];
216
+ },
217
+ execute(args, active) {
218
+ const { task, recentRuns } = active.taskService.get(String(args.sessionId), String(args.taskId), {
219
+ includeRuns: args.includeRuns !== false,
220
+ });
221
+ return {
222
+ ...taskView(task),
223
+ recentRuns: recentRuns.map((run) => ({
224
+ runId: run.runId,
225
+ status: run.status,
226
+ progress: run.progress,
227
+ startedAt: run.startedAt,
228
+ ...(run.finishedAt ? { finishedAt: run.finishedAt } : {}),
229
+ })),
230
+ };
231
+ },
232
+ }, engine);
233
+ const update = buildTool({
234
+ name: 'task_update',
235
+ description: '修改任务模板(标题、描述、步骤或状态)。必须携带 expectedRevision 做乐观锁;revision 不匹配会返回 TASK_REVISION_CONFLICT。'
236
+ + '把 status 改为 paused 会同步暂停关联的原生定时规则,改为 active 会恢复。',
237
+ parameters: {
238
+ taskId: { type: 'string', description: '任务 ID。' },
239
+ expectedRevision: { type: 'integer', description: '从 task_get 读到的 revision;用于防止覆盖他人的新版本。' },
240
+ title: { type: 'string', description: '新的任务标题(2–80 字符)。' },
241
+ description: { type: 'string', description: '新的任务说明。' },
242
+ steps: {
243
+ type: 'array',
244
+ description: '替换全部步骤(1–10 个,顺序即执行顺序)。',
245
+ items: STEP_INPUT_SCHEMA,
246
+ },
247
+ status: { type: 'string', enum: ['active', 'paused'], description: '启用或暂停任务(归档请用 task_archive)。' },
248
+ },
249
+ args: z.object({
250
+ taskId: z.string().trim().min(4).max(64),
251
+ expectedRevision: z.number().int().min(1),
252
+ title: z.string().trim().min(2).max(80).optional(),
253
+ description: z.string().trim().max(2000).optional(),
254
+ steps: z.array(stepInput).optional(),
255
+ status: z.enum(['active', 'paused']).optional(),
256
+ }),
257
+ output: out(TASK_FIELDS, ['taskId', 'revision']),
258
+ render: (args, value) => {
259
+ const record = value;
260
+ if (isFailure(value))
261
+ return renderGeneric(args, value);
262
+ return [
263
+ {
264
+ type: 'text',
265
+ text: `已更新任务「${String(record.title ?? '')}」\n`
266
+ + `taskId: ${String(record.taskId ?? '')} · revision ${String(record.revision ?? '')} · 状态 ${String(record.status ?? '')}`,
267
+ },
268
+ ];
269
+ },
270
+ async execute(args, active) {
271
+ const task = await active.taskService.update({
272
+ sessionId: String(args.sessionId),
273
+ taskId: String(args.taskId),
274
+ expectedRevision: Number(args.expectedRevision),
275
+ title: args.title,
276
+ description: args.description,
277
+ steps: args.steps,
278
+ status: args.status,
279
+ });
280
+ return taskView(task);
281
+ },
282
+ }, engine);
283
+ const archive = buildTool({
284
+ name: 'task_archive',
285
+ description: '归档任务(软删除):任务变为只读,关联的原生定时规则会被删除,但历史运行与步骤记录全部保留。'
286
+ + '存在活动运行时会被拒绝,请先结束或恢复该运行。',
287
+ parameters: {
288
+ taskId: { type: 'string', description: '任务 ID。' },
289
+ expectedRevision: { type: 'integer', description: '从 task_get 读到的 revision。' },
290
+ },
291
+ args: z.object({
292
+ taskId: z.string().trim().min(4).max(64),
293
+ expectedRevision: z.number().int().min(1),
294
+ }),
295
+ output: out({ ...TASK_FIELDS, previousStatus: { type: 'string' } }, ['taskId', 'status']),
296
+ render: (args, value) => {
297
+ const record = value;
298
+ if (isFailure(value))
299
+ return renderGeneric(args, value);
300
+ return [
301
+ {
302
+ type: 'text',
303
+ text: `已归档「${String(record.title ?? '')}」(${String(record.taskId ?? '')})\n`
304
+ + '历史运行记录保留,任务不能再执行或修改。',
305
+ },
306
+ ];
307
+ },
308
+ async execute(args, active) {
309
+ const before = active.taskService.get(String(args.sessionId), String(args.taskId), { includeRuns: false }).task;
310
+ const task = await active.taskService.archive({
311
+ sessionId: String(args.sessionId),
312
+ taskId: String(args.taskId),
313
+ expectedRevision: Number(args.expectedRevision),
314
+ });
315
+ return { ...taskView(task), previousStatus: before.status };
316
+ },
317
+ }, engine);
318
+ // Exposed so the schedule tool can render step arrays consistently.
319
+ void STEPS_ARRAY_SCHEMA;
320
+ return [create, list, get, update, archive];
321
+ }
@@ -0,0 +1,8 @@
1
+ /** `tsk_` + 20 chars: unique per task, stable, copy-pasteable. */
2
+ export declare function newTaskId(): string;
3
+ /** `run_` + 20 chars. */
4
+ export declare function newRunId(): string;
5
+ /** `stp_` + 16 chars. */
6
+ export declare function newStepId(): string;
7
+ /** Shorten an id for display while keeping it copyable in full elsewhere. */
8
+ export declare function shortId(id: string): string;
@@ -0,0 +1,29 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ /** Lower-case base32 alphabet without look-alike characters (crockford-ish). */
3
+ const ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz';
4
+ function randomToken(length) {
5
+ const bytes = randomBytes(length);
6
+ let out = '';
7
+ for (let i = 0; i < length; i += 1) {
8
+ out += ALPHABET[bytes[i] % ALPHABET.length];
9
+ }
10
+ return out;
11
+ }
12
+ /** `tsk_` + 20 chars: unique per task, stable, copy-pasteable. */
13
+ export function newTaskId() {
14
+ return `tsk_${randomToken(20)}`;
15
+ }
16
+ /** `run_` + 20 chars. */
17
+ export function newRunId() {
18
+ return `run_${randomToken(20)}`;
19
+ }
20
+ /** `stp_` + 16 chars. */
21
+ export function newStepId() {
22
+ return `stp_${randomToken(16)}`;
23
+ }
24
+ /** Shorten an id for display while keeping it copyable in full elsewhere. */
25
+ export function shortId(id) {
26
+ if (id.length <= 12)
27
+ return id;
28
+ return `${id.slice(0, 8)}…${id.slice(-4)}`;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Cursor pagination for list/history tools (PRD 6.6).
3
+ *
4
+ * Cursors are opaque base64url JSON, never StorageDomain query expressions.
5
+ * Ordering is descending by (sortKey, id) — a stable keyset so concurrent
6
+ * writes cannot cause skipped or duplicated rows.
7
+ */
8
+ export declare const DEFAULT_PAGE_LIMIT = 20;
9
+ export declare const MAX_PAGE_LIMIT = 100;
10
+ export interface CursorPayload {
11
+ /** sort key (ISO timestamp) */
12
+ u: string;
13
+ /** tie-breaker id */
14
+ i: string;
15
+ }
16
+ export declare function normaliseLimit(limit: unknown): number;
17
+ export declare function encodeCursor(payload: CursorPayload): string;
18
+ export declare function decodeCursor(cursor: string | undefined): CursorPayload | undefined;
19
+ /** True when `item` sorts strictly after the cursor position. */
20
+ export declare function isAfterCursor(itemTs: string, itemId: string, cursor: CursorPayload | undefined): boolean;
21
+ export interface PageSlice<T> {
22
+ items: T[];
23
+ nextCursor?: string;
24
+ }
25
+ /**
26
+ * Slice an already-sorted (desc) array. `limit + 1` is inspected so a
27
+ * `nextCursor` is only returned when more rows actually exist.
28
+ */
29
+ export declare function paginate<T>(sorted: T[], options: {
30
+ limit: number;
31
+ cursor: CursorPayload | undefined;
32
+ tsOf: (item: T) => string;
33
+ idOf: (item: T) => string;
34
+ }): PageSlice<T>;
35
+ /** Descending comparator over (timestamp, id). */
36
+ export declare function compareDesc(aTs: string, aId: string, bTs: string, bId: string): number;
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Cursor pagination for list/history tools (PRD 6.6).
3
+ *
4
+ * Cursors are opaque base64url JSON, never StorageDomain query expressions.
5
+ * Ordering is descending by (sortKey, id) — a stable keyset so concurrent
6
+ * writes cannot cause skipped or duplicated rows.
7
+ */
8
+ export const DEFAULT_PAGE_LIMIT = 20;
9
+ export const MAX_PAGE_LIMIT = 100;
10
+ export function normaliseLimit(limit) {
11
+ if (limit === undefined || limit === null)
12
+ return DEFAULT_PAGE_LIMIT;
13
+ const value = typeof limit === 'string' ? Number(limit) : limit;
14
+ if (typeof value !== 'number' || !Number.isFinite(value))
15
+ return DEFAULT_PAGE_LIMIT;
16
+ const integer = Math.floor(value);
17
+ if (integer < 1)
18
+ return 1;
19
+ if (integer > MAX_PAGE_LIMIT)
20
+ return MAX_PAGE_LIMIT;
21
+ return integer;
22
+ }
23
+ export function encodeCursor(payload) {
24
+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
25
+ }
26
+ export function decodeCursor(cursor) {
27
+ if (!cursor)
28
+ return undefined;
29
+ try {
30
+ const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
31
+ if (typeof parsed.u === 'string' && typeof parsed.i === 'string') {
32
+ return { u: parsed.u, i: parsed.i };
33
+ }
34
+ }
35
+ catch {
36
+ /* fall through: invalid cursor is treated as "start from the beginning" */
37
+ }
38
+ return undefined;
39
+ }
40
+ /** True when `item` sorts strictly after the cursor position. */
41
+ export function isAfterCursor(itemTs, itemId, cursor) {
42
+ if (!cursor)
43
+ return true;
44
+ if (itemTs < cursor.u)
45
+ return true;
46
+ if (itemTs > cursor.u)
47
+ return false;
48
+ return itemId < cursor.i;
49
+ }
50
+ /**
51
+ * Slice an already-sorted (desc) array. `limit + 1` is inspected so a
52
+ * `nextCursor` is only returned when more rows actually exist.
53
+ */
54
+ export function paginate(sorted, options) {
55
+ const filtered = sorted.filter((item) => isAfterCursor(options.tsOf(item), options.idOf(item), options.cursor));
56
+ const window = filtered.slice(0, options.limit + 1);
57
+ const items = window.slice(0, options.limit);
58
+ if (window.length > options.limit && items.length > 0) {
59
+ const last = items[items.length - 1];
60
+ return { items, nextCursor: encodeCursor({ u: options.tsOf(last), i: options.idOf(last) }) };
61
+ }
62
+ return { items };
63
+ }
64
+ /** Descending comparator over (timestamp, id). */
65
+ export function compareDesc(aTs, aId, bTs, bId) {
66
+ if (aTs !== bTs)
67
+ return aTs < bTs ? 1 : -1;
68
+ if (aId === bId)
69
+ return 0;
70
+ return aId < bId ? 1 : -1;
71
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Text helpers for summaries, instructions and paginated output.
3
+ */
4
+ export declare const SUMMARY_TRUNCATION_MARK = "\u2026[truncated]";
5
+ /**
6
+ * Truncate to `max` characters (PRD FR-006: summaries are bounded, and the
7
+ * caller keeps the Session/file reference instead of copying history).
8
+ */
9
+ export declare function truncateText(input: string | undefined, max: number): string | undefined;
10
+ /** Trim + cap a user supplied title/description without truncation markers. */
11
+ export declare function trimTo(input: unknown, max: number): string;
12
+ /** One-line preview for list output. */
13
+ export declare function oneLine(input: string | undefined, max?: number): string;
14
+ /**
15
+ * External text (task titles, step summaries, schedule deliveries) is rendered
16
+ * as untrusted data: strip control characters that could forge UI lines.
17
+ */
18
+ export declare function untrustedText(input: string | undefined, max?: number): string;
19
+ /** JSON string used in schedule delivery payloads and prompts. */
20
+ export declare function jsonLiteral(value: unknown): string;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Text helpers for summaries, instructions and paginated output.
3
+ */
4
+ export const SUMMARY_TRUNCATION_MARK = '…[truncated]';
5
+ /**
6
+ * Truncate to `max` characters (PRD FR-006: summaries are bounded, and the
7
+ * caller keeps the Session/file reference instead of copying history).
8
+ */
9
+ export function truncateText(input, max) {
10
+ if (input === undefined || input === null)
11
+ return undefined;
12
+ const text = String(input);
13
+ if (text.length <= max)
14
+ return text;
15
+ const budget = Math.max(0, max - SUMMARY_TRUNCATION_MARK.length);
16
+ return `${text.slice(0, budget)}${SUMMARY_TRUNCATION_MARK}`;
17
+ }
18
+ /** Trim + cap a user supplied title/description without truncation markers. */
19
+ export function trimTo(input, max) {
20
+ const text = typeof input === 'string' ? input.trim() : '';
21
+ return text.length > max ? text.slice(0, max) : text;
22
+ }
23
+ /** One-line preview for list output. */
24
+ export function oneLine(input, max = 80) {
25
+ if (!input)
26
+ return '';
27
+ const flat = input.replace(/\s+/g, ' ').trim();
28
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
29
+ }
30
+ /**
31
+ * External text (task titles, step summaries, schedule deliveries) is rendered
32
+ * as untrusted data: strip control characters that could forge UI lines.
33
+ */
34
+ export function untrustedText(input, max = 400) {
35
+ if (!input)
36
+ return '';
37
+ const cleaned = String(input)
38
+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ')
39
+ .replace(/\s+/g, ' ')
40
+ .trim();
41
+ return cleaned.length > max ? `${cleaned.slice(0, max - 1)}…` : cleaned;
42
+ }
43
+ /** JSON string used in schedule delivery payloads and prompts. */
44
+ export function jsonLiteral(value) {
45
+ return JSON.stringify(value);
46
+ }
@@ -0,0 +1,7 @@
1
+ /** RFC3339 UTC timestamps, e.g. 2026-11-26T01:02:03.456Z */
2
+ export declare function nowIso(): string;
3
+ export declare function toMillis(iso: string | undefined): number;
4
+ export declare function minutesAgoIso(minutes: number, now?: number): string;
5
+ export declare function daysAgoIso(days: number, now?: number): string;
6
+ export declare function isOlderThanMinutes(iso: string | undefined, minutes: number, now?: number): boolean;
7
+ export declare function elapsedLabel(fromIso: string | undefined, toIso: string | undefined): string;
@@ -0,0 +1,38 @@
1
+ /** RFC3339 UTC timestamps, e.g. 2026-11-26T01:02:03.456Z */
2
+ export function nowIso() {
3
+ return new Date().toISOString();
4
+ }
5
+ export function toMillis(iso) {
6
+ if (!iso)
7
+ return 0;
8
+ const value = Date.parse(iso);
9
+ return Number.isFinite(value) ? value : 0;
10
+ }
11
+ export function minutesAgoIso(minutes, now = Date.now()) {
12
+ return new Date(now - minutes * 60_000).toISOString();
13
+ }
14
+ export function daysAgoIso(days, now = Date.now()) {
15
+ return new Date(now - days * 24 * 60 * 60_000).toISOString();
16
+ }
17
+ export function isOlderThanMinutes(iso, minutes, now = Date.now()) {
18
+ if (!iso)
19
+ return true;
20
+ const millis = toMillis(iso);
21
+ if (millis === 0)
22
+ return true;
23
+ return now - millis > minutes * 60_000;
24
+ }
25
+ export function elapsedLabel(fromIso, toIso) {
26
+ const from = toMillis(fromIso);
27
+ const to = toIso ? toMillis(toIso) : Date.now();
28
+ if (!from || !to)
29
+ return '—';
30
+ const seconds = Math.max(0, Math.round((to - from) / 1000));
31
+ if (seconds < 60)
32
+ return `${seconds}s`;
33
+ const minutes = Math.floor(seconds / 60);
34
+ if (minutes < 60)
35
+ return `${minutes}m${seconds % 60 ? `${seconds % 60}s` : ''}`;
36
+ const hours = Math.floor(minutes / 60);
37
+ return `${hours}h${minutes % 60 ? `${minutes % 60}m` : ''}`;
38
+ }