# OfficeCLI Error Codes: How Agents Should Handle Failures and Implement Recovery Logic

> Understand OfficeCLI error codes and implement deterministic error handling. Inspect the stable machine-readable code field for automatic remediation workflows in your agent.

- Repository: [OfficeAI/OfficeCLI](https://github.com/iofficeai/OfficeCLI)
- Tags: api-reference
- Published: 2026-07-20

---

**OfficeCLI returns all failures via a structured JSON envelope containing a stable, machine-readable `code` field that agents must inspect to implement deterministic error handling and automatic remediation workflows.**

OfficeCLI is a command-line interface for programmatic Office document manipulation that enforces strict error protocols. Instead of emitting free-form text to stderr, every failure is wrapped by `OfficeCli.Core.OutputFormatter` in a standardized JSON payload, enabling AI agents and automation scripts to parse errors programmatically and execute context-specific recovery logic without fragile string matching.

## Error Code Architecture and JSON Envelope

OfficeCLI centralizes error formatting in [`src/officecli/Core/OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/OutputFormatter.cs). The `WrapErrorEnvelope` method (lines 66–74) constructs a consistent response structure that separates business logic failures from transport errors.

Every error response follows this schema:

```json
{
  "success": false,
  "error": {
    "error": "Human-readable description",
    "code": "machine_readable_code",
    "suggestion": "Optional remediation hint",
    "help": "null or reference to help documentation",
    "validValues": ["array", "of", "allowed", "values"]
  }
}

```

The `code` field is generated by mapping exceptions to stable identifiers within [`OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/OutputFormatter.cs). When a handler detects an exceptional condition, it either throws a `CliException` (defined in [`src/officecli/Core/CliException.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/CliException.cs)) with an explicit code, or relies on `InferErrorCode` logic to classify unhandled exceptions.

## Complete Reference of OfficeCLI Error Codes

The following table documents every error code emitted by the CLI core, extracted from the source logic in [`OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/OutputFormatter.cs):

| Error Code | Trigger Condition | Source Locations |
|------------|-------------------|------------------|
| **not_found** | Any element, slide, sheet, cell, range, or XPath cannot be located. Includes short-form "X N not found" messages. | Lines 327, 342, 352, 361, 422, 508, 521, 536, 673 |
| **invalid_path** | Document-path, part-path, or selector syntax is malformed or references non-existent parent parts. | Lines 369, 405, 477, 673 |
| **unsupported_type** | Handler cannot process the requested file type, diagram type, or MIME type. | Lines 377, 433, 447, 474 |
| **invalid_value** | Property value, enum, base-64 data, or numeric range violates constraints. | Lines 385, 397, 414, 460, 477, 484, 496, 543, 556, 568, 630, 638, 656, 664, 672, 680, 688, 696 |
| **invalid_input** | Top-level batch payload or field name is malformed. | Lines 645, 659, 678 |
| **invalid_json** | JSON parsing fails for batch body or nested values. | Lines 617, 666, 670 |
| **missing_property** | Required property is absent from the command. | Lines 568, 590, 603, 608, 614, 626 |
| **duplicate_name** | Entity name already exists (e.g., worksheet or defined name collision). | Line 578 |
| **unsupported_property** | Command attempts to set a property the handler does not recognize. | Line 585 |
| **file_not_found** | Required file cannot be opened on the filesystem. | Line 652 |
| **invalid_xpath** | XPath expression is malformed or evaluates to no node-set. | Line 685 |
| **io_error** | I/O exceptions other than `FileNotFoundException` (permissions, path-too-long). | Lines 694, 699 |
| **internal_error** | Unclassified business failure or unexpected exception fallback. | Line 709 |

## How Agents Should Handle Each Error Code

Agents consuming OfficeCLI must implement a switch on `error.code` rather than parsing the `error.error` message string. The following remediation strategies map directly to the error classifications found in [`src/officecli/Core/OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/OutputFormatter.cs):

- **not_found**: Re-query the collection to determine valid index ranges. The `error.suggestion` field typically contains ranges like `"Valid Slide index range: 1-12"` that agents can parse to adjust indices automatically.

- **invalid_path**: Verify path syntax (e.g., `/slide[3]/shape[2]`) and ensure parent parts exist. Consult `error.help` for format-specific documentation links.

- **unsupported_type**: Switch to a supported file or MIME type. Use the CLI's `help` command referenced in `error.help` to enumerate supported types.

- **invalid_value**: Check `error.validValues` for an allowed enumeration, or use `error.suggestion` to clamp numeric inputs to valid ranges.

- **invalid_input** / **invalid_json**: Re-serialize the batch payload, fixing structural mistakes such as missing fields or incorrect JSON types.

- **missing_property**: Add the required property named in `error.suggestion` before retrying the operation.

- **duplicate_name**: Generate a unique name by appending a numeric suffix or UUID, then retry.

- **unsupported_property**: Remove or rename the property; consult `error.help` for the specific handler's supported property list.

- **file_not_found**: Verify the file path exists and is accessible to the process identity before retrying.

- **invalid_xpath**: Rewrite the XPath expression to ensure it selects a valid node-set.

- **io_error**: Check filesystem permissions, path length limits, and drive availability; retry after fixing the environment.

- **internal_error**: Log the full error envelope for debugging, implement exponential backoff, and treat as an unexpected crash requiring manual intervention.

## Batch Processing and Per-Item Error Codes

When executing batch operations, each item may fail independently. According to [`src/officecli/BatchTypes.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/BatchTypes.cs) (lines 10–15), individual `BatchResult` objects contain their own `code` field using the same error vocabulary defined above.

If a batch item returns a `null` code, the agent must fall back to the plain `error` text, as the failure could not be classified by [`CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/CommandBuilder.Batch.cs) or the `InferErrorCode` logic.

Example batch error handling:

```csharp
var envelope = JsonSerializer.Deserialize<Root>(json, BatchJsonContext.Default.Root);
if (!envelope.Success && envelope.Error?.Code == "invalid_json")
{
    // Fix the payload structure then re-run the batch
    var correctedPayload = FixJsonStructure(rawPayload);
    return await ExecuteBatch(correctedPayload);
}

```

## Implementation Examples for Agent Integration

### Detecting and Routing Errors in JavaScript

```javascript
function handleOfficeCliResponse(resp) {
  if (resp.success) return resp.data;  // Normal path
  
  const err = resp.error;
  
  switch (err.code) {
    case 'not_found':
      // Parse suggestion for valid range
      const match = err.suggestion?.match(/range: (\d+)-(\d+)/);
      if (match) {
        const [min, max] = [parseInt(match[1]), parseInt(match[2])];
        return retryWithValidIndex(min, max);
      }
      break;
      
    case 'invalid_value':
      // Use server-provided valid values
      if (err.validValues?.length) {
        return retryWithValue(err.validValues[0]);
      }
      break;
      
    case 'duplicate_name':
      return retryWithName(generateUniqueName());
      
    case 'file_not_found':
      if (!fs.existsSync(request.path)) {
        throw new Error(`Path inaccessible: ${request.path}`);
      }
      break;
      
    default:
      // Handle io_error, internal_error, etc.
      logFatalError(err);
      throw err;
  }
}

```

### C# Agent Integration Pattern

```csharp
using System.Text.Json;
using OfficeCli.Core;

public class OfficeCliAgent
{
    public async Task<T> ExecuteWithRetry<T>(string command)
    {
        var result = await _cli.Execute(command);
        
        if (result.Success) 
            return JsonSerializer.Deserialize<T>(result.Data);
            
        var code = result.Error.Code;
        var suggestion = result.Error.Suggestion;
        
        return code switch
        {
            "missing_property" => await RetryWithPropertyAdded(suggestion),
            "invalid_path" => await RetryWithNormalizedPath(command),
            "not_found" => await RetryWithValidIndex(suggestion),
            _ => throw new OfficeCliException(code, result.Error.Error)
        };
    }
}

```

## Key Source Files for Error Handling

Understanding the OfficeCLI error system requires familiarity with these implementation files:

- **[`src/officecli/Core/OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/OutputFormatter.cs)** – Contains `WrapErrorEnvelope` and `InferErrorCode` logic that maps exceptions to stable codes and constructs the JSON response envelope.
- **[`src/officecli/Core/CliException.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/CliException.cs)** – Defines the typed exception used when handlers need to specify an error code explicitly.
- **[`src/officecli/BatchTypes.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/BatchTypes.cs)** – Declares `BatchResult` class with per-item `code` support for batch operations.
- **[`src/officecli/ResidentServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/ResidentServer.cs)** – Entry point that determines OS process exit codes (0, 1, 2); agents should prioritize the JSON envelope over exit codes.
- **[`src/officecli/CommandBuilder.Batch.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/CommandBuilder.Batch.cs)** – Propagates per-item failure codes through `InferErrorCode` for batch result items.

## Summary

- OfficeCLI returns **machine-readable error codes** via a JSON envelope containing `success`, `error.code`, and remediation metadata.
- The **13 stable error codes** (including `not_found`, `invalid_value`, and `io_error`) are defined in [`OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/OutputFormatter.cs) and cover all failure modes from XPath errors to filesystem permissions.
- Agents must inspect `error.code` to implement **deterministic remediation** such as index adjustment, value clamping, or automatic renaming.
- **Batch operations** return per-item codes via `BatchResult` objects; a `null` code indicates an unclassified failure requiring fallback to message text.
- **Never parse error messages**; always use the `code` field combined with `suggestion` and `validValues` for recovery logic.

## Frequently Asked Questions

### What is the structure of an OfficeCLI error response?

OfficeCLI returns a JSON object with a top-level `success` boolean set to `false`. The `error` property contains `code` (machine-readable string), `error` (human-readable message), `suggestion` (optional fix hint), `help` (documentation reference), and `validValues` (array of allowed inputs). This structure is generated by `WrapErrorEnvelope` in [`src/officecli/Core/OutputFormatter.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/Core/OutputFormatter.cs).

### How should an agent respond to a "not_found" error?

When receiving `code: "not_found"`, the agent should parse the `suggestion` field for valid index ranges (e.g., "Valid Slide index range: 1-12"), re-query the document to confirm current bounds, and adjust the request index to fall within the valid range before retrying. This handles cases where slides or cells have been deleted since the last document inspection.

### What is the difference between "invalid_input" and "invalid_json"?

`invalid_input` indicates semantic errors in the batch payload structure, such as missing required fields or malformed field names, while `invalid_json` indicates syntactic parsing failures where the request body could not be deserialized into JSON. Agents should re-serialize the payload for `invalid_json`, whereas `invalid_input` requires schema validation against the command specification.

### Should agents rely on OS exit codes or the JSON envelope?

Agents should prioritize the **JSON envelope** for error detection. While [`src/officecli/ResidentServer.cs`](https://github.com/iOfficeAI/OfficeCLI/blob/main/src/officecli/ResidentServer.cs) sets OS exit codes (`0` for success, `1` for known errors, `2` for unhandled exceptions), the JSON envelope provides granular `code` values, `suggestion` text, and `validValues` necessary for programmatic remediation that exit codes cannot convey.