@saturn-universe/tools 0.0.0-stage → 0.1.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.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/dist/container-sandbox.d.ts +168 -0
  3. package/dist/container-sandbox.js +1241 -0
  4. package/dist/counter.d.ts +5 -0
  5. package/dist/counter.js +82 -0
  6. package/dist/data-review.d.ts +4 -0
  7. package/dist/data-review.js +146 -0
  8. package/dist/execution-backend.d.ts +55 -0
  9. package/dist/execution-backend.js +339 -0
  10. package/dist/executor.d.ts +25 -0
  11. package/dist/executor.js +978 -0
  12. package/dist/file-window.d.ts +3 -0
  13. package/dist/file-window.js +12 -0
  14. package/dist/index.d.ts +27 -0
  15. package/dist/index.js +17 -0
  16. package/dist/mcp-headers.d.ts +3 -0
  17. package/dist/mcp-headers.js +51 -0
  18. package/dist/mcp-http.d.ts +3 -0
  19. package/dist/mcp-http.js +253 -0
  20. package/dist/mcp-stdio.d.ts +2 -0
  21. package/dist/mcp-stdio.js +147 -0
  22. package/dist/mcp-wire.d.ts +33 -0
  23. package/dist/mcp-wire.js +85 -0
  24. package/dist/mcp.d.ts +19 -0
  25. package/dist/mcp.js +325 -0
  26. package/dist/path-containment.d.ts +3 -0
  27. package/dist/path-containment.js +11 -0
  28. package/dist/planner.d.ts +3 -0
  29. package/dist/planner.js +162 -0
  30. package/dist/process-manager.d.ts +67 -0
  31. package/dist/process-manager.js +423 -0
  32. package/dist/process-output.d.ts +34 -0
  33. package/dist/process-output.js +162 -0
  34. package/dist/process-worker.d.ts +1 -0
  35. package/dist/process-worker.js +202 -0
  36. package/dist/registry.d.ts +33 -0
  37. package/dist/registry.js +227 -0
  38. package/dist/search.d.ts +9 -0
  39. package/dist/search.js +96 -0
  40. package/dist/team.d.ts +36 -0
  41. package/dist/team.js +284 -0
  42. package/dist/text-patch.d.ts +15 -0
  43. package/dist/text-patch.js +81 -0
  44. package/dist/todo.d.ts +3 -0
  45. package/dist/todo.js +105 -0
  46. package/dist/workspace-discovery.d.ts +42 -0
  47. package/dist/workspace-discovery.js +404 -0
  48. package/dist/workspace-snapshot.d.ts +28 -0
  49. package/dist/workspace-snapshot.js +371 -0
  50. package/dist/workspace.d.ts +22 -0
  51. package/dist/workspace.js +1819 -0
  52. package/package.json +16 -3
  53. package/README.md +0 -3
package/dist/team.js ADDED
@@ -0,0 +1,284 @@
1
+ import { maxTeamMembers, RuntimeError, teamNotifyMessagePrefix, validateTeamConfig, } from '@saturn-universe/core';
2
+ export const spawnTeamToolName = 'spawn_team';
3
+ export const teamNotifyParentToolName = 'team_notify_parent';
4
+ const MAIN_PARENT_ALIASES = new Set(['coordinator', 'root', 'self']);
5
+ function isCtfModeRef(modeRef) {
6
+ return modeRef === 'ctf@1' || Boolean(modeRef?.startsWith('ctf@'));
7
+ }
8
+ export function createSpawnTeamTool(options) {
9
+ const includeSandboxProfile = options?.includeSandboxProfile === true;
10
+ const includeWorkSubpath = options?.includeWorkSubpath === true;
11
+ const isV2 = includeSandboxProfile || includeWorkSubpath;
12
+ return {
13
+ definition: {
14
+ name: spawnTeamToolName,
15
+ version: isV2 ? '2' : '1',
16
+ description: isV2
17
+ ? "Default to handling single-file, single-binary, simple linear verification, or short-command tasks directly as a single agent; do NOT spawn workers for simple static checks, a single debugging session, or short validation scripts. Call spawn_team only when the task genuinely contains 2+ time-consuming, independent modules or subsystems (e.g., separate services, frontend/backend splits, or parallel multi-module analysis in a large codebase) where you need parallel coverage while occupied elsewhere. Give each worker a strictly non-overlapping scope and concrete deliverable so teammates do not repeat identical baseline checks. members[].parent is optional and defaults to the current caller ('main' for the main session, or your own member ID for a Depth-1 worker; main-session aliases 'coordinator', 'root', and 'self' automatically normalize to 'main'). End your turn immediately with NO further tool calls after calling this tool so the runtime executes the team workers and returns their reports in the next turn."
18
+ : 'Default to handling single-file, single-binary, simple linear verification, or short-command tasks directly as a single agent; do NOT spawn workers for simple static checks, a single debugging session, or short validation scripts. Call spawn_team only when the task genuinely contains 2+ time-consuming, independent modules or subsystems (e.g., separate services, frontend/backend splits, or parallel multi-module analysis in a large codebase) where you need parallel coverage while occupied elsewhere. Give each worker a strictly non-overlapping scope and concrete deliverable so teammates do not repeat identical baseline checks. End your turn immediately with NO further tool calls after calling this tool so the runtime executes the team workers and returns their reports in the next turn.',
19
+ inputSchema: {
20
+ type: 'object',
21
+ properties: {
22
+ reason: { type: 'string', minLength: 1, maxLength: 1000 },
23
+ concurrency: { type: 'integer', minimum: 1, maximum: 16 },
24
+ members: {
25
+ type: 'array',
26
+ minItems: 1,
27
+ maxItems: 15,
28
+ items: {
29
+ type: 'object',
30
+ properties: {
31
+ id: { type: 'string', minLength: 1, maxLength: 64 },
32
+ parent: isV2
33
+ ? {
34
+ type: 'string',
35
+ minLength: 1,
36
+ maxLength: 64,
37
+ description: "Optional parent member ID. Omit to default to the current caller ('main' for the main coordinator, or your own member ID for a Depth-1 worker). For the main coordinator, 'coordinator', 'root', and 'self' normalize to 'main'.",
38
+ }
39
+ : { type: 'string', minLength: 1, maxLength: 64 },
40
+ task: { type: 'string', minLength: 1, maxLength: isV2 ? 8000 : 4000 },
41
+ ...(includeSandboxProfile
42
+ ? { sandboxProfile: { type: 'string', enum: ['default', 'readonly', 'build'] } }
43
+ : {}),
44
+ ...(includeWorkSubpath
45
+ ? {
46
+ workSubpath: {
47
+ type: 'string',
48
+ minLength: 1,
49
+ maxLength: 512,
50
+ description: "Relative directory path under workspace root mounted at container /workspace root. Required for Depth-1 workers in ctf@1 mode; Depth-2 helpers omit it to inherit their parent worker's workSubpath.",
51
+ },
52
+ }
53
+ : {}),
54
+ },
55
+ required: isV2 ? ['id', 'task'] : ['id', 'parent', 'task'],
56
+ additionalProperties: false,
57
+ },
58
+ },
59
+ },
60
+ required: ['reason', 'members'],
61
+ additionalProperties: false,
62
+ },
63
+ source: { kind: 'builtin' },
64
+ effects: 'read',
65
+ supportsIdempotencyKey: false,
66
+ supportsReconcile: false,
67
+ concurrency: 'serial_per_run',
68
+ timeoutMs: 10000,
69
+ },
70
+ handler: {
71
+ async invoke(input, ctx) {
72
+ const caller = options?.resolveCaller
73
+ ? await options.resolveCaller(ctx)
74
+ : { memberId: 'main', depth: 0, maxDepth: 1 };
75
+ if (caller.depth >= caller.maxDepth) {
76
+ return {
77
+ effect: 'none',
78
+ outcome: {
79
+ status: 'error',
80
+ error: {
81
+ code: 'TEAM_MAX_DEPTH_EXCEEDED',
82
+ message: `Member "${caller.memberId}" at depth ${caller.depth} cannot spawn further sub-teams (maxDepth=${caller.maxDepth})`,
83
+ retryable: false,
84
+ },
85
+ },
86
+ };
87
+ }
88
+ const parsed = input;
89
+ const reason = typeof parsed?.reason === 'string' ? parsed.reason.trim() : '';
90
+ if (!reason)
91
+ return invalidTeam('reason must not be empty');
92
+ if (!Array.isArray(parsed.members) || parsed.members.length === 0) {
93
+ return invalidTeam('members must contain at least one worker');
94
+ }
95
+ const declaredIds = new Set(parsed.members
96
+ .map((member) => (typeof member?.id === 'string' ? member.id.trim() : ''))
97
+ .filter(Boolean));
98
+ const members = parsed.members.map((member) => {
99
+ const rawParent = typeof member.parent === 'string' ? member.parent.trim() : '';
100
+ let resolvedParent = rawParent || caller.memberId;
101
+ if (caller.memberId === 'main' &&
102
+ MAIN_PARENT_ALIASES.has(resolvedParent.toLowerCase()) &&
103
+ !declaredIds.has(resolvedParent)) {
104
+ resolvedParent = 'main';
105
+ }
106
+ return {
107
+ id: member.id,
108
+ parent: resolvedParent,
109
+ task: member.task,
110
+ ...(member.sandboxProfile !== undefined ? { sandboxProfile: member.sandboxProfile } : {}),
111
+ ...(member.workSubpath !== undefined ? { workSubpath: member.workSubpath } : {}),
112
+ };
113
+ });
114
+ if (includeWorkSubpath && isCtfModeRef(caller.modeRef) && caller.depth === 0) {
115
+ for (const member of members) {
116
+ if (member.parent !== 'main')
117
+ continue;
118
+ if (typeof member.workSubpath !== 'string' || !member.workSubpath.trim()) {
119
+ return invalidTeam(`In ctf@1 mode, every Depth-1 worker spawned by main (member "${member.id}") must provide a non-empty workSubpath matching its challenge directory name (for example, "task_01"). Do not omit workSubpath.`);
120
+ }
121
+ }
122
+ }
123
+ if (caller.depth === 0 && caller.maxActiveDepth1 !== undefined) {
124
+ const requestedDepth1 = members.filter((member) => member.parent === 'main').length;
125
+ const activeDepth1 = caller.activeDepth1Count ?? 0;
126
+ const availableSlots = Math.max(0, caller.maxActiveDepth1 - activeDepth1);
127
+ if (requestedDepth1 > availableSlots) {
128
+ return invalidTeam(`Cannot spawn ${requestedDepth1} Depth-1 worker(s): max_active_challenges is ${caller.maxActiveDepth1}, currently ${activeDepth1} active Depth-1 worker(s) (${availableSlots} slot(s) available). Spawn at most ${availableSlots} Depth-1 worker(s) now and backfill incrementally as active workers complete.`);
129
+ }
130
+ }
131
+ const concurrencyCap = caller.maxConcurrentWorkers ?? maxTeamMembers;
132
+ const effectiveConcurrency = parsed.concurrency !== undefined
133
+ ? Math.min(parsed.concurrency, concurrencyCap)
134
+ : caller.depth === 0 && caller.maxActiveDepth1 !== undefined
135
+ ? Math.max(1, Math.min(caller.maxActiveDepth1, concurrencyCap))
136
+ : undefined;
137
+ const team = {
138
+ members,
139
+ ...(effectiveConcurrency !== undefined ? { concurrency: effectiveConcurrency } : {}),
140
+ ...(caller.memberId !== 'main' ? { rootId: caller.memberId } : {}),
141
+ };
142
+ try {
143
+ validateTeamConfig(team, caller.memberId === 'main'
144
+ ? undefined
145
+ : { rootId: caller.memberId, maxDepth: Math.max(1, caller.maxDepth - caller.depth) });
146
+ }
147
+ catch (err) {
148
+ if (err instanceof RuntimeError) {
149
+ return {
150
+ effect: 'none',
151
+ outcome: {
152
+ status: 'error',
153
+ error: { code: err.code, message: err.message, retryable: false },
154
+ },
155
+ };
156
+ }
157
+ throw err;
158
+ }
159
+ const teamData = {
160
+ members: members.map((member) => ({ ...member })),
161
+ ...(effectiveConcurrency !== undefined ? { concurrency: effectiveConcurrency } : {}),
162
+ ...(caller.memberId !== 'main' ? { rootId: caller.memberId } : {}),
163
+ };
164
+ return {
165
+ effect: 'none',
166
+ outcome: {
167
+ status: 'success',
168
+ content: [
169
+ {
170
+ type: 'text',
171
+ text: `Team spawn recorded with ${team.members.length} worker(s). End your turn immediately so the runtime executes the team workers and returns their reports in the next turn.`,
172
+ },
173
+ ],
174
+ data: {
175
+ kind: spawnTeamToolName,
176
+ reason,
177
+ team: teamData,
178
+ },
179
+ },
180
+ };
181
+ },
182
+ },
183
+ };
184
+ }
185
+ function invalidTeam(message) {
186
+ return {
187
+ effect: 'none',
188
+ outcome: {
189
+ status: 'error',
190
+ error: { code: 'INVALID_TEAM_CONFIG', message, retryable: false },
191
+ },
192
+ };
193
+ }
194
+ export function createTeamNotifyParentTool(options) {
195
+ return {
196
+ definition: {
197
+ name: teamNotifyParentToolName,
198
+ version: '1',
199
+ description: 'Depth-1 Worker only: send a lightweight non-blocking incremental update to your parent coordinator (main) without terminating or interrupting your own turn. Use this to report key milestones, remote instance quota/cooldown blocks, or cross-challenge clues.',
200
+ inputSchema: {
201
+ type: 'object',
202
+ properties: {
203
+ message: { type: 'string', minLength: 1, maxLength: 4000 },
204
+ kind: {
205
+ type: 'string',
206
+ minLength: 1,
207
+ maxLength: 64,
208
+ description: "Optional category label such as 'milestone', 'blocker', 'quota', 'clue', or 'info'.",
209
+ },
210
+ },
211
+ required: ['message'],
212
+ additionalProperties: false,
213
+ },
214
+ source: { kind: 'builtin' },
215
+ effects: 'read',
216
+ supportsIdempotencyKey: false,
217
+ supportsReconcile: false,
218
+ concurrency: 'serial_per_run',
219
+ timeoutMs: 10000,
220
+ },
221
+ handler: {
222
+ async invoke(input, ctx) {
223
+ const parsed = input;
224
+ const message = typeof parsed?.message === 'string' ? parsed.message.trim() : '';
225
+ if (!message || message.length > 4000) {
226
+ return notifyError('INVALID_INPUT', 'message must be a non-empty string up to 4000 characters');
227
+ }
228
+ const rawKind = parsed?.kind;
229
+ if (rawKind !== undefined &&
230
+ (typeof rawKind !== 'string' || !rawKind.trim() || rawKind.trim().length > 64)) {
231
+ return notifyError('INVALID_INPUT', 'kind must be a non-empty string up to 64 characters');
232
+ }
233
+ const kind = typeof rawKind === 'string' ? rawKind.trim() : undefined;
234
+ const caller = options?.resolveCaller
235
+ ? await options.resolveCaller(ctx)
236
+ : { memberId: 'main', parentId: null, depth: 0 };
237
+ if (caller.depth !== 1 || caller.memberId === 'main' || !caller.parentId) {
238
+ return notifyError('TEAM_NOTIFY_FORBIDDEN', `team_notify_parent is only available to Depth-1 workers (caller "${caller.memberId}" has depth=${caller.depth})`);
239
+ }
240
+ const callKey = (typeof ctx?.executionKey === 'string' && ctx.executionKey.trim()) ||
241
+ (typeof ctx?.attemptId === 'string' && ctx.attemptId.trim()) ||
242
+ `${caller.memberId}:${Date.now()}`;
243
+ const messageId = `${teamNotifyMessagePrefix}${callKey}`;
244
+ const text = kind ? `[${kind}] ${message}` : message;
245
+ await options?.notifyParent?.({
246
+ runId: ctx.runId,
247
+ from: caller.memberId,
248
+ to: caller.parentId,
249
+ messageId,
250
+ text,
251
+ ...(kind ? { kind } : {}),
252
+ });
253
+ return {
254
+ effect: 'applied',
255
+ outcome: {
256
+ status: 'success',
257
+ content: [
258
+ {
259
+ type: 'text',
260
+ text: `Incremental notification (${messageId}) sent to ${caller.parentId}. Continue executing your assigned task.`,
261
+ },
262
+ ],
263
+ data: {
264
+ kind: teamNotifyParentToolName,
265
+ from: caller.memberId,
266
+ to: caller.parentId,
267
+ messageId,
268
+ ...(kind ? { notificationKind: kind } : {}),
269
+ },
270
+ },
271
+ };
272
+ },
273
+ },
274
+ };
275
+ }
276
+ function notifyError(code, message) {
277
+ return {
278
+ effect: 'none',
279
+ outcome: {
280
+ status: 'error',
281
+ error: { code, message, retryable: false },
282
+ },
283
+ };
284
+ }
@@ -0,0 +1,15 @@
1
+ interface Hunk {
2
+ readonly anchor: string | undefined;
3
+ readonly before: string[];
4
+ readonly after: string[];
5
+ eof: boolean;
6
+ }
7
+ export interface FilePatch {
8
+ readonly path: string;
9
+ readonly operation: 'add' | 'update';
10
+ readonly added: string[];
11
+ readonly hunks: Hunk[];
12
+ }
13
+ export declare function parseTextPatch(input: string): FilePatch[];
14
+ export declare function applyTextPatch(patch: FilePatch, original: string): string;
15
+ export {};
@@ -0,0 +1,81 @@
1
+ import { RuntimeError } from '@saturn-universe/core';
2
+ const invalid = (message) => new RuntimeError('INVALID_PATCH', message);
3
+ export function parseTextPatch(input) {
4
+ if (Buffer.byteLength(input) > 256 * 1024)
5
+ throw invalid('Patch exceeds 256 KiB');
6
+ const lines = input.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
7
+ if (lines.shift() !== '*** Begin Patch' || lines.pop() !== '*** End Patch')
8
+ throw invalid('Start with *** Begin Patch and end with *** End Patch');
9
+ const files = [];
10
+ let current;
11
+ let hunk;
12
+ for (const line of lines) {
13
+ const header = /^\*\*\* (Add|Update) File: (.+)$/.exec(line);
14
+ if (header) {
15
+ current = { path: header[2], operation: header[1] === 'Add' ? 'add' : 'update', added: [], hunks: [] };
16
+ files.push(current);
17
+ hunk = undefined;
18
+ continue;
19
+ }
20
+ if (!current)
21
+ throw invalid('Expected a file header');
22
+ if (current.operation === 'add' && line.startsWith('+')) {
23
+ current.added.push(line.slice(1));
24
+ continue;
25
+ }
26
+ if (current.operation === 'update') {
27
+ if (line === '@@' || line.startsWith('@@ ')) {
28
+ hunk = { anchor: line.slice(3) || undefined, before: [], after: [], eof: false };
29
+ current.hunks.push(hunk);
30
+ continue;
31
+ }
32
+ if (hunk && !hunk.eof && line === '*** End of File') {
33
+ hunk.eof = true;
34
+ continue;
35
+ }
36
+ const prefix = line[0];
37
+ if (hunk && !hunk.eof && (prefix === ' ' || prefix === '-' || prefix === '+')) {
38
+ if (prefix !== '+')
39
+ hunk.before.push(line.slice(1));
40
+ if (prefix !== '-')
41
+ hunk.after.push(line.slice(1));
42
+ continue;
43
+ }
44
+ }
45
+ throw invalid('Use @@ to start an update hunk and prefix its lines with space, + or -');
46
+ }
47
+ if (!files.length || files.length > 32)
48
+ throw invalid('Patch must contain 1 to 32 files');
49
+ if (files.some((file) => file.operation === 'update' && (!file.hunks.length || file.hunks.some((item) => !item.before.length))))
50
+ throw invalid('Include at least one original context line in every update hunk');
51
+ return files;
52
+ }
53
+ export function applyTextPatch(patch, original) {
54
+ const eol = original.includes('\r\n') ? '\r\n' : '\n';
55
+ const finalNewline = original.endsWith('\n');
56
+ const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
57
+ let lines = original
58
+ .slice(bom.length)
59
+ .replace(/\r?\n$/, '')
60
+ .split(/\r?\n/);
61
+ let cursor = 0;
62
+ for (const [index, hunk] of patch.hunks.entries()) {
63
+ const start = hunk.anchor === undefined ? cursor : lines.indexOf(hunk.anchor, cursor);
64
+ if (start < 0 || (hunk.anchor !== undefined && lines.indexOf(hunk.anchor, start + 1) >= 0))
65
+ throw new RuntimeError('PATCH_CONTEXT_MISMATCH', 'Hunk anchor must match exactly once');
66
+ let match = -1;
67
+ const limit = lines.length - hunk.before.length;
68
+ for (let row = hunk.eof ? limit : start; row >= start && row <= limit; row++) {
69
+ if (!hunk.before.every((line, offset) => lines[row + offset] === line))
70
+ continue;
71
+ if (match >= 0)
72
+ throw new RuntimeError('PATCH_AMBIGUOUS', 'Hunk ' + (index + 1) + ' matches multiple locations in ' + patch.path);
73
+ match = row;
74
+ }
75
+ if (match < 0)
76
+ throw new RuntimeError('PATCH_CONTEXT_MISMATCH', 'Hunk ' + (index + 1) + ' did not match in ' + patch.path);
77
+ lines = lines.slice(0, match).concat(hunk.after, lines.slice(match + hunk.before.length));
78
+ cursor = match + hunk.after.length;
79
+ }
80
+ return bom + (lines.length ? lines.join(eol) + (finalNewline ? eol : '') : '');
81
+ }
package/dist/todo.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import type { ToolBinding } from '@saturn-universe/core';
2
+ export declare const todoWriteToolName = "todo_write";
3
+ export declare function createTodoWriteTool(): ToolBinding;
package/dist/todo.js ADDED
@@ -0,0 +1,105 @@
1
+ import { isTodoStatus, todoStatuses } from '@saturn-universe/core';
2
+ export const todoWriteToolName = 'todo_write';
3
+ export function createTodoWriteTool() {
4
+ return {
5
+ definition: {
6
+ name: todoWriteToolName,
7
+ version: '1',
8
+ description: `Replace the task checklist for multi-step or complex tasks. Keep each item concise with a unique id and accurate status (${todoStatuses.join(', ')}). Never mark a core user objective as cancelled unless explicitly cancelled by the user or proven blocked by an external error. Skip todo lists on simple, single-step tasks.`,
9
+ inputSchema: {
10
+ type: 'object',
11
+ properties: {
12
+ todos: {
13
+ type: 'array',
14
+ maxItems: 50,
15
+ items: {
16
+ type: 'object',
17
+ properties: {
18
+ id: { type: 'string', minLength: 1, maxLength: 64 },
19
+ content: { type: 'string', minLength: 1, maxLength: 500 },
20
+ status: {
21
+ type: 'string',
22
+ enum: [...todoStatuses],
23
+ },
24
+ },
25
+ required: ['id', 'content', 'status'],
26
+ additionalProperties: false,
27
+ },
28
+ },
29
+ },
30
+ required: ['todos'],
31
+ additionalProperties: false,
32
+ },
33
+ source: { kind: 'builtin' },
34
+ effects: 'read',
35
+ supportsIdempotencyKey: false,
36
+ supportsReconcile: false,
37
+ concurrency: 'serial_per_run',
38
+ timeoutMs: 10000,
39
+ },
40
+ handler: {
41
+ async invoke(input) {
42
+ const parsed = input;
43
+ if (!parsed || !Array.isArray(parsed.todos)) {
44
+ return invalidTodos('todos must be an array');
45
+ }
46
+ if (parsed.todos.length > 50) {
47
+ return invalidTodos('todos must contain at most 50 items');
48
+ }
49
+ const seen = new Set();
50
+ const normalizedTodos = [];
51
+ for (const item of parsed.todos) {
52
+ if (!item || typeof item !== 'object') {
53
+ return invalidTodos('each todo item must be an object');
54
+ }
55
+ if (typeof item.id !== 'string' || typeof item.content !== 'string') {
56
+ return invalidTodos('todo id and content must be strings');
57
+ }
58
+ const id = item.id.trim();
59
+ const content = item.content.trim();
60
+ if (!id || !content) {
61
+ return invalidTodos('todo id and content must not be empty');
62
+ }
63
+ if (id.length > 64 || content.length > 500) {
64
+ return invalidTodos('todo id or content exceeds maximum length');
65
+ }
66
+ if (!isTodoStatus(item.status)) {
67
+ return invalidTodos(`invalid todo status "${String(item.status)}"`);
68
+ }
69
+ if (seen.has(id)) {
70
+ return invalidTodos(`duplicate todo id "${id}"`);
71
+ }
72
+ seen.add(id);
73
+ normalizedTodos.push({ id, content, status: item.status });
74
+ }
75
+ return {
76
+ effect: 'none',
77
+ outcome: {
78
+ status: 'success',
79
+ content: [
80
+ {
81
+ type: 'text',
82
+ text: normalizedTodos.length === 0
83
+ ? 'Todo list cleared (0 items).'
84
+ : `Todo list updated (${normalizedTodos.length} item(s)).`,
85
+ },
86
+ ],
87
+ data: {
88
+ kind: todoWriteToolName,
89
+ todos: normalizedTodos,
90
+ },
91
+ },
92
+ };
93
+ },
94
+ },
95
+ };
96
+ }
97
+ function invalidTodos(message) {
98
+ return {
99
+ effect: 'none',
100
+ outcome: {
101
+ status: 'error',
102
+ error: { code: 'INVALID_ARGUMENTS', message, retryable: false },
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,42 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ export declare const maxDiscoveryResults = 1000;
3
+ export declare const maxContextLines = 5;
4
+ interface SearchScope {
5
+ root: string;
6
+ target: string;
7
+ strictSymlinks?: boolean;
8
+ }
9
+ interface GrepOptions extends SearchScope {
10
+ pattern: string;
11
+ include?: string;
12
+ ignoreCase: boolean;
13
+ contextLines: number;
14
+ limit: number;
15
+ }
16
+ interface SearchLine {
17
+ path: string;
18
+ line: number;
19
+ text: string;
20
+ kind: 'match' | 'context';
21
+ }
22
+ interface GrepResult {
23
+ lines: SearchLine[];
24
+ matchCount: number;
25
+ truncated: boolean;
26
+ }
27
+ interface RipgrepProgram {
28
+ filename: string;
29
+ env: NodeJS.ProcessEnv;
30
+ spawn?: (args: readonly string[], cwd: string, signal: AbortSignal) => ChildProcess;
31
+ mapPath?: (file: string) => string;
32
+ unmapPath?: (filename: string) => string;
33
+ }
34
+ export declare function isDiscoverablePath(relative: string): boolean;
35
+ export declare function globWorkspace({ root, target, strictSymlinks }: SearchScope, pattern: string, limit: number, signal: AbortSignal): Promise<{
36
+ paths: string[];
37
+ totalMatched: number;
38
+ truncated: boolean;
39
+ }>;
40
+ export declare function grepText(result: GrepResult): string;
41
+ export declare function grepWorkspace(options: GrepOptions, signal: AbortSignal, program?: RipgrepProgram): Promise<GrepResult>;
42
+ export {};