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68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
export type CodexToolResolution = {
  name: string;
  input: Record<string, unknown>;
};

export type CodexTodoItem = {
  content: string;
  status: 'pending' | 'in_progress' | 'completed';
  activeForm?: string;
};

const TOOL_NAME_BASH = 'Bash';
const TOOL_NAME_READ = 'Read';
const TOOL_NAME_EDIT = 'Edit';
const TOOL_NAME_WRITE = 'Write';
const TOOL_NAME_GREP = 'Grep';
const TOOL_NAME_GLOB = 'Glob';
const TOOL_NAME_TODO = 'TodoWrite';
const TOOL_NAME_DELETE = 'Delete';
const TOOL_NAME_LS = 'Ls';

const INPUT_KEY_COMMAND = 'command';
const INPUT_KEY_FILE_PATH = 'file_path';
const INPUT_KEY_PATTERN = 'pattern';

const SHELL_WRAPPER_PATTERNS = [
  /^\/bin\/bash\s+-lc\s+["']([\s\S]+)["']$/,
  /^bash\s+-lc\s+["']([\s\S]+)["']$/,
  /^\/bin\/sh\s+-lc\s+["']([\s\S]+)["']$/,
  /^sh\s+-lc\s+["']([\s\S]+)["']$/,
  /^cmd\.exe\s+\/c\s+["']?([\s\S]+)["']?$/i,
  /^powershell(?:\.exe)?\s+-Command\s+["']?([\s\S]+)["']?$/i,
  /^pwsh(?:\.exe)?\s+-Command\s+["']?([\s\S]+)["']?$/i,
] as const;

const COMMAND_SEPARATOR_PATTERN = /\s*(?:&&|\|\||;)\s*/;
const SEGMENT_SKIP_PREFIXES = ['cd ', 'export ', 'set ', 'pushd '] as const;
const WRAPPER_COMMANDS = new Set(['sudo', 'env', 'command']);
const READ_COMMANDS = new Set(['cat', 'sed', 'head', 'tail', 'less', 'more', 'bat', 'stat', 'wc']);
const SEARCH_COMMANDS = new Set(['rg', 'grep', 'ag', 'ack']);
const GLOB_COMMANDS = new Set(['ls', 'find', 'fd', 'tree']);
const DELETE_COMMANDS = new Set(['rm', 'del', 'erase', 'remove', 'unlink']);
const LIST_COMMANDS = new Set(['ls', 'dir', 'll', 'la']);
const WRITE_COMMANDS = new Set(['tee', 'touch', 'mkdir']);
const APPLY_PATCH_COMMAND = 'apply_patch';
const APPLY_PATCH_PATTERN = /\bapply_patch\b/;
const REDIRECTION_TARGET_PATTERN = /(?:>>|>)\s*([^\s]+)/;
const SED_IN_PLACE_FLAGS = new Set(['-i', '--in-place']);
const PERL_IN_PLACE_FLAG = /-.*i/;
const SEARCH_PATTERN_FLAGS = new Set(['-e', '--regexp']);
const SEARCH_VALUE_FLAGS = new Set([
  '-g',
  '--glob',
  '--iglob',
  '--type',
  '--type-add',
  '--type-clear',
  '--encoding',
]);
const SEARCH_FILE_LIST_FLAGS = new Set(['--files']);
const TODO_LINE_PATTERN = /^[-*]\s*(?:\[(?<status>[ x~])\]\s*)?(?<content>.+)$/;
const TODO_STATUS_COMPLETED = 'completed';
const TODO_STATUS_IN_PROGRESS = 'in_progress';
const TODO_STATUS_PENDING = 'pending';
const PATCH_FILE_MARKERS = [
  '*** Update File: ',
  '*** Add File: ',
  '*** Delete File: ',
  '*** Move to: ',
] as const;

function stripShellWrapper(command: string): string {
  const trimmed = command.trim();
  for (const pattern of SHELL_WRAPPER_PATTERNS) {
    const match = trimmed.match(pattern);
    if (match && match[1]) {
      return unescapeCommand(match[1].trim());
    }
  }
  return trimmed;
}

function unescapeCommand(command: string): string {
  return command.replace(/\\(["'])/g, '$1');
}

function extractPrimarySegment(command: string): string {
  const segments = command
    .split(COMMAND_SEPARATOR_PATTERN)
    .map((segment) => segment.trim())
    .filter(Boolean);

  for (const segment of segments) {
    const shouldSkip = SEGMENT_SKIP_PREFIXES.some((prefix) => segment.startsWith(prefix));
    if (!shouldSkip) {
      return segment;
    }
  }

  return command.trim();
}

function tokenizeCommand(command: string): string[] {
  const tokens: string[] = [];
  let current = '';
  let inSingleQuote = false;
  let inDoubleQuote = false;
  let isEscaped = false;

  for (const char of command) {
    if (isEscaped) {
      current += char;
      isEscaped = false;
      continue;
    }

    if (char === '\\') {
      isEscaped = true;
      continue;
    }

    if (char === "'" && !inDoubleQuote) {
      inSingleQuote = !inSingleQuote;
      continue;
    }

    if (char === '"' && !inSingleQuote) {
      inDoubleQuote = !inDoubleQuote;
      continue;
    }

    if (!inSingleQuote && !inDoubleQuote && /\s/.test(char)) {
      if (current) {
        tokens.push(current);
        current = '';
      }
      continue;
    }

    current += char;
  }

  if (current) {
    tokens.push(current);
  }

  return tokens;
}

function stripWrapperTokens(tokens: string[]): string[] {
  let index = 0;
  while (index < tokens.length && WRAPPER_COMMANDS.has(tokens[index].toLowerCase())) {
    index += 1;
  }
  return tokens.slice(index);
}

function extractFilePathFromTokens(tokens: string[]): string | null {
  const candidates = tokens.slice(1).filter((token) => token && !token.startsWith('-'));
  if (candidates.length === 0) return null;
  return candidates[candidates.length - 1];
}

function extractSearchPattern(tokens: string[]): string | null {
  const remaining = tokens.slice(1);

  for (let index = 0; index < remaining.length; index += 1) {
    const token = remaining[index];
    if (token === '--') {
      return remaining[index + 1] ?? null;
    }
    if (SEARCH_PATTERN_FLAGS.has(token)) {
      return remaining[index + 1] ?? null;
    }
    if (SEARCH_VALUE_FLAGS.has(token)) {
      index += 1;
      continue;
    }
    if (token.startsWith('-')) {
      continue;
    }
    return token;
  }

  return null;
}

function extractTeeTarget(tokens: string[]): string | null {
  const teeIndex = tokens.findIndex((token) => token === 'tee');
  if (teeIndex < 0) return null;
  const candidate = tokens[teeIndex + 1];
  return candidate && !candidate.startsWith('-') ? candidate : null;
}

function extractRedirectionTarget(command: string): string | null {
  const match = command.match(REDIRECTION_TARGET_PATTERN);
  return match?.[1] ?? null;
}

function extractFilePathFromDeleteTokens(tokens: string[]): string | null {
  // rm file.txt or rm /path/to/file.txt
  // Skip flags and get the first non-flag argument
  for (let i = 1; i < tokens.length; i++) {
    const token = tokens[i];
    if (token && !token.startsWith('-')) {
      return token;
    }
  }
  return null;
}

function hasSedInPlaceFlag(tokens: string[]): boolean {
  return tokens.some((token) => SED_IN_PLACE_FLAGS.has(token) || token.startsWith('-i'));
}

function hasPerlInPlaceFlag(tokens: string[]): boolean {
  return tokens.some((token) => PERL_IN_PLACE_FLAG.test(token));
}

function extractPatchFilePath(command: string): string | null {
  for (const marker of PATCH_FILE_MARKERS) {
    const index = command.indexOf(marker);
    if (index < 0) continue;
    const start = index + marker.length;
    const end = command.indexOf('\n', start);
    const rawPath = (end === -1 ? command.slice(start) : command.slice(start, end)).trim();
    if (rawPath) return rawPath;
  }
  return null;
}

function buildInputWithFilePath(filePath: string | null): Record<string, unknown> {
  return filePath ? { [INPUT_KEY_FILE_PATH]: filePath } : {};
}

function buildInputWithPattern(pattern: string | null): Record<string, unknown> {
  return pattern ? { [INPUT_KEY_PATTERN]: pattern } : {};
}

export function resolveCodexToolCall(command: string): CodexToolResolution {
  const normalized = stripShellWrapper(command);
  const primarySegment = extractPrimarySegment(normalized);
  const tokens = stripWrapperTokens(tokenizeCommand(primarySegment));
  const commandToken = tokens[0]?.toLowerCase() ?? '';

  const redirectionTarget = extractRedirectionTarget(primarySegment);
  if (redirectionTarget) {
    return {
      name: TOOL_NAME_WRITE,
      input: buildInputWithFilePath(redirectionTarget),
    };
  }

  if (commandToken === APPLY_PATCH_COMMAND || APPLY_PATCH_PATTERN.test(primarySegment)) {
    return {
      name: TOOL_NAME_EDIT,
      input: buildInputWithFilePath(extractPatchFilePath(primarySegment)),
    };
  }

  if (commandToken === 'sed' && hasSedInPlaceFlag(tokens)) {
    return {
      name: TOOL_NAME_EDIT,
      input: buildInputWithFilePath(extractFilePathFromTokens(tokens)),
    };
  }

  if (commandToken === 'perl' && hasPerlInPlaceFlag(tokens)) {
    return {
      name: TOOL_NAME_EDIT,
      input: buildInputWithFilePath(extractFilePathFromTokens(tokens)),
    };
  }

  if (WRITE_COMMANDS.has(commandToken)) {
    const filePath =
      commandToken === 'tee' ? extractTeeTarget(tokens) : extractFilePathFromTokens(tokens);
    return {
      name: TOOL_NAME_WRITE,
      input: buildInputWithFilePath(filePath),
    };
  }

  if (SEARCH_COMMANDS.has(commandToken)) {
    if (tokens.some((token) => SEARCH_FILE_LIST_FLAGS.has(token))) {
      return {
        name: TOOL_NAME_GLOB,
        input: buildInputWithPattern(extractFilePathFromTokens(tokens)),
      };
    }

    return {
      name: TOOL_NAME_GREP,
      input: buildInputWithPattern(extractSearchPattern(tokens)),
    };
  }

  // Handle Delete commands (rm, del, erase, remove, unlink)
  if (DELETE_COMMANDS.has(commandToken)) {
    // Skip if -r or -rf flags (recursive delete should go to Bash)
    if (
      tokens.some((token) => token === '-r' || token === '-rf' || token === '-f' || token === '-rf')
    ) {
      return {
        name: TOOL_NAME_BASH,
        input: { [INPUT_KEY_COMMAND]: normalized },
      };
    }
    // Simple file deletion - extract the file path
    const filePath = extractFilePathFromDeleteTokens(tokens);
    if (filePath) {
      return {
        name: TOOL_NAME_DELETE,
        input: { path: filePath },
      };
    }
    // Fall back to bash if we can't determine the file path
    return {
      name: TOOL_NAME_BASH,
      input: { [INPUT_KEY_COMMAND]: normalized },
    };
  }

  // Handle simple Ls commands (just listing, not find/glob)
  if (LIST_COMMANDS.has(commandToken)) {
    const filePath = extractFilePathFromTokens(tokens);
    return {
      name: TOOL_NAME_LS,
      input: { path: filePath || '.' },
    };
  }

  if (GLOB_COMMANDS.has(commandToken)) {
    return {
      name: TOOL_NAME_GLOB,
      input: buildInputWithPattern(extractFilePathFromTokens(tokens)),
    };
  }

  if (READ_COMMANDS.has(commandToken)) {
    return {
      name: TOOL_NAME_READ,
      input: buildInputWithFilePath(extractFilePathFromTokens(tokens)),
    };
  }

  return {
    name: TOOL_NAME_BASH,
    input: { [INPUT_KEY_COMMAND]: normalized },
  };
}

function parseTodoLines(lines: string[]): CodexTodoItem[] {
  const todos: CodexTodoItem[] = [];

  for (const line of lines) {
    const match = line.match(TODO_LINE_PATTERN);
    if (!match?.groups?.content) continue;

    const statusToken = match.groups.status;
    const status =
      statusToken === 'x'
        ? TODO_STATUS_COMPLETED
        : statusToken === '~'
          ? TODO_STATUS_IN_PROGRESS
          : TODO_STATUS_PENDING;

    todos.push({ content: match.groups.content.trim(), status });
  }

  return todos;
}

function extractTodoFromArray(value: unknown[]): CodexTodoItem[] {
  return value
    .map((entry) => {
      if (typeof entry === 'string') {
        return { content: entry, status: TODO_STATUS_PENDING };
      }
      if (entry && typeof entry === 'object') {
        const record = entry as Record<string, unknown>;
        const content =
          typeof record.content === 'string'
            ? record.content
            : typeof record.text === 'string'
              ? record.text
              : typeof record.title === 'string'
                ? record.title
                : null;
        if (!content) return null;
        const status =
          record.status === TODO_STATUS_COMPLETED ||
          record.status === TODO_STATUS_IN_PROGRESS ||
          record.status === TODO_STATUS_PENDING
            ? (record.status as CodexTodoItem['status'])
            : TODO_STATUS_PENDING;
        const activeForm = typeof record.activeForm === 'string' ? record.activeForm : undefined;
        return { content, status, activeForm };
      }
      return null;
    })
    .filter((item): item is CodexTodoItem => Boolean(item));
}

export function extractCodexTodoItems(item: Record<string, unknown>): CodexTodoItem[] | null {
  const todosValue = item.todos;
  if (Array.isArray(todosValue)) {
    const todos = extractTodoFromArray(todosValue);
    return todos.length > 0 ? todos : null;
  }

  const itemsValue = item.items;
  if (Array.isArray(itemsValue)) {
    const todos = extractTodoFromArray(itemsValue);
    return todos.length > 0 ? todos : null;
  }

  const textValue =
    typeof item.text === 'string'
      ? item.text
      : typeof item.content === 'string'
        ? item.content
        : null;
  if (!textValue) return null;

  const lines = textValue
    .split('\n')
    .map((line) => line.trim())
    .filter(Boolean);
  const todos = parseTodoLines(lines);
  return todos.length > 0 ? todos : null;
}

export function getCodexTodoToolName(): string {
  return TOOL_NAME_TODO;
}