FoundationAgents/MetaGPT · error · LineNumberError

Invalid line number: {start}. Line numbers must be between 1

Error message

Invalid line number: {start}. Line numbers must be between 1 and {len(lines)} (inclusive).

What it means

Raised by Editor._insert_impl when inserting into a non-empty file but start is None, so there is no anchor line to insert at. The insert algorithm needs a 1-based line position; with an empty file it can place content outright, but with existing lines and no start it cannot decide where to insert, so it raises LineNumberError.

Source

Thrown at metagpt/tools/libs/editor.py:427

            n_added_lines: int: The number of lines added to the file.

        Raises:
            LineNumberError: If the start line number is invalid.
        """
        inserted_lines = [content + "\n" if not content.endswith("\n") else content]
        if len(lines) == 0:
            new_lines = inserted_lines
        elif start is not None:
            if len(lines) == 1 and lines[0].strip() == "":
                # if the file with only 1 line and that line is empty
                lines = []

            if len(lines) == 0:
                new_lines = inserted_lines
            else:
                new_lines = lines[: start - 1] + inserted_lines + lines[start - 1 :]
        else:
            raise LineNumberError(
                f"Invalid line number: {start}. Line numbers must be between 1 and {len(lines)} (inclusive)."
            )

        content = "".join(new_lines)
        n_added_lines = len(inserted_lines)
        return content, n_added_lines

    @staticmethod
    def _edit_impl(lines, start, end, content):
        """Internal method to handle editing a file.

        REQUIRES (should be checked by caller):
            start <= end
            start and end are between 1 and len(lines) (inclusive)
            content ends with a newline

        Args:
            lines: list[str]: The lines in the original file.

View on GitHub (pinned to 11cdf466d0)

Solutions

  1. Always supply a start line (1..len(lines)) when inserting into a non-empty file
  2. To add at the end, use the append mode instead of insert with no start
  3. For a truly empty file, either keep it empty-then-insert (allowed) or create content directly

Example fix

// before
editor.insert_content_at('new line')  # start omitted on non-empty file

// after
editor.insert_content_at('new line', line_number=len(lines) + 1)  # or use append
Defensive patterns

Strategy: validation

Validate before calling

lines = editor.current_file.read_text().splitlines()
start = len(lines) + 1 if start is None else start
assert 1 <= start <= max(1, len(lines) + 1)
# then perform insert via editor API with explicit line_number

Type guard

def has_insert_anchor(start, n_lines: int) -> bool:
    return start is not None and 1 <= start <= n_lines + 1

Try / catch

try:
    result = editor.insert_content_at(content, line_number=start)
except LineNumberError:
    result = editor.append_file(content)  # append when no anchor fits

Prevention

When it happens

Trigger: Calling the insert path (insert_content_at / _edit_file_impl with is_insert=True) without a line number on a file that has content; passing start=None explicitly; a caller bug where the start argument is dropped.

Common situations: Agent tool calls that omit the line parameter when inserting; wrappers with defaulted start=None forwarding None into insert.

Related errors


AI-assisted analysis of FoundationAgents/MetaGPT@11cdf466d0 (2026-08-14). Data as JSON: /api/errors/f007d8a8520f3c9f. Report an issue: GitHub.