Tritium Web API (v 3.0.0)


Initialize Tritium

Tritium can be embedded in a web application as a WebAssembly-powered editor. Follow the basic installation instructions at tritium.legal/wasm, including adding a canvas with the ID tritium-canvas. Import the bundle as an ES module and await the import before using the API:

<canvas id="tritium-canvas"></canvas>

<script type="module">
  const tritium = await import("https://tritium.legal/static/init.js");

  await tritium.start();
</script>

The awaited import initializes the WebAssembly bundle. Awaiting start() then launches Tritium in the canvas and resolves when the editor is ready. Calling it without an argument uses the default launch settings.

Adjust Settings

Each setting is optional. Omitted settings retain their default value.

interface Identity {
  /** Author's given name. Defaults to `null`. */
  firstName?: string | null;
  /** Author's family name. Defaults to `null`. */
  lastName?: string | null;
  /** Author's organization. Defaults to `null`. */
  organization?: string | null;
}

interface AutoSaveSettings {
  /** Wait after the last edit before requesting a save, in milliseconds. Defaults to 3000. */
  debounceMs?: number;
}

interface Settings {
  /** Author information used for document changes and comments. Defaults to an empty identity. */
  identity?: Identity;
  /** Makes the host responsible for editing permission. Defaults to `false`.
   * 
   * NOTE: This setting cannot be modified in the application, and a restart is required to affect 
   * a change.
  */
  hostManagesCheckout?: boolean;
  /** Automatically requests a save after edits. Set to `null` to disable. Defaults to `{ debounceMs: 3000 }`. */
  autoSaveSettings?: AutoSaveSettings | null;
  /** Shows the Tritium logo in the application. Defaults to `true`. */
  showLogo?: boolean;
  /** Shows a dark frame with dark page background with light text. Defaults to `false`. */
  darkMode?: boolean;
  /** Shows formatting marks in documents. Defaults to `true`. */
  formattingMarks?: boolean;
  /** Produces blacklines instead of colored redlines. Defaults to `false`. */
  blacklineMode?: boolean;
  /** Records tool edits as tracked changes. Defaults to `true`. */
  trackToolEdits?: boolean;
  /** Configures and enables the in-app assistant. Defaults to `null`. */
  provider?: Provider | null;
  /** Internal configuration values. */
  installId?: string;
  recentFolders?: string[];
  recentFiles?: string[];
  panels?: string[][];
  cleanExit?: boolean;
  authToken?: string | null;
}

The main user-facing settings are:

PropertyDefaultPurpose
identityEmpty identityAuthor information used for document changes and comments.
hostManagesCheckoutfalseHost controls editing permission. Documents start read-only unless loaded with isCheckedOut: true; checkout/check-in emit requests without changing permission.
autoSaveSettings{ debounceMs: 3000 }Request a save after 3 seconds without edits; set to null to disable.
showLogotrueShow the Tritium logo in the application.
darkModefalseShow white text on a dark page background.
formattingMarkstrueShows formatting marks in documents.
blacklineModefalseProduce blacklines instead of redlines.
trackToolEditstrueRender tool edits as tracked changes.
providernullConfigures and enables the in-app assistant.

The remaining properties represent installation, authentication, or session state and are for internal use.

Auto-save applies to edited DOCX documents that already have a path and are neither generated nor read-only. It makes one save attempt after editing stops for debounceMs milliseconds; a further edit permits another attempt. In the WebAssembly build, the attempt calls setSaveHandler; the host is responsible for persisting the file. A newly created document without a path is not auto-saved.

Configure the Assistant

The in-application assistant is disabled by default in the WebAssembly build. It is enabled only when settings.provider is supplied.

To connect the assistant to your own backend, use a Custom provider and set its url to your endpoint:

await tritium.start({
  settings: {
    provider: {
      Custom: {
        name: "Example assistant",
        url: "https://assistant.example.com/v1/chat/completions",
        model: "example-model",
        token: "optional-bearer-token",
        location: "memory",
        payloadType: "json",
      },
    },
  },
});

The provider schema is:

type Provider =
  | { Tritium: ProviderConfiguration }
  | { OpenAI: ProviderConfiguration }
  | { Claude: ProviderConfiguration }
  | { DeepSeek: ProviderConfiguration }
  | { Gemini: ProviderConfiguration }
  | { Custom: ProviderConfiguration };

interface ProviderConfiguration {
  name?: string;
  token?: string | null;
  model?: string | null;
  url?: string;
  queryParameters?: [string, string][];
  location?: "memory" | { file: string };
  payloadType?: "json" | "form";
}

A custom endpoint must implement the OpenAI Chat Completions API, including streamed Server-Sent Events and OpenAI-style tool calls. The integration will not work with an incompatible request or response format.

Tritium sends token, when present, as a bearer token. Because WebAssembly runs in the browser, the endpoint must also permit requests from the embedding application's origin. Avoid placing long-lived secrets in client-side code; a backend-controlled short-lived credential or authenticated proxy is preferable.

Start Tritium

start(options?: LaunchOptions): Promise<void>

All launch options are optional:

interface LaunchOptions {
  folder?: string;
  documents?: Document[];
  settings?: Settings;
}
  • folder is the logical path of the folder to show in Tritium's library.
  • documents contains Document objects, each wrapping a browser File and an optional ID. Without folder, the documents are opened directly. With folder, they are loaded as documents in that folder.
  • settings overrides Tritium's defaults for this launch.

For example, an application can start Tritium with files selected by the user:

const documents = Array.from(fileInput.files ?? [], file => ({ file }));

await tritium.start({
  folder: "matter-123",
  documents,
  settings: {
    darkMode: true,
    formattingMarks: false,
    identity: {
      firstName: "Alex",
      lastName: "Morgan",
      organization: "Example LLP",
    },
  },
});

Always await start() before calling other session APIs.

Open Documents and Folders

The following APIs add documents to a running Tritium session. Await start() before using them.

addDocument and openDocument (alias: openFile)

type DocumentId = string;

interface Document {
  file: File;
  id?: DocumentId;
  isCheckedOut?: boolean;
}

addDocument(document: Document): Promise<void>
openDocument(document: Document): Promise<void>
openFile(document: Document): Promise<void> // Backward-compatible alias

addDocument reads the browser file in document.file and adds it to the session Library without creating a tab, showing it, or changing the active document. Adding an existing ID preserves its contents and UI state. Browser file paths are placed beneath the logical Library folder when one is set, matching the launch behavior.

openDocument is the compatibility composite: add if absent, ensure a tab exists, show it, and activate it. openFile remains an alias with identical behavior. Pass your backend identifier in document.id, or omit it to generate a UUID v4. IDs can be arbitrary strings; they do not have to be UUIDs.

PDF (.pdf) and Markdown (.md) files can also be opened and rendered for viewing only.

  • openDocument activates an existing document with the same ID and retains its contents; addDocument leaves its UI state unchanged.
  • Different IDs add separate documents even when their filenames match. Omitting the ID gives each incoming document a new UUID.

IDs remain stable through edits, renaming, and saving. list_documents exposes them, and the save handler receives a Document with its ID populated. Persist the ID in your backend and supply it when reopening to retain identity across sessions. IDs are not embedded in file contents.

await tritium.addDocument({ file: versionA, id: "resolution-v1" }); // No tab
await tritium.openDocument({ file: versionB, id: "resolution-v2" });
await tritium.openDocument({ file: new File([bytes], "draft.docx") });

These file-ingestion promises complete after reading and enqueueing the input; document initialization and workspace updates are applied by the application loop, as with the existing openDocument API. Use list_documents to observe initialized session documents.

removeDocument (WebAssembly only)

removeDocument(documentId: DocumentId): Promise<ToolResult>

Removes a document from the session, including its tabs and Library entry, without saving or deleting its source file or backend record. Unsaved changes are discarded. This is a convenience wrapper for callTool("remove_document", { documentId }) and returns the same structured result. Native builds do not expose this operation.

openFolder

openFolder(path: string, documents: Document[]): Promise<void>

Sets the logical Library folder and adds its Document objects without creating tabs or activating them. Each object carries its own optional ID.

Use Tools

A document is open when it is available in the session and appears in list_documents. It is tabbed when it has a tab in a document panel, including a background tab. It is showing when its content is currently visible in a panel. The active document is the one selected for user interaction. active: false does not imply that the document has no tab.

Library documents remain open when their tabs are closed and can still be read, searched, edited, saved, and compared through tools. Existing directory placement rules still apply: documents within the Library directory (or supplied when no root directory is set) belong to the Library; documents outside it may be owned only by their tabs and leave the session when those tabs close.

After Tritium has been started, getToolCatalog() returns the available tools. Each entry includes the tool's name, description, input schema, and whether it can modify a document:

interface ToolCatalog {
  apiVersion: "3.0.0";
  tools: ToolDefinition[];
}

interface ToolDefinition {
  name: string;
  description: string;
  modifiesDocument: boolean;
  inputSchema: Record<string, unknown>;
}

Use the returned inputSchema to construct valid arguments, then invoke the tool by name with callTool(name, args). Arguments must be JSON-serializable. Tool names such as list_documents remain snake_case protocol identifiers; argument and result properties use camelCase.

const catalog = tritium.getToolCatalog();
const tool = catalog.tools.find(({ name }) => name === "list_documents");

if (!tool) {
  throw new Error("This Tritium build does not provide list_documents");
}

const result = await tritium.callTool(tool.name /* i.e., "list_documents" */, {});
const outcome = result.output;

if (outcome.ok) {
  console.log(outcome.data);
  console.log(result.displayText);
} else {
  console.error(outcome.error.code, outcome.error.message);
}

callTool() always resolves to a ToolResult, including for invalid calls and execution failures. Inspect the discriminated output union to determine whether the call succeeded:

interface ToolResult {
  output: ToolCallOutput;
  displayText: string;
}

type ToolCallOutput =
  | {
      ok: true;
      data: unknown;
    }
  | {
      ok: false;
      error: {
        code:
          | "not_running"
          | "not_ready"
          | "cancelled"
          | "unknown_tool"
          | "invalid_arguments"
          | "execution_failed"
          | "apply_failed"
          | "unsupported_effect"
          | "stale_segment_ids";
        message: string;
        retryable: boolean;
      };
    };

displayText is a short human-readable summary for logs or UI. The structured output.data value is the result intended for programmatic use or for returning to an LLM. Tool-specific data uses camelCase property names, for example documentId, segmentCount, and segmentIdsStale.

The catalog is the source of truth for the tools and argument schemas in the loaded bundle. Check result.output.ok before accessing data, and do not assume that every release exposes the same catalog.

Document and segment identifiers

Call list_documents to obtain document IDs before invoking document-specific tools. read_document returns structured data in the form described below.

Call read_document with camelCase arguments, for example callTool("read_document", { documentId: "backend-contract-123" }).

Segment IDs describe the document state returned by the read call. After a modifying tool succeeds, its data contains segmentIdsStale: true; read the document again before issuing another segment-based edit.

Save, Workspace, Exit and Error Handlers

Register optional host event handlers before calling start() so the host can observe the entire Tritium session.

All handler setters replace the previously registered callback. Pass null or undefined, or omit the argument, to clear a callback (None from Rust). A cleared handler can be registered again later.

setSaveHandler

type SaveHandler = (document: Document & { id: DocumentId }) => void;

setSaveHandler(handler?: SaveHandler | null): void

Register a save handler so the host application can persist documents. Tritium passes one Document object with a browser File in file and the document's required string ID in id. The file's name, type, size, and contents are available through the standard File API. The ID is either caller-supplied or generated, including for documents created inside Tritium.

tritium.setSaveHandler(({ file, id }) => {
  console.log(`Saving ${file.name} (${file.size} bytes)`);
  uploadSavedFile(id, file);
});

setWorkspaceActionHandler

type WorkspaceActionKind =
  | "addDocument"
  | "openDocument"
  | "openSideTab"
  | "openTab"
  | "showDocument"
  | "activateDocument"
  | "selectTab"
  | "closeDocumentTabs"
  | "closeOrUnpin"
  | "closeOthers"
  | "closeToTheRight"
  | "closeAll"
  | "moveRight"
  | "swapDocuments"
  | "setPinned"
  | "openDirectory"
  | "openArchive"
  | "deleteDocument"
  | "renameDocument"
  | "duplicateDocument"
  | "pasteDocument"
  | "revertDocument"
  | "openSideTabAtLocation"
  | "clear"
  | "applyEdits"
  | "requestRedline"
  | "scrollToLocation"
  | "removeDocument"
  | "saveDocument"
  | "checkOutRequested"
  | "checkInRequested";

type WorkspaceActionOrigin = "user" | "host" | "agent";

interface WorkspaceActionEvent {
  action: WorkspaceActionKind;
  origin: WorkspaceActionOrigin;
  documentIds: DocumentId[];
  /** Present on checkout/check-in requests. */
  requestId?: string;
}

type WorkspaceActionHandler = (event: WorkspaceActionEvent) => void;

setWorkspaceActionHandler(handler?: WorkspaceActionHandler | null): void

Register a handler to receive notifications for successfully applied workspace actions and checkout/check-in requests, in queue order. Failed actions and ignored stale UI actions do not produce notifications. No handler is registered by default; registering another replaces the previous handler. Pass null or undefined, or call the setter without an argument, to disable notifications.

documentIds contains unique IDs for the action's explicit document targets and documents whose session membership, tabs, visibility, activation, or pinning changed. For example, closeOthers can include the closed documents as well as the selected document, and requestRedline includes the source documents and the newly generated redline. IDs can refer to documents that have been removed from the session, and the array can be empty.

origin identifies how the workspace action was queued:

ValueSource
"user"The editor's default action queue, including UI actions and document loading.
"host"Workspace actions produced by host-issued tool calls.
"agent"Workspace actions produced by the in-app assistant.

Hosts can use origin to avoid echoing their own tool actions back to Tritium. File-loading APIs such as openDocument use the default queue, so their resulting actions can have origin "user".

tritium.setWorkspaceActionHandler(({ action, origin, documentIds }) => {
  console.log("Tritium workspace action", { action, origin, documentIds });
});

// Disable notifications when no longer needed.
tritium.setWorkspaceActionHandler(null);

The handler receives applied workspace actions and checkout/check-in requests. Its return value is ignored and is not awaited. Exceptions thrown by the handler are logged without interrupting subsequent actions; the host should handle failures from its own asynchronous work.

These notifications report workspace commands, not every document edit or completion of file persistence. Continue to use setSaveHandler to persist saved files. Event objects may gain additional fields or data, and future versions may add action kinds; consume the fields you need and ignore unrecognized kinds.

openArchive replaces the library root while retaining existing tabs. deleteDocument deletes the source file and removes the document from the workspace; it is distinct from removeDocument, which preserves the source. renameDocument, duplicateDocument, and pasteDocument report successful filesystem commands; documents discovered as a result can produce later loading events. Paste captures the clipboard when requested, and its explicit document target is the destination sibling. revertDocument restores the document's history baseline and requests saving when it has a path. openSideTabAtLocation opens or moves the target into a side panel and navigates to the requested location in one action.

setExitHandler

setExitHandler(handler?: (() => void) | null): void

Register an exit handler to restore the host application's UI or perform other cleanup after Tritium shuts down:

tritium.setExitHandler(() => {
  document.querySelector("#host-application").hidden = false;
});

Call tritium.shutdown() to close the current Tritium session. Shutdown removes the editor session and then invokes the registered exit handler. Tritium does not modify browser history.

setDocumentErrorHandler

type DocumentErrorCode =
  | "parse_error"
  | "initialization_failed"
  | "unsupported_format";

interface DocumentError {
  code: DocumentErrorCode;
  message: string;
  path: string | null;
}

setDocumentErrorHandler(handler?: ((error: DocumentError) => void) | null): void

Register a document error handler so the host application can report failures to open or initialize documents. code is a machine-readable category, message describes the failure, and path identifies the affected document when available.

tritium.setDocumentErrorHandler(({ code, message, path }) => {
  console.error(`Tritium document error (${code})`, { message, path });
});

The handler is called synchronously. Its return value is not awaited, so the host should handle failures from any asynchronous reporting itself.

setPanicHandler

interface PanicReport {
  summary: string;
  detail: string;
}

setPanicHandler(handler?: ((report: PanicReport) => void) | null): void

Register a panic handler so the host application can capture an unexpected internal Tritium failure. summary contains the panic message, while detail includes diagnostic context such as the source location and, when available, a backtrace.

tritium.setPanicHandler(({ summary, detail }) => {
  console.error(`Tritium panicked: ${summary}`, { detail });
});

The handler is called synchronously while Tritium is processing the panic. Its return value is not awaited. The panic continues after the handler returns, so the host should not assume that the current Tritium session remains usable.

Register panic, document error, save, workspace action, and exit handlers before calling start(). Each handler is optional:

const tritium = await import("https://tritium.legal/static/init.js");

tritium.setPanicHandler(handlePanic);
tritium.setDocumentErrorHandler(handleDocumentError);
tritium.setSaveHandler(handleSavedDocument);
tritium.setWorkspaceActionHandler(handleWorkspaceAction);
tritium.setExitHandler(handleTritiumExit);
await tritium.start();

Future versions of this API will add these handlers to the launch settings.

Tool Description

The following tools are available in the current build, but they may be added, removed, or changed in future releases.

Agents should call getToolCatalog() at runtime and treat its returned names, descriptions, and input schemas as canonical. This section describes the current API, but runtime discovery is preferred.

Every tool is invoked with callTool(name, args) and returns a ToolResult.

list_documents

callTool(name: "list_documents", args: Record<string, never>): Promise<ToolResult>

Lists all documents open in the session, including documents without tabs. Successful result data contains a documents array whose entries have id, filename, tabbed, active, and nullable path properties. tabbed reports tab membership, not whether the document's content is currently showing. Use the stable id to correlate documents with your backend and as documentId in document-specific tool calls.

await tritium.callTool("list_documents", {})
/*
{
  output: {
    ok: true,
    data: {
      documents: [
        { id: "backend-contract-123", filename: "contract.docx", tabbed: true, active: true, path: "/matter/contract.docx" },
        { id: "67e55044-10b1-426f-9247-bb680e5fe0c8", filename: "schedule.docx", tabbed: false, active: false, path: "/matter/schedule.docx" }
      ]
    }
  },
  displayText: "Listed 2 open document(s)."
}
*/

read_document

callTool(name: "read_document", args: { documentId: DocumentId }): Promise<ToolResult>

Reads every segment in a document. Successful result data contains documentId, filename, segmentCount, a segments array of { id, text } objects, a comments array mirroring the comments returned via the list_comments tool call, and a revisions array mirroring the revisions returned via the list_revisions tool call.

await tritium.callTool("read_document", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: {
      documentId: "backend-contract-123",
      filename: "contract.docx",
      segmentCount: 2,
      segments: [
        { id: 0, text: "Services Agreement" },
        { id: 1, text: "This agreement begins on 1 September 2026." }
      ],
      comments: [{
        id: "0",
        author: "Alex Morgan",
        date: "2026-09-21T10:30:00Z",
        content: "Please confirm this date.",
        startSegment: 1,
        endSegment: 2
      }],
      revisions: [{
        id: "2",
        revisionType: "insertion",
        author: "Alex Morgan",
        date: "2026-09-21T10:30:00Z",
        startSegment: 1,
        endSegment: 2
      }]
    }
  },
  displayText: "Read 2 segment(s) from \"contract.docx\"."
}
*/

list_comments

callTool(name: "list_comments", args: { documentId: DocumentId }): Promise<ToolResult>

Lists all comments in a DOCX document. Call list_documents first to obtain the document ID. Comments are not currently supported for PDF or Markdown documents.

Successful result data contains documentId, commentCount, and a comments array. Each comment contains its string id, author, nullable date, text content, startSegment, and nullable endSegment. A point comment has a null endSegment.

await tritium.callTool("list_comments", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: {
      documentId: "backend-contract-123",
      commentCount: 1,
      comments: [{
        id: "0",
        author: "Alex Morgan",
        date: "2026-09-21T10:30:00Z",
        content: "Please confirm this date.",
        startSegment: 1,
        endSegment: 2
      }]
    }
  },
  displayText: "Read 1 comment(s) from \"contract.docx\"."
}
*/

list_revisions

callTool(name: "list_revisions", args: { documentId: DocumentId }): Promise<ToolResult>

Lists all tracked changes in a DOCX document. Call list_documents first to obtain the document ID. Revisions are not currently supported for PDF or Markdown documents.

Successful result data contains documentId, revisionsCount, and a revisions array. Each revision contains its string id, a revisionType of "insertion" or "deletion", nullable author and date values, startSegment, and nullable endSegment.

await tritium.callTool("list_revisions", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: {
      documentId: "backend-contract-123",
      revisionsCount: 1,
      revisions: [{
        id: "2",
        revisionType: "insertion",
        author: "Alex Morgan",
        date: "2026-09-21T10:30:00Z",
        startSegment: 1,
        endSegment: 2
      }]
    }
  },
  displayText: "Read 1 revision(s) from \"contract.docx\"."
}
*/

accept_revision and reject_revision

callTool(name: "accept_revision" | "reject_revision", args: {
  documentId: DocumentId;
  revisionId: string;
}): Promise<ToolResult>

Accepts or rejects one tracked change in a DOCX document. Obtain the document ID from list_documents and the string revisionId from list_revisions (or the revisions array returned by read_document). PDF and Markdown documents do not support revision review.

ToolInsertionDeletion
accept_revisionKeep the inserted text and remove its revision marking.Remove the deleted text.
reject_revisionRemove the inserted text.Restore the deleted text and remove its revision marking.

Each call targets only the specified revision. Nested tracked changes within retained content remain unresolved; removing content also removes any revisions inside that content.

Successful result data contains status: "accepted", documentId, revisionId, and segmentIdsStale: true. Both tools modify the document and use the applyEdits workspace action. Read the document again after each successful call to refresh segment IDs, and refresh the revision list before selecting another revision. An unknown document ID, a missing revision ID, or an ambiguous revision ID returns an error; if a revision is missing, call list_revisions again to obtain current IDs.

await tritium.callTool("accept_revision", {
  documentId: "backend-contract-123",
  revisionId: "2",
})
/*
{
  output: {
    ok: true,
    data: {
      status: "accepted",
      documentId: "backend-contract-123",
      revisionId: "2",
      segmentIdsStale: true
    }
  },
  displayText: "Queued 1 accept_revision edit(s) for document backend-contract-123."
}
*/

To reject a revision instead, use the same arguments with reject_revision:

await tritium.callTool("reject_revision", {
  documentId: "backend-contract-123",
  revisionId: "3",
})
/*
{
  output: {
    ok: true,
    data: {
      status: "accepted",
      documentId: "backend-contract-123",
      revisionId: "3",
      segmentIdsStale: true
    }
  },
  displayText: "Queued 1 reject_revision edit(s) for document backend-contract-123."
}
*/

read_segments

callTool(name: "read_segments", args: { documentId: DocumentId; startId: number; endId: number }): Promise<ToolResult>

Reads an inclusive range of segments. Successful result data contains documentId, the requestedRange, and the matching segments.

await tritium.callTool("read_segments", {
  documentId: "backend-contract-123",
  startId: 10,
  endId: 20,
})
/*
{
  output: {
    ok: true,
    data: {
      documentId: "backend-contract-123",
      requestedRange: { startId: 10, endId: 20 },
      segments: [
        { id: 10, text: "10. Confidentiality" },
        { id: 11, text: "Each party must keep information confidential." }
      ]
    }
  },
  displayText: "Read 2 segment(s) from range [10, 20]."
}
*/

search_text

callTool(name: "search_text", args: { query: string; documentId?: DocumentId }): Promise<ToolResult>

Searches for a case-insensitive substring across every open document, or within one document when documentId is supplied. Successful result data contains query, totalMatches, and matching documents (identified by id) and segments.

await tritium.callTool("search_text", {
  query: "termination",
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: {
      query: "termination",
      totalMatches: 1,
      documents: [{
        id: "backend-contract-123",
        filename: "contract.docx",
        segments: [{ id: 24, text: "Either party may terminate on 30 days' notice." }]
      }]
    }
  },
  displayText: "Found 1 matching segment(s)."
}
*/

Document view tools

callTool(name: "open_tab" | "show_document" | "activate_document", args: {
  documentId: DocumentId
}): Promise<ToolResult>

These tools operate on documents already in the session; obtain their IDs from list_documents.

ToolEffect
open_tabCreate a background tab without showing or activating the document. If already tabbed, leave its UI state unchanged.
show_documentSelect an existing tab within its panel without focusing another panel. If the panel is active or no document is active, the selected document becomes active. Returns an error if the document has no tab.
activate_documentEnsure a tab exists, show the document, and make it active.

Successful result data is { status: "accepted", documentId }. None of these operations changes document contents or saves the document.

close_document_tabs (alias: close_document)

callTool(name: "close_document_tabs", args: { documentId: DocumentId }): Promise<ToolResult>

Closes all of a document's tabs by its ID. Call list_documents first to obtain the ID. Library documents remain open in the session and listed with tabbed: false; closing an already untabbed Library document is a successful no-op. Documents owned only by their tabs leave the session when closed. Closing tabs does not save the document first. close_document remains a compatibility alias; the tool catalog advertises only close_document_tabs.

await tritium.callTool("close_document_tabs", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123" }
  },
  displayText: "Queued closing document tabs: \"contract.docx\""
}
*/

remove_document (WebAssembly only)

callTool(name: "remove_document", args: { documentId: DocumentId }): Promise<ToolResult>

Removes a document from the session, closing its tabs and removing its Library entry. After removal it no longer appears in list_documents. This operation does not save the document or delete its source file or backend record. Unsaved changes are discarded. An unknown document ID returns an error.

This tool is compiled and registered only in WebAssembly builds. Native tool catalogs do not include it.

await tritium.callTool("remove_document", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123" }
  },
  displayText: "Queued removing document from session: \"contract.docx\""
}
*/

save_document

callTool(name: "save_document", args: { documentId: DocumentId }): Promise<ToolResult>

Requests that an open document be saved by its ID. Call list_documents first to obtain the ID. In the WebAssembly build, saving a DOCX document with unsaved changes passes a Document containing the complete file and its ID to the callback registered with setSaveHandler.

await tritium.callTool("save_document", {
  documentId: "backend-contract-123",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123" }
  },
  displayText: "Queued saving document: \"contract.docx\""
}
*/

compare_documents

callTool(name: "compare_documents", args: { originalId: DocumentId; modifiedId: DocumentId }): Promise<ToolResult>

Requests a redline comparison between two open documents. Successful result data confirms the accepted originalId and modifiedId.

await tritium.callTool("compare_documents", {
  originalId: "backend-contract-123",
  modifiedId: "backend-revision",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", originalId: "backend-contract-123", modifiedId: "backend-revision" }
  },
  displayText: "Queued redline comparison: \"contract.docx\" (original) vs \"revised-contract.docx\" (modified)."
}
*/

replace_segment

callTool(name: "replace_segment", args: { documentId: DocumentId; segmentId: number; newText: string }): Promise<ToolResult>

Replaces the text of one segment. Read the document first to obtain its current segment IDs.

await tritium.callTool("replace_segment", {
  documentId: "backend-contract-123",
  segmentId: 12,
  newText: "The replacement paragraph text.",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123", segmentId: 12, segmentIdsStale: true }
  },
  displayText: "Queued replacement of segment 12."
}
*/

insert_segment

callTool(name: "insert_segment", args: { documentId: DocumentId; beforeId: number; text: string }): Promise<ToolResult>

Inserts one segment before beforeId. Use the document's segment count as beforeId to append at the end.

await tritium.callTool("insert_segment", {
  documentId: "backend-contract-123",
  beforeId: 12,
  text: "A newly inserted paragraph.",
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123", beforeId: 12, segmentIdsStale: true }
  },
  displayText: "Queued segment insertion before position 12."
}
*/

delete_segment

callTool(name: "delete_segment", args: { documentId: DocumentId; segmentId: number }): Promise<ToolResult>

Deletes one segment using its current segment ID.

await tritium.callTool("delete_segment", {
  documentId: "backend-contract-123",
  segmentId: 12,
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123", segmentId: 12, segmentIdsStale: true }
  },
  displayText: "Queued deletion of segment 12."
}
*/

batch_edit

callTool(name: "batch_edit", args: { documentId: DocumentId; edits: Array<{ segmentId: number; newText: string }> }): Promise<ToolResult>

Replaces several segments in one operation. Passing an empty edits array succeeds as a no-op.

await tritium.callTool("batch_edit", {
  documentId: "backend-contract-123",
  edits: [
    { segmentId: 12, newText: "First replacement." },
    { segmentId: 15, newText: "Second replacement." },
  ],
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "backend-contract-123", editCount: 2, segmentIdsStale: true }
  },
  displayText: "Queued 2 edit(s) for document backend-contract-123."
}
*/

create_document

callTool(name: "create_document", args: { filename: string; segments: string[] }): Promise<ToolResult>

Creates a DOCX document. Each string in segments becomes one document segment, and at least one segment is required.

await tritium.callTool("create_document", {
  filename: "draft.docx",
  segments: ["Draft agreement", "1. Definitions", "2. Term"],
})
/*
{
  output: {
    ok: true,
    data: { status: "accepted", documentId: "67e55044-10b1-426f-9247-bb680e5fe0c8", filename: "draft.docx", segmentCount: 3 }
  },
  displayText: "Queued creation of \"draft.docx\" with 3 segment(s)."
}
*/

draft_section

callTool(name: "draft_section", args: { documentId: DocumentId; beforeId: number; segments: string[] }): Promise<ToolResult>

Concatenates the strings in segments in array order and inserts the resulting text together before beforeId. No spaces, newlines, or paragraph boundaries are added between strings. Include any required separators in the strings themselves.

segments must contain at least one string. beforeId is a zero-based segment ID from the current document; use the current segment count to append at the end. The returned segmentCount is the number of input strings, not the number of document segments created. Read the document again after insertion to obtain its updated segments and IDs.

await tritium.callTool("draft_section", {
  documentId: "backend-contract-123",
  beforeId: 12,
  segments: ["3. Confidentiality\n", "Each party must keep information confidential.\n"],
})
/*
{
  output: {
    ok: true,
    data: {
      status: "accepted",
      documentId: "backend-contract-123",
      beforeId: 12,
      segmentCount: 2,
      segmentIdsStale: true
    }
  },
  displayText: "Queued section from 2 input string(s) at position 12 in document backend-contract-123."
}
*/

Segment IDs are positional identifiers for the document state returned by read_document or read_segments. After an edit succeeds with segmentIdsStale: true, read the document again before making another segment-based call.

TypeScript Declarations

TypeScript declarations are available at https://tritium.legal/static/init.d.ts

Download the declaration file into your project, for example:

curl -fsSL https://tritium.legal/static/init.d.ts -o src/types/init.d.ts

Then, add it to your tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "https://tritium.legal/static/init.js": [
        "./src/types/init.d.ts"
      ]
    }
  }
}

Host-controlled editability

hostManagesCheckout replaces readonlyMode (removed; no alias). When enabled, checkout/check-in actions only notify the host; they do not change permission. Without host control, these actions immediately change local permission. PDFs and Markdown remain read-only regardless of permission.

Documents passed to start, addDocument, or openDocument accept an optional isCheckedOut Boolean indicating whether this application owns the checkout. In host-controlled mode, omitted state defaults to false. Loading remains asynchronous; supply initial checkout state with the document.

interface DocumentCheckoutStatus {
  documentId: DocumentId;
  isCheckedOut: boolean;
}

setDocumentCheckoutStatus(update: DocumentCheckoutStatus): void;

Checkout/check-in events identify the document through documentIds[0] and include a fresh UUID requestId. These are stateless notifications: Tritium does not retain, validate, or correlate request IDs, and repeated requests are allowed.

tritium.setDocumentCheckoutStatus({
  documentId: event.documentIds[0],
  isCheckedOut: true,
});

The setter changes checkout state immediately, without a queue or observation, and emits no request event. It throws if the document is missing or the application is unavailable or currently borrowed (for example, during a synchronous non-editing workspace callback). The host is responsible for authorizing updates and handling out-of-order backend replies.

Check-in requests leave permission unchanged until the host changes it. The host must coordinate the final save; this API does not await uploads, freeze edits, or implement a DMS transaction.