> For the complete documentation index, see [llms.txt](https://adaptix-framework.gitbook.io/adaptix-framework/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adaptix-framework.gitbook.io/adaptix-framework/development/teamserver-interface/teamserver-interface-api-ts-api.md).

# TS API

## ID generators

Six wrappers around the built-in `idgen.Generator`. They return the next free value for the corresponding entity; counters are restored from the DB on server start (`MAX(id) + 1`). Plugins that create an entity on the server side must take the ID via these helpers so it does not collide with existing DB records.

```go
TsAgentGenID()  int64   // entity "agent",  table Agents.Id
TsTaskGenID()   int64   // entity "task",   table Tasks.TaskId
TsCredGenID()   int64   // entity "cred",   table Credentials.CredId
TsScreenGenID() int64   // entity "screen", table Screenshots.ScreenId
TsTargetGenID() int64   // entity "target", table Targets.TargetId
TsFileGenID()   int64   // entity "file",   table Downloads.FileId
```

***

## Agent Functions

### TsAgentIsExists

Checks if an agent exists by ID.

```go
TsAgentIsExists(agentId int64) bool
```

**Returns:** `bool` — `true` if agent exists

***

### TsAgentGetById

Reads one in-memory session. The second result is false when the id is unknown or the agent was removed.

```go
TsAgentGetById(agentId int64) (AgentData, bool)
```

***

### TsAgentIdByUID

Linear search for an agent by `UID` (optional identifier filled by the listener/agent plugin, not overlapping with `agentId`).&#x20;

```go
TsAgentIdByUID(uid []byte) (int64, bool)
```

**Returns:** the found `agentId` and `true`; `(0, false)` if no agent has this UID or `uid` is empty.

***

### TsAgentList

JSON array of every in-memory session (`AgentData` as stored, including the session key). An empty server marshals as `null`, not `[]`.

```go
TsAgentList() (string, error)
```

***

### TsAgentCatalog

JSON array of registered agent types, sorted by name. Each item is `{name, listeners, axs}`. `axs` is the agent AxScript and is omitted when empty.

```go
TsAgentCatalog() (string, error)
```

***

### TsAgentCreate

Creates a new agent on first connection.

```go
TsAgentCreate(agentCrc string, agentUid []byte, beat []byte, listenerName string, ExternalIP string, Async bool) (adaptix.AgentData, error)
```

<table><thead><tr><th width="144">Parameter</th><th width="130">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentCrc</code></td><td><code>string</code></td><td>CRC/watermark of the agent type</td></tr><tr><td><code>agentUid</code></td><td><code>[]byte</code></td><td>Unique agent UID (agentId is generated server-side)</td></tr><tr><td><code>beat</code></td><td><code>[]byte</code></td><td>Initial data from agent (heartbeat)</td></tr><tr><td><code>listenerName</code></td><td><code>string</code></td><td>Listener name</td></tr><tr><td><code>ExternalIP</code></td><td><code>string</code></td><td>Agent's external IP</td></tr><tr><td><code>Async</code></td><td><code>bool</code></td><td>Asynchronous mode</td></tr></tbody></table>

**Returns:** `adaptix.AgentData`, `error`

**Events:**

* `agent.new` (Pre/Post hooks)

***

### TsAgentProcessData

Processes data received from an agent.

```go
TsAgentProcessData(agentId int64, bodyData []byte) error
```

<table><thead><tr><th width="152.38330078125">Parameter</th><th width="140.75">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>bodyData</code></td><td><code>[]byte</code></td><td>Data from agent</td></tr></tbody></table>

**Events:** `agent.activate` (post only), and only when `Mark` was `"Inactive"`. The mark is cleared, the row is saved, then the post hook runs.

***

### TsAgentUpdateData

Updates agent data (sleep, jitter, killdate, workingtime).

```go
TsAgentUpdateData(newAgentData adaptix.AgentData) error
```

***

### TsAgentUpdateDataPartial

Partial update of agent data. `updateData` is any struct/map that JSON-marshals to an object with keys from the table below; only present fields are applied.

```go
TsAgentUpdateDataPartial(agentId int64, updateData interface{}) error
```

**Supported fields** (JSON key → `AgentData` field):

<table data-search="false"><thead><tr><th width="162.41668701171875">JSON key</th><th width="139.3333740234375">AgentData field</th><th>Type</th></tr></thead><tbody><tr><td><code>internal_ip</code></td><td><code>InternalIP</code></td><td>string</td></tr><tr><td><code>external_ip</code></td><td><code>ExternalIP</code></td><td>string</td></tr><tr><td><code>gmt_offset</code></td><td><code>GmtOffset</code></td><td>int</td></tr><tr><td><code>acp</code></td><td><code>ACP</code></td><td>int</td></tr><tr><td><code>oemcp</code></td><td><code>OemCP</code></td><td>int</td></tr><tr><td><code>pid</code></td><td><code>Pid</code></td><td>string</td></tr><tr><td><code>tid</code></td><td><code>Tid</code></td><td>string</td></tr><tr><td><code>arch</code></td><td><code>Arch</code></td><td>string</td></tr><tr><td><code>elevated</code></td><td><code>Elevated</code></td><td>bool</td></tr><tr><td><code>process</code></td><td><code>Process</code></td><td>string</td></tr><tr><td><code>os</code></td><td><code>Os</code></td><td>int</td></tr><tr><td><code>os_desc</code></td><td><code>OsDesc</code></td><td>string</td></tr><tr><td><code>domain</code></td><td><code>Domain</code></td><td>string</td></tr><tr><td><code>computer</code></td><td><code>Computer</code></td><td>string</td></tr><tr><td><code>username</code></td><td><code>Username</code></td><td>string</td></tr><tr><td><code>impersonated</code></td><td><code>Impersonated</code></td><td>string</td></tr><tr><td><code>tags</code></td><td><code>Tags</code></td><td>string</td></tr><tr><td><code>mark</code></td><td><code>Mark</code></td><td>string</td></tr><tr><td><code>color</code></td><td><code>Color</code></td><td>string ("bg-fg" hex, RGB-validated)</td></tr><tr><td><code>listener</code></td><td><code>Listener</code></td><td>string</td></tr><tr><td><code>a_session_key</code></td><td><code>SessionKey</code></td><td>string (stored as <code>[]byte</code>; not emitted in <code>TYPE_AGENT_UPDATE</code>)</td></tr><tr><td><code>custom_data</code></td><td><code>CustomData</code></td><td>string (stored as <code>[]byte</code>; not emitted in <code>TYPE_AGENT_UPDATE</code>)</td></tr><tr><td><code>sleep</code></td><td><code>Sleep</code></td><td>uint</td></tr><tr><td><code>jitter</code></td><td><code>Jitter</code></td><td>uint</td></tr><tr><td><code>working_time</code></td><td><code>WorkingTime</code></td><td>int (packed: <code>(startH&#x3C;&#x3C;24)|(startM&#x3C;&#x3C;16)|(endH&#x3C;&#x3C;8)|endM</code>)</td></tr><tr><td><code>kill_date</code></td><td><code>KillDate</code></td><td>int (unix seconds)</td></tr></tbody></table>

**Notes:**

* Changing `Mark` is silently ignored if the current mark is already `"Terminated"` (terminal state).
* Setting `Mark = "Disconnect"` also updates `LastTick` to the current time.
* `Color` accepts `"<bg>-<fg>"` hex (`"#1e3050-#ffffff"`); each half is checked as a valid RGB, and an empty half keeps the previous value.
* Empty `updateData` (no recognized fields) is a no-op: the function returns `nil`, nothing is written to the DB, no sync packet is sent.
* Fields not listed are ignored. `Crc`, `Id`, `UID`, `Name`, `CreateTime`, `Async`, and `TargetId` cannot be modified through this API. `LastTick` changes only as a side effect of `Mark = "Disconnect"`, or through `TsAgentSetTick`. `Active` is a runtime flag on the `Agent` struct, not part of `AgentData`.

**Typical call from a plugin (for example inside `OnDispatch` for `sleep`):**

```go
ts.TsAgentUpdateDataPartial(agentId, struct {
    Sleep  *uint `json:"sleep"`
    Jitter *uint `json:"jitter"`
}{Sleep: &newSleep, Jitter: &newJitter})
```

***

### TsAgentTerminate

Terminates an agent.

```go
TsAgentTerminate(agentId int64, terminateTaskId int64) error
```

**Actions performed:**

1. Cancels all active downloads
2. Stops all tunnels
3. Closes terminals
4. Clears task queues
5. Removes pivot links

**Events:**

* `agent.terminate` (Pre/Post hooks)

***

### TsAgentSetTick

Updates the agent's last response time.

```go
TsAgentSetTick(agentId int64, listenerName string) error
```

***

### TsAgentConsoleOutput

Outputs a message to the agent console.

```go
TsAgentConsoleOutput(agentId int64, client string, messageType int, message string, clearText string, store bool)
```

<table><thead><tr><th width="125.14996337890625">Parameter</th><th width="108.166748046875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>client</code></td><td><code>string</code></td><td>Initiator operator name (used for filtering in non-team mode)</td></tr><tr><td><code>messageType</code></td><td><code>int</code></td><td>Message type (5=INFO, 6=ERROR, 7=SUCCESS)</td></tr><tr><td><code>message</code></td><td><code>string</code></td><td>Message header</td></tr><tr><td><code>clearText</code></td><td><code>string</code></td><td>Message text</td></tr><tr><td><code>store</code></td><td><code>bool</code></td><td>Save to the DB</td></tr></tbody></table>

***

### TsAgentBuildExecute

Runs an external command during agent build, redirecting output to the build WebSocket channel.

```go
TsAgentBuildExecute(builderId string, workingDir string, env []string, program string, args ...string) error
```

<table><thead><tr><th width="141">Parameter</th><th width="145">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>builderId</code></td><td><code>string</code></td><td>Builder ID (empty string for synchronous execution)</td></tr><tr><td><code>workingDir</code></td><td><code>string</code></td><td>Working directory for the command</td></tr><tr><td><code>program</code></td><td><code>string</code></td><td>Executable</td></tr><tr><td><code>args</code></td><td><code>...string</code></td><td>Command-line arguments</td></tr></tbody></table>

**Note:** If `builderId` is empty, the command runs synchronously without output to the WebSocket. Otherwise stdout/stderr are redirected to the build channel.

***

### TsAgentBuildLog

Sends a log message to the agent's WebSocket build channel.

```go
TsAgentBuildLog(builderId string, status int, message string) error
```

<table><thead><tr><th width="124">Parameter</th><th width="115">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>builderId</code></td><td><code>string</code></td><td>Builder ID</td></tr><tr><td><code>status</code></td><td><code>int</code></td><td>Status: BUILD_LOG_NONE=0, INFO=1, ERROR=2, SUCCESS=3</td></tr><tr><td><code>message</code></td><td><code>string</code></td><td>Message text</td></tr></tbody></table>

***

### TsAgentEncryptData / TsAgentDecryptData

Session-key encrypt and decrypt. Both return an error if the agent has been removed.

```go
TsAgentEncryptData(agentId int64, data []byte) ([]byte, error)
TsAgentDecryptData(agentId int64, data []byte) ([]byte, error)
```

***

### TsSetAgentDeliveryFunc / TsRemoveAgentDeliveryFunc / TsGetAgentDeliveryFunc

Per-agent push callback. `TsTaskCreate` calls it in a goroutine so a listener can deliver a task without waiting for the next poll. `DeliveryFunc` is `func(agentId int64, taskData TaskData) error`.

```go
TsSetAgentDeliveryFunc(AgentId int64, fn DeliveryFunc)
TsRemoveAgentDeliveryFunc(AgentId int64)
TsGetAgentDeliveryFunc(AgentId int64) DeliveryFunc
```

***

### TsAgentGetHosted\* Functions

Retrieve tasks for sending to an agent. All functions pack tasks while respecting a size limit. They do **not** write to the agent console — dequeue is not a send. The task queue (`HostedQueue`) is a `safe.PriorityQueue` with FIFO inside each priority level; `Pop()` returns the highest-priority item first.

`StatTasks` is counted **after** `OnDispatch`. Each known task type has its own `{Count, Bytes}` (`Task`, `Job`, `Browser`, `Tunnel`, `Proxy`, `Local`, `Other`). Helpers: `stats.Commands()` (TASK+JOB), `stats.Total()`, `stats.Of(taskType)`, `stat.SizeString()`.

#### **TsAgentGetHostedAll**

Gets all available tasks: regular tasks, tunnel tasks, tunnel data, and pivot tasks.

```go
TsAgentGetHostedAll(agentId int64, maxDataSize int) ([]byte, StatTasks, error)
```

<table><thead><tr><th width="144">Parameter</th><th width="107">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>maxDataSize</code></td><td><code>int</code></td><td>Maximum data size (bytes)</td></tr></tbody></table>

**Returns:** Packed bytes, operator-visible note, error.

A nested `TsAgentGetHostedAll` for a child should not write a console line for that child.

#### **TsAgentGetHostedTasks**

Gets hosted tasks without pivot. `maxCount <= 0` means unlimited.

```go
TsAgentGetHostedTasks(agentId int64, maxCount int, maxDataSize int) ([]byte, StatTasks, error)
```

<table><thead><tr><th width="146.6500244140625">Parameter</th><th width="103.61669921875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>maxCount</code></td><td><code>int</code></td><td>Max tasks, or <code>&#x3C;= 0</code> for unlimited</td></tr><tr><td><code>maxDataSize</code></td><td><code>int</code></td><td>Max data size in bytes</td></tr></tbody></table>

The teamserver does **not** write a console line. After a successful send the listener formats its own text from `StatTasks` and the bytes it actually wrote (`FormatByteSize(len(wire))`). `stats.Packed` is size after `PackTasks`, before listener wrapping.

Framed transports: the listener prints with `adaptix.NoteFrameSent` / `NoteFrameRecv` after `TsFrameGetChunk` or `TsFrameGetChunkSticky`, or after a completed `TsFramePut`, `TsFramePutDecoded`, or `TsFramePutStream`. `TsFrameTakeStatTasks` and `TsFrameTakeStatRecv` fire once per blob.

#### TsAgentBuildEmptyTasks

Packs an empty task blob with the agent session key.&#x20;

```go
TsAgentBuildEmptyTasks(agentId int64) ([]byte, error)
```

***

## Task Functions

### TsTaskRunningExists

Checks if a task is running.

```go
TsTaskRunningExists(agentId int64, taskId int64) bool
```

***

### TsTaskCreate

Creates a new task.

```go
TsTaskCreate(agentId int64, cmdline string, client string, taskData adaptix.TaskData)
```

A task created with `taskData.Completed = true` (a command that finished on the server) does not enter the `HostedQueue`. It is finalized immediately: `task.complete` post hook and a sync broadcast.

**Events:**

* `task.create` (Pre/Post hooks)

***

### TsTaskUpdate

Updates the task with execution results.

```go
TsTaskUpdate(agentId int64, updateData adaptix.TaskData)
```

**Events:**

* `task.complete` (post only) when this update finalizes the task (`Completed` on a synced task or job). An update that only parks the task for a client hook does not emit it. Cancel goes through `TsTaskCancel` and does not emit `task.complete`.
* `task.update_job` (post only) on every update of a `TASK_TYPE_JOB` task, before that job is finalized. `task.start` is declared and is not emitted.

***

### TsTaskCancel

Cancels a task — both one still queued and one already dispatched to the agent.

```go
TsTaskCancel(agentId int64, taskId int64) error
```

<table><thead><tr><th width="142">Parameter</th><th width="141">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>taskId</code></td><td><code>int64</code></td><td>Task ID</td></tr></tbody></table>

* Task still in `agent.HostedQueue` (not yet taken by `TsTaskGetAvailableAll` or `TsTaskGetAvailableTasks`) — removed from the queue and finalized as canceled: `Completed=true`, `MessageType=MESSAGE_ERROR`, `Message="Task canceled"`, `FinishDate=now`; `OnComplete` runs. Sync tasks are updated in the DB and broadcast as a task update; others are removed from the client.
* Task already dispatched (in `agent.RunningTasks`) is cancelable too: removed from `RunningTasks`, `TsFrameResetDownstream` drops the rest of that downstream session, server AxScript hooks for that task are unregistered, then the same finalization.

***

## Frame Manager Functions

Frame Manager is shared infrastructure for protocol-independent fragmentation/reassembly of large messages between server and agent. It extracts the duplicated logic from listener plugins. It supports three upstream-assembly modes, auto-detected from the first call to the corresponding method:

* **Byte-offset mode** (`TsFramePut` with `totalSize > 0`, `chunkCount == 0`): the caller knows the total size in bytes and addresses by byte offset.
* **Chunk-index mode** (`TsFramePut` with `chunkCount > 0`): the caller knows the chunk count and addresses by chunk index.
* **Stream mode** (`TsFramePutStream`): the total size is unknown up front; chunks arrive with an incrementing `seqNum`, and the `isLast` flag signals completion.

Encoding/decoding (compression, frame headers) is performed by the plugin. The plugin passes an `encode` callback to `TsFrameGetChunk` and decodes the data returned by `TsFramePut`/`TsFramePutStream` itself.

***

### TsFrameHasPending

Returns `true` if the agent has outgoing data in its downstream session, tasks in `HostedQueue`, pivot tasks for child agents, or orphaned TASK/BROWSER tasks in `RunningTasks` (see the requeue above).

```go
TsFrameHasPending(sessionId int64) bool
```

***

### TsFramePut

Accepts an upstream fragment from the listener and places it into the reassembly buffer. When assembly is complete, returns the assembled raw block (the plugin decodes/decompresses it and calls `TsAgentProcessData`).

```go
TsFramePut(sessionId int64, index uint32, data []byte, totalSize uint32, chunkCount uint16) (complete bool, nextExpected uint32, received uint32, sackBitmap uint32, assembled []byte)
```

<table><thead><tr><th width="120.13330078125">Parameter</th><th width="95.8333740234375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>sessionId</code></td><td><code>string</code></td><td>Session ID (usually <code>agentId</code>)</td></tr><tr><td><code>index</code></td><td><code>uint32</code></td><td>Byte offset or chunk index (depends on the mode)</td></tr><tr><td><code>data</code></td><td><code>[]byte</code></td><td>Fragment contents</td></tr><tr><td><code>totalSize</code></td><td><code>uint32</code></td><td>Full message size (byte-offset mode); <code>0</code> for chunk-index mode</td></tr><tr><td><code>chunkCount</code></td><td><code>uint16</code></td><td>Number of chunks (chunk-index mode); <code>0</code> for byte-offset mode</td></tr></tbody></table>

**Returns:** `complete` — fully assembled; `nextExpected` — next expected offset/index; `received` — how much has been received; `sackBitmap` — SACK bitmap of acknowledged chunks; `assembled` — the fully assembled blob (only when `complete=true`).

***

### TsFramePutStream

Accepts an upstream chunk in **stream mode**. Chunks arrive with an increasing `seqNum`; out-of-order arrivals are buffered. When a chunk with `isLast = true` arrives and all preceding seqNums have been collected — the function returns the assembled raw block.

```go
TsFramePutStream(sessionId int64, seqNum uint32, data []byte, isLast bool) (complete bool, assembled []byte)
```

<table><thead><tr><th width="135.18328857421875">Parameter</th><th width="117.5">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>sessionId</code></td><td><code>int64</code></td><td>Session ID (usually <code>agentId</code>)</td></tr><tr><td><code>seqNum</code></td><td><code>uint32</code></td><td>Chunk sequence number (starting at 0)</td></tr><tr><td><code>data</code></td><td><code>[]byte</code></td><td>Chunk contents</td></tr><tr><td><code>isLast</code></td><td><code>bool</code></td><td><code>true</code> — this chunk is the last</td></tr></tbody></table>

**Returns:** `complete` — the stream is fully assembled; `assembled` — the assembled data (only when `complete=true`). Duplicate `seqNum`s are ignored; a repeated `TsFramePutStream` for an already-finished session returns `(true, nil)`.

***

### TsFramePutDecoded

A `TsFramePut` variant (byte-offset mode): after the reassembly completes, the `decode` callback is applied to the assembled block. If decoding returns an error — `assembled = nil` (the listener can drop the session instead of dispatching garbage).

```go
TsFramePutDecoded(sessionId int64, index uint32, data []byte, totalSize uint32, chunkCount uint16, decode func(assembled []byte) ([]byte, error)) (bool, uint32, uint32, uint32, []byte)
```

**Returns:** the same values as `TsFramePut` (`complete`, `nextExpected`, `received`, `sackBitmap`, `assembled`), but `assembled` is the result of `decode(assembled)`.

***

### TsFrameGetChunk

Returns the next downstream chunk for an agent. Creates a downstream session on the first call (including pulling tasks from `HostedQueue`, packing and encrypting by the agent, applying `encode`).

```go
TsFrameGetChunk(sessionId int64, reqOffset uint32, maxChunkSize int, encode func([]byte) []byte) (total uint32, offset uint32, data []byte, taskNonce uint32, isEmpty bool)
```

<table><thead><tr><th width="138.04998779296875">Parameter</th><th width="202.2166748046875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>sessionId</code></td><td><code>string</code></td><td>Session ID</td></tr><tr><td><code>reqOffset</code></td><td><code>uint32</code></td><td>Requested offset</td></tr><tr><td><code>maxChunkSize</code></td><td><code>int</code></td><td>Max bytes in a chunk (transport-dependent, e.g., 160 for DNS UDP)</td></tr><tr><td><code>encode</code></td><td><code>func([]byte) []byte</code></td><td>Optional callback to prepare the full payload (compression + frame); <code>nil</code> — no transformation</td></tr></tbody></table>

**Returns:** `total` — total payload size, `offset` — actual chunk offset, `data` — chunk contents, `taskNonce` — session nonce (for subsequent ACK), `isEmpty` — no data to send.

***

### TsFrameGetChunkSticky

The downstream session is marked sticky: when `maxAttempts` is exceeded it is not evicted — the attempt counter resets instead, and the session is released only by the idle timeout or via `TsFrameAckDelivery`. The attempt counter is incremented only on repeated requests for the same offset — requesting a new offset resets it.

```go
TsFrameGetChunkSticky(sessionId int64, reqOffset uint32, maxChunkSize int, encode func([]byte) []byte) (total uint32, offset uint32, data []byte, taskNonce uint32, isEmpty bool)
```

***

### TsFrameAckDelivery

Acknowledges to the agent that the entire downstream message has been delivered. Releases the downstream session.

```go
TsFrameAckDelivery(sessionId int64, ackOffset uint32, ackNonce uint32)
```

***

### TsFrameTakeStatTasks / TsFrameTakeStatRecv

Atomically take the statistics accumulated by the Frame Manager for a session. Framed transports print "N bytes sent" after `TsFrameGetChunk` or `TsFrameGetChunkSticky`, or after a completed `TsFramePut`, `TsFramePutDecoded`, or `TsFramePutStream`.

```go
TsFrameTakeStatTasks(sessionId int64) (StatTasks, int, bool)
TsFrameTakeStatRecv(sessionId int64) (size int, requests int, ok bool)
```

***

### TsFrameResetUpstream / TsFrameResetDownstream

Reset an unfinished upstream or downstream session (e.g., when desync is detected or an agent is explicitly reloaded).

```go
TsFrameResetUpstream(sessionId int64)
TsFrameResetDownstream(sessionId int64)
```

Used on task/upload cancellation: resetting the downstream session prevents the agent from receiving the canceled task's tail on its next poll.

***

## Client GUI Functions

Functions for synchronizing data with GUI clients (File Browser, Process Manager). These functions send results only to the client that initiated the request.

### TsClientGuiDisksWindows

Sends the list of Windows drives to the client.

```go
TsClientGuiDisksWindows(taskData adaptix.TaskData, drives []adaptix.ListingDrivesDataWin)
```

<table><thead><tr><th width="139">Parameter</th><th width="303">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data</td></tr><tr><td><code>drives</code></td><td><code>[]adaptix.ListingDrivesDataWin</code></td><td>Drive list</td></tr></tbody></table>

***

### TsClientGuiFilesWindows

Sends the list of Windows files to the client.

```go
TsClientGuiFilesWindows(taskData adaptix.TaskData, path string, files []adaptix.ListingFileDataWin)
```

<table><thead><tr><th width="135">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data</td></tr><tr><td><code>path</code></td><td><code>string</code></td><td>Directory path</td></tr><tr><td><code>files</code></td><td><code>[]adaptix.ListingFileDataWin</code></td><td>File list</td></tr></tbody></table>

***

### TsClientGuiFilesUnix

Sends the list of Unix/Linux files to the client.

```go
TsClientGuiFilesUnix(taskData adaptix.TaskData, path string, files []adaptix.ListingFileDataUnix)
```

<table><thead><tr><th width="141">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data</td></tr><tr><td><code>path</code></td><td><code>string</code></td><td>Directory path</td></tr><tr><td><code>files</code></td><td><code>[]adaptix.ListingFileDataUnix</code></td><td>File list</td></tr></tbody></table>

***

### TsClientGuiFilesStatus

Sends the file operation status (delete, rename, etc.) to the client.

```go
TsClientGuiFilesStatus(taskData adaptix.TaskData)
```

<table><thead><tr><th width="128">Parameter</th><th width="187">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data with MessageType and Message for status</td></tr></tbody></table>

***

### TsClientGuiProcessWindows

Sends the list of Windows processes to the client.

```go
TsClientGuiProcessWindows(taskData adaptix.TaskData, process []adaptix.ListingProcessDataWin)
```

<table><thead><tr><th width="137">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data</td></tr><tr><td><code>process</code></td><td><code>[]adaptix.ListingProcessDataWin</code></td><td>Process list</td></tr></tbody></table>

***

### TsClientGuiProcessUnix

Sends the list of Unix/Linux processes to the client.

```go
TsClientGuiProcessUnix(taskData adaptix.TaskData, process []adaptix.ListingProcessDataUnix)
```

<table><thead><tr><th width="141">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>taskData</code></td><td><code>adaptix.TaskData</code></td><td>Task data</td></tr><tr><td><code>process</code></td><td><code>[]adaptix.ListingProcessDataUnix</code></td><td>Process list</td></tr></tbody></table>

***

## Credentials Functions

### TsCredentilsAdd

Adds credentials.

```go
TsCredentilsAdd(creds []map[string]interface{}) error
```

**Credential structure:**

```go
map[string]interface{}{
    "username": "admin",
    "password": "hash_or_password",
    "realm":    "DOMAIN",
    "type":     "NTLM",
    "tag":      "DC01",
    "storage":  "LSASS",
    "agent_id": "abc123",
    "host":     "192.168.1.1",
}
```

**Events:**

* `credentials.add` (Pre/Post hooks)

***

### TsCredentilsEdit

```go
TsCredentilsEdit(credId int64, username string, password string, realm string, credType string, tag string, storage string, host string) error
```

**Events:**

* `credentials.edit` (Pre/Post hooks)

***

### TsCredentialsSetTag

```go
TsCredentialsSetTag(credsId []int64, tag string) error
```

***

### TsCredentilsDelete

```go
TsCredentilsDelete(credsId []int64) error
```

**Events:**

* `credentials.remove` (Pre/Post hooks)

***

## Download/Upload Functions

### TsDownloadAdd

Initializes a file download. `fileId` comes from `TsFileGenID`.

```go
TsDownloadAdd(agentId int64, fileId int64, fileName string, fileSize int64) error
```

**Events:**

* `download.start` (Pre/Post hooks)

***

### TsDownloadUpdate

Updates download state.

```go
TsDownloadUpdate(fileId int64, state int, data []byte) error
```

<table><thead><tr><th width="110">State</th><th width="142">Value</th><th>Description</th></tr></thead><tbody><tr><td>1</td><td>RUNNING</td><td>Download in progress</td></tr><tr><td>2</td><td>STOPPED</td><td>Paused</td></tr><tr><td>3</td><td>FINISHED</td><td>Completed</td></tr><tr><td>4</td><td>CANCELED</td><td>Cancelled</td></tr></tbody></table>

***

### TsDownloadClose

Finishes a download.

```go
TsDownloadClose(fileId int64, reason int) error
```

**Events:**

* `download.finish` (Pre/Post hooks)

***

### TsDownloadSave

Saves a file directly (from memory).

```go
TsDownloadSave(agentId int64, fileId int64, filename string, content []byte) error
```

***

### TsDownloadGet

One transfer record. The in-memory map is checked first; otherwise the DB row is returned. Unknown id is `"File not found: <id>"`. No event.

```go
TsDownloadGet(fileId int64) (TransferData, error)
```

***

### TsDownloadGetFilepath

Returns the local path to the downloaded file.

```go
TsDownloadGetFilepath(fileId int64) (string, error)
```

**Returns:** Full path to the file on the server.

**Note:** Works only for completed downloads (state=FINISHED).

***

### TsDownloadDelete

Deletes downloaded files.

```go
TsDownloadDelete(fileId []int64) error
```

**Events:**

* `download.remove` (Pre/Post hooks)

***

### TsDownloadSetTag

Update of a tag on a group of downloads.

```go
TsDownloadSetTag(fileIds []int64, tag string) error
```

<table><thead><tr><th width="124.433349609375">Parameter</th><th width="117.4833984375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>fileIds</code></td><td><code>[]int64</code></td><td>Array of download FileIds</td></tr><tr><td><code>tag</code></td><td><code>string</code></td><td>New tag; empty string clears it</td></tr></tbody></table>

***

### TsUploadAdd / TsUploadAddContent

Initialize an upload of a file to an agent. `TsUploadAdd` reads the file from disk (`localPath`). `TsUploadAddContent` takes bytes in memory and optional memory-artifact fields. `fileId` comes from `TsFileGenID`.

```go
TsUploadAdd(agentId int64, fileId int64, localPath string, remotePath string) error
TsUploadAddContent(agentId int64, fileId int64, remotePath string, content []byte, canceled bool, kind int, artname string, arttype string) error
```

<table><thead><tr><th width="111.5333251953125">Parameter</th><th width="100.11669921875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>canceled</code></td><td><code>bool</code></td><td><code>false</code> → <code>TsUploadClose(CANCELED)</code> rejects with an error; the UI Cancel button is disabled. For artifacts without an agent-side break command. Regular file uploads — <code>true</code>.</td></tr><tr><td><code>kind</code></td><td><code>int</code></td><td><code>TRANSFER_KIND_FILE = 0</code> (regular file) or <code>TRANSFER_KIND_MEMORY = 1</code> (BOF / shellcode / .NET)</td></tr><tr><td><code>artname</code></td><td><code>string</code></td><td>Operator-friendly label for <code>Kind=MEMORY</code> (BOF / shellcode name). For FILE — empty string.</td></tr><tr><td><code>arttype</code></td><td><code>string</code></td><td>Category for <code>Kind=MEMORY</code> (<code>"bof"</code> / <code>"shellcode"</code> / <code>"dotnet"</code>). For FILE — empty string.</td></tr></tbody></table>

**Events:** `upload.start` (Pre/Post hooks).

***

### TsUploadGetChunk

Returns the next chunk of the upload file. Used by the agent plugin when preparing a portion of data to send to the agent.

```go
TsUploadGetChunk(fileId int64, chunkSize int, needApprove bool) ([]byte, error)
```

<table><thead><tr><th width="136.61663818359375">Parameter</th><th width="92.13330078125">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>fileId</code></td><td><code>int64</code></td><td>Upload session ID</td></tr><tr><td><code>chunkSize</code></td><td><code>int</code></td><td>Desired chunk size (bytes)</td></tr><tr><td><code>needApprove</code></td><td><code>bool</code></td><td><code>true</code> — Progress is incremented only after <code>TsUploadApprove</code>; <code>false</code> — immediately</td></tr></tbody></table>

**Returns:** a slice of the read bytes; `nil` with no error means the file has already been fully sent.

***

### TsUploadApprove

Acknowledges delivery of the next chunk of upload data to the agent. Used when `needApprove = true`, where the agent explicitly confirms receipt of a chunk before Progress is incremented.

```go
TsUploadApprove(fileId int64, approvedBytes int) error
```

***

### TsUploadClose

Closes the upload session (`reason` — `TRANSFER_STATE_FINISHED` or `TRANSFER_STATE_CANCELED`).

```go
TsUploadClose(fileId int64, reason int) error
```

If `reason == TRANSFER_STATE_CANCELED` and the upload has `Cancellable == false` (memory artifact without an agent-side break) — returns `upload %d is not cancellable`. `TsAgentRemove` and `TsUploadDelete` still close that upload. After a successful close, state and progress are saved.

**Events:** `upload.finish` (Pre/Post hooks).

***

### TsUploadGet

Returns the current snapshot of an upload session. The in-memory map is checked first; otherwise the stored row is returned (finished or canceled). Same shape as `TsDownloadGet`.

```go
TsUploadGet(fileId int64) (adaptix.TransferData, error)
```

***

### TsUploadDelete

Cancel and remove uploads. Active records are closed as canceled even when `Cancellable` is false, then the ids are deleted. Clients receive a transfer-delete for each upload. Backs `POST /upload/delete`.

```go
TsUploadDelete(fileIds []int64) error
```

***

## Listener Functions

### TsListenerGet

Returns the data of a running listener.

```go
TsListenerGet(listenerName string) (adaptix.ListenerData, bool)
```

**Parameters:**

* `listenerName` — listener instance name.

**Returns:** the `ListenerData` and an existence flag (`false` — listener not found; an empty name returns `false` immediately).

***

### TsListenerGetProfile

Gets a profile for agent generation.

```go
TsListenerGetProfile(listenerName string) (string, []byte, error)
```

**Returns:** watermark, profile bytes, error

***

### TsListenerInteralHandler

Handles internal requests (pivot agents).

```go
TsListenerInteralHandler(watermark string, data []byte) (int64, error)
```

**Returns:** child agent id (`int64`) and an error.

***

### TsListenerList / TsListenerCatalog

Running listeners, and the listener types registered by extenders.

```go
TsListenerList() (string, error)
TsListenerCatalog() (string, error)
```

***

## Pivot Functions

### TsPivotCreate

Creates a pivot connection.

```go
TsPivotCreate(pivotId string, pAgentId int64, chAgentId int64, pivotName string, isRestore bool) error
```

**Events:**

* `pivot.create` (Pre/Post hooks)

***

### TsPivotDelete

```go
TsPivotDelete(pivotId string) error
```

**Events:**

* `pivot.remove` (Pre/Post hooks)

***

### TsGetPivotInfoByName / TsGetPivotInfoById

```go
TsGetPivotInfoByName(pivotName string) (string, int64, int64)  // pivotId, parentAgentId, childAgentId
TsGetPivotInfoById(pivotId string) (string, int64, int64)      // pivotName, parentAgentId, childAgentId
```

***

## Screenshot Functions

### TsScreenshotAdd

Adds a screenshot.

```go
TsScreenshotAdd(agentId int64, Note string, Content []byte) error
```

**Events:**

* `screenshot.add` (Pre/Post hooks)

***

### TsScreenshotNote

Updates the note for a screenshot.

```go
TsScreenshotNote(screenId int64, note string) error
```

***

### TsScreenshotDelete

Deletes a screenshot.

```go
TsScreenshotDelete(screenId int64) error
```

**Actions:**

1. Deletes the file from disk
2. Removes the record from the DB
3. Synchronizes with clients

**Events:**

* `screenshot.remove` (Pre/Post hooks)

***

## Target Functions

### TsTargetsAdd

Adds new targets (hosts). Duplicates are automatically ignored.

```go
TsTargetsAdd(targets []map[string]interface{}) error
```

**Target structure:**

```go
map[string]interface{}{
    "computer": "DC01",           // Computer name
    "domain":   "CORP.LOCAL",     // Domain
    "address":  "192.168.1.10",   // IP address
    "os":       1,                // 1=Windows, 2=Linux, 3=macOS
    "os_desk":  "Windows Server 2019",
    "tag":      "Domain Controller",
    "info":     "Additional information",
    "alive":    true,             // Is target alive
}
```

**Events:**

* `target.add` (Pre/Post hooks)

***

### TsTargetsEdit

Edits an existing target.

```go
TsTargetsEdit(targetId int64, computer string, domain string, address string, os int, osDesk string, tag string, info string, alive bool) error
```

<table data-search="false"><thead><tr><th width="168">Parameter</th><th width="155">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>targetId</code></td><td><code>int64</code></td><td>Target ID</td></tr><tr><td><code>computer</code></td><td><code>string</code></td><td>Computer name</td></tr><tr><td><code>domain</code></td><td><code>string</code></td><td>Domain</td></tr><tr><td><code>address</code></td><td><code>string</code></td><td>IP address</td></tr><tr><td><code>os</code></td><td><code>int</code></td><td>OS type (1/2/3)</td></tr><tr><td><code>osDesk</code></td><td><code>string</code></td><td>OS description</td></tr><tr><td><code>tag</code></td><td><code>string</code></td><td>Tag</td></tr><tr><td><code>info</code></td><td><code>string</code></td><td>Additional info</td></tr><tr><td><code>alive</code></td><td><code>bool</code></td><td>Is alive</td></tr></tbody></table>

**Events:**

* `target.edit` (Pre/Post hooks)

***

### TsTargetSetTag

Sets a tag for a group of targets.

```go
TsTargetSetTag(targetsId []int64, tag string) error
```

***

### TsTargetDelete

Deletes targets.

```go
TsTargetDelete(targetsId []int64) error
```

**Events:**

* `target.remove` (Pre/Post hooks)

***

## Tunnel Functions

### TsTunnelStart

Starts the created tunnel.

```go
TsTunnelStart(TunnelId int64) (int64, error)
```

**Returns:** TaskId for tracking

**Events:**

* `tunnel.start` (Pre/Post hooks)

***

### TsTunnelCreate\* Functions

Functions for creating tunnels of different types. Return TunnelId.

#### TsTunnelCreateSocks4

Creates a SOCKS4 proxy.

```go
TsTunnelCreateSocks4(AgentId int64, Info string, Lhost string, Lport int) (int64, error)
```

<table><thead><tr><th width="144">Parameter</th><th width="126">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>AgentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>Info</code></td><td><code>string</code></td><td>Tunnel description</td></tr><tr><td><code>Lhost</code></td><td><code>string</code></td><td>Bind address</td></tr><tr><td><code>Lport</code></td><td><code>int</code></td><td>Bind port</td></tr></tbody></table>

#### TsTunnelCreateSocks5

Creates a SOCKS5 proxy with optional authentication.

```go
TsTunnelCreateSocks5(AgentId int64, Info string, Lhost string, Lport int, UseAuth bool, Username string, Password string) (int64, error)
```

<table data-search="false"><thead><tr><th width="150">Parameter</th><th width="128">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>AgentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>Info</code></td><td><code>string</code></td><td>Tunnel description</td></tr><tr><td><code>Lhost</code></td><td><code>string</code></td><td>Bind address</td></tr><tr><td><code>Lport</code></td><td><code>int</code></td><td>Bind port</td></tr><tr><td><code>UseAuth</code></td><td><code>bool</code></td><td>Use authentication</td></tr><tr><td><code>Username</code></td><td><code>string</code></td><td>Username (if UseAuth)</td></tr><tr><td><code>Password</code></td><td><code>string</code></td><td>Password (if UseAuth)</td></tr></tbody></table>

#### TsTunnelCreateLportfwd

Creates a local port forward.

```go
TsTunnelCreateLportfwd(AgentId int64, Info string, Lhost string, Lport int, Thost string, Tport int) (int64, error)
```

<table><thead><tr><th width="140">Parameter</th><th width="143">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>AgentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>Info</code></td><td><code>string</code></td><td>Tunnel description</td></tr><tr><td><code>Lhost</code></td><td><code>string</code></td><td>Local address</td></tr><tr><td><code>Lport</code></td><td><code>int</code></td><td>Local port</td></tr><tr><td><code>Thost</code></td><td><code>string</code></td><td>Target address (on agent)</td></tr><tr><td><code>Tport</code></td><td><code>int</code></td><td>Target port</td></tr></tbody></table>

#### TsTunnelCreateRportfwd

Creates a reverse port forward.

```go
TsTunnelCreateRportfwd(AgentId int64, Info string, Lport int, Thost string, Tport int) (int64, error)
```

<table><thead><tr><th width="136">Parameter</th><th width="152">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>AgentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>Info</code></td><td><code>string</code></td><td>Tunnel description</td></tr><tr><td><code>Lport</code></td><td><code>int</code></td><td>Port on agent</td></tr><tr><td><code>Thost</code></td><td><code>string</code></td><td>Target address (on server)</td></tr><tr><td><code>Tport</code></td><td><code>int</code></td><td>Target port</td></tr></tbody></table>

***

### TsTunnelUpdateRportfwd

Updates reverse port forward status after the agent response.

```go
TsTunnelUpdateRportfwd(tunnelId int, result bool) (string, string, error)
```

<table><thead><tr><th width="138">Parameter</th><th width="153">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>tunnelId</code></td><td><code>int</code></td><td>Tunnel ID (numeric)</td></tr><tr><td><code>result</code></td><td><code>bool</code></td><td>Whether the tunnel was created on the agent</td></tr></tbody></table>

**Returns:** TaskId, message, error

***

### TsTunnelStop\* Functions

Functions for stopping tunnels.

#### TsTunnelStop

Stops a tunnel by ID.

```go
TsTunnelStop(tunnelId int64) error
```

**Events:**

* `tunnel.stop` (Pre/Post hooks)

#### TsTunnelStopSocks

Stops a SOCKS proxy by agent and port.

```go
TsTunnelStopSocks(AgentId int64, Port int)
```

#### TsTunnelStopLportfwd

Stops a local port forward.

```go
TsTunnelStopLportfwd(AgentId int64, Port int)
```

#### TsTunnelStopRportfwd

Stops a reverse port forward. Sends a close command to the agent.

```go
TsTunnelStopRportfwd(AgentId int64, Port int)
```

***

### TsTunnelChannelExists

Checks whether the tunnel channel exists.

```go
TsTunnelChannelExists(channelId int64) bool
```

***

### TsTunnelGetPipe

Gets pipes for reading/writing tunnel data.

```go
TsTunnelGetPipe(AgentId int64, channelId int64) (*io.PipeReader, *io.PipeWriter, error)
```

**Returns:** PipeReader for reading data from the server, PipeWriter for writing data to the tunnel.

***

### TsTunnelConnection\* Functions

Functions for managing tunnel connections.

#### TsTunnelConnectionData

Sends data to the tunnel channel.

```go
TsTunnelConnectionData(channelId int64, data []byte)
```

#### TsTunnelConnectionResume

Resumes the connection after a successful connection on the agent side.

```go
TsTunnelConnectionResume(AgentId int64, channelId int64, ioDirect bool)
```

<table><thead><tr><th width="147">Parameter</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>AgentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>channelId</code></td><td><code>int64</code></td><td>Channel ID</td></tr><tr><td><code>ioDirect</code></td><td><code>bool</code></td><td>true = direct transfer without buffering</td></tr></tbody></table>

#### TsTunnelConnectionClose

Closes the channel connection.

```go
TsTunnelConnectionClose(channelId int64, writeOnly bool)
```

<table><thead><tr><th width="147">Parameter</th><th width="109">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>channelId</code></td><td><code>int64</code></td><td>ChannelId ID</td></tr><tr><td><code>writeOnly</code></td><td><code>bool</code></td><td>To ensure sufficient time for reading and sending data over a socket. Used in async payloads such as HTTP.</td></tr></tbody></table>

#### TsTunnelConnectionHalt

Closes the connection with a SOCKS error.

```go
TsTunnelConnectionHalt(channelId int64, errorCode byte)
```

<table><thead><tr><th width="147">Parameter</th><th width="118">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>channelId</code></td><td><code>int64</code></td><td>Channel ID</td></tr><tr><td><code>errorCode</code></td><td><code>byte</code></td><td>SOCKS5 error code (1-8)</td></tr></tbody></table>

#### TsTunnelConnectionAccept

Accepts an incoming connection for reverse port forward.

```go
TsTunnelConnectionAccept(tunnelId int64, channelId int64)
```

***

#### TsTunnelConnectionBindReply

Reports a SOCKS5 BIND channel phase change to the server (the agent's response to `TunnelCallbacks.BindTCP`).

```go
TsTunnelConnectionBindReply(channelId int64, phase int, atyp int, addr []byte, port int)
```

<table><thead><tr><th width="117.9832763671875">Parameter</th><th width="92.0999755859375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>channelId</code></td><td><code>int64</code></td><td>Channel ID</td></tr><tr><td><code>phase</code></td><td><code>int</code></td><td><code>TUNNEL_BIND_LISTENING (2)</code> or <code>TUNNEL_BIND_ACCEPTED (3)</code></td></tr><tr><td><code>atyp</code></td><td><code>int</code></td><td>address type: <code>ADDRESS_TYPE_IPV4 (1)</code> / <code>DOMAIN (3)</code> / <code>IPV6 (4)</code></td></tr><tr><td><code>addr</code></td><td><code>[]byte</code></td><td>bind address (4 / 16 bytes, or domain)</td></tr><tr><td><code>port</code></td><td><code>int</code></td><td>actual port bound on the agent</td></tr></tbody></table>

***

### TsTunnelPause

Pause tunnels connection to client

```go
TsTunnelPause(channelId int)
```

***

### TsTunnelResume

Recume tunnels connection to client

```go
TsTunnelResume(channelId int)
```

***

## Terminal Functions

Functions for managing interactive terminal sessions via the agent.

### TsAgentTerminalCloseChannel

Closes the terminal channel and notifies the client.

```go
TsAgentTerminalCloseChannel(terminalId int64, status string) error
```

<table><thead><tr><th width="167">Parameter</th><th width="134">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>terminalId</code></td><td><code>int64</code></td><td>Terminal session ID</td></tr><tr><td><code>status</code></td><td><code>string</code></td><td>Close status/reason</td></tr></tbody></table>

***

### TsTerminalConnExists

Checks whether a terminal connection exists.

```go
TsTerminalConnExists(terminalId int64) bool
```

<table><thead><tr><th width="155">Parameter</th><th width="114">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>terminalId</code></td><td><code>int64</code></td><td>Terminal session ID</td></tr></tbody></table>

**Returns:** `true` if the session exists

***

### TsTerminalConnResume

Resumes the terminal connection after a successful start on the agent.

```go
TsTerminalConnResume(agentId int64, terminalId int64, ioDirect bool)
```

<table><thead><tr><th width="150">Parameter</th><th width="124">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>terminalId</code></td><td><code>int64</code></td><td>Terminal session ID</td></tr><tr><td><code>ioDirect</code></td><td><code>bool</code></td><td>true = direct transfer without buffering</td></tr></tbody></table>

***

### TsTerminalConnData

Sends data to the terminal session (output from the agent).

```go
TsTerminalConnData(terminalId int64, data []byte)
```

<table><thead><tr><th width="151">Parameter</th><th width="118">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>terminalId</code></td><td><code>int64</code></td><td>Terminal session ID</td></tr><tr><td><code>data</code></td><td><code>[]byte</code></td><td>Data to send</td></tr></tbody></table>

***

### TsTerminalConnClose

Closes the terminal session.

```go
TsTerminalConnClose(terminalId int64, reason string) error
```

<table><thead><tr><th width="149">Parameter</th><th width="133">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>terminalId</code></td><td><code>int64</code></td><td>Terminal session ID</td></tr><tr><td><code>reason</code></td><td><code>string</code></td><td>Close reason</td></tr></tbody></table>

***

### TsTerminalGetPipe

Gets pipes for terminal input/output.

```go
TsTerminalGetPipe(AgentId int64, terminalId int64) (*io.PipeReader, *io.PipeWriter, error)
```

**Returns:** PipeReader for reading input from the client, PipeWriter for writing agent output.

***

## Service Functions

### TsPluginServiceSendDataAll

Sends data to all clients on behalf of the service.

```go
TsPluginServiceSendDataAll(service string, data string)
```

***

### TsPluginServiceSendDataClient

Sends data to a specific client on behalf of the service.

```go
TsPluginServiceSendDataClient(operator string, service string, data string)
```

***

## AxScript Server Functions

Server-side AxScript engine functions. Allow loading and executing scripts on the server side, defining commands and hooks without client participation.

### TsAxScriptLoadUser

Loads a user AxScript on the server.

```go
TsAxScriptLoadUser(name string, script string) error
```

<table><thead><tr><th width="131.66668701171875">Parameter</th><th width="107.3333740234375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td><code>string</code></td><td>Script name</td></tr><tr><td><code>script</code></td><td><code>string</code></td><td>Script content</td></tr></tbody></table>

***

### TsAxScriptUnloadUser

Unloads a user AxScript from the server.

```go
TsAxScriptUnloadUser(name string) error
```

***

### TsAxScriptList

Returns a JSON list of loaded scripts.

```go
TsAxScriptList() (string, error)
```

***

### TsAxScriptCommands

Returns a JSON list of registered server-side commands.

```go
TsAxScriptCommands() (string, error)
```

***

### TsAxScriptResolveHooks

Resolves server-side hooks for an agent command. Used when processing commands where the client did not provide a hook/handler.

```go
TsAxScriptResolveHooks(agentName string, agentId int64, listenerRegName string, os int, cmdline string, args map[string]interface{}, client string) (string, string, bool, error)
```

<table><thead><tr><th width="165">Parameter</th><th width="229.6666259765625">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentName</code></td><td><code>string</code></td><td>Agent type name</td></tr><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>listenerRegName</code></td><td><code>string</code></td><td>Registered listener name</td></tr><tr><td><code>os</code></td><td><code>int</code></td><td>Agent OS type</td></tr><tr><td><code>cmdline</code></td><td><code>string</code></td><td>Command line</td></tr><tr><td><code>args</code></td><td><code>map[string]interface{}</code></td><td>Command arguments</td></tr><tr><td><code>client</code></td><td><code>string</code></td><td>Operator client name</td></tr></tbody></table>

**Returns:** `hookId`, `handlerId`, `preHookHandled` (true if Pre hook fully handled the command), `error`

***

### TsAxScriptParseAndExecute

Parses and executes a raw command via the server-side AxScript engine.

```go
TsAxScriptParseAndExecute(agentId int64, username string, cmdline string) error

TsAxScriptParseAndExecuteResult(agentId int64, username string, cmdline string) (taskId int64, local bool, err error)
```

<table><thead><tr><th width="129">Parameter</th><th width="133.66668701171875">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>agentId</code></td><td><code>int64</code></td><td>Agent ID</td></tr><tr><td><code>username</code></td><td><code>string</code></td><td>Operator name</td></tr><tr><td><code>cmdline</code></td><td><code>string</code></td><td>Command line</td></tr></tbody></table>

***

### TsAxScriptIsServerHook

True when `id` is a hook registered by a teamserver script rather than a client script.

```go
AxGetAgentContext(id string) bool
```

***

## Event Hook Functions

Generic event-hook registration. Unlike the narrow `TsEventHookOnPost` / `TsEventHookOnPre` wrappers, these methods take explicit `phase` and `priority` — multiple hooks on one event are ordered by priority.

### TsEventHookRegister

Registers an event hook with an explicit phase and priority.

```go
TsEventHookRegister(eventType string, name string, phase int, priority int, handler func(event any) error) string
```

**Parameters:**

<table><thead><tr><th width="143.066650390625">Parameter</th><th width="215.9833984375">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>eventType</code></td><td><code>string</code></td><td>Event type (e.g. <code>"task.create"</code>, <code>"agent.new"</code>, <code>"upload.finish"</code>)</td></tr><tr><td><code>name</code></td><td><code>string</code></td><td>Hook name (used for bulk unregister via <code>TsEventHookUnregisterByName</code>).</td></tr><tr><td><code>phase</code></td><td><code>int</code></td><td><code>0</code> — synchronous, before the action; <code>1</code> — asynchronous, after the action.</td></tr><tr><td><code>priority</code></td><td><code>int</code></td><td>Priority within the phase. Calls run in priority order</td></tr><tr><td><code>handler</code></td><td><code>func(event any) error</code></td><td>Handler function; receives the event as <code>any</code> (type-asserted by the plugin).</td></tr></tbody></table>

**Returns:** the hook ID (string).

***

### TsEventHookOnPre / TsEventHookOnPost

Registers a pre or post hook at the default priority and returns the hook id. Neither call emits an event.

```go
TsEventHookOnPre(eventType string, name string, handler func(event any) error) string
TsEventHookOnPost(eventType string, name string, handler func(event any) error) string
```

***

### TsEventHookUnregister

Unregisters one hook by the id returned from `TsEventHookRegister`.

```go
TsEventHookUnregister(hookID string) bool
```

Returns `true` when a hook with that id was removed.

***

### TsEventHookUnregisterByName

Unregisters all hooks registered under the given name.

```go
TsEventHookUnregisterByName(name string) int
```

**Returns:** the number of hooks removed (0 if none found).

***

### TsEventHookSetEnabled

Enables/disables a registered hook without unregistering it.

```go
TsEventHookSetEnabled(hookID string, enabled bool) error
```

***

## Extender Data Functions

Functions for storing extender data in the database.

### TsExtenderDataSave

Saves extender data to the database.

```go
TsExtenderDataSave(extenderName string, key string, value []byte) error
```

***

### TsExtenderDataLoad

Loads extender data from the database.

```go
TsExtenderDataLoad(extenderName string, key string) ([]byte, error)
```

***

### TsExtenderDataDelete

Deletes data by key from the database.

```go
TsExtenderDataDelete(extenderName string, key string) error
```

***

### TsExtenderDataKeys

Returns a list of saved extender keys.

```go
TsExtenderDataKeys(extenderName string) ([]string, error)
```

***

### TsExtenderDataDeleteAll

Deletes all extender data from the database.

```go
TsExtenderDataDeleteAll(extenderName string) error
```

***

## Endpoint Functions

Functions for registering HTTP endpoints.

### TsEndpointRegister

Registers a protected endpoint (uses the teamserver's shared JWT authentication).

```go
TsEndpointRegister(method string, path string, handler func(username string, body []byte) (int, []byte)) error
```

<table><thead><tr><th width="117">Parameter</th><th width="440">Type</th><th width="186">Description</th></tr></thead><tbody><tr><td><code>method</code></td><td><code>string</code></td><td>HTTP method (GET, POST...)</td></tr><tr><td><code>path</code></td><td><code>string</code></td><td>Endpoint path</td></tr><tr><td><code>handler</code></td><td><code>func(username string, body []byte) (int, []byte)</code></td><td>Handler</td></tr></tbody></table>

**Handler parameters:**

* `username` — authenticated username
* `body` — request body

**Handler returns:**

* `int` — HTTP status code
* `[]byte` — response body

***

### TsEndpointUnregister

Unregisters an endpoint.

```go
TsEndpointUnregister(method string, path string) error
```

***

### TsEndpointExists

Checks whether an endpoint exists.

```go
TsEndpointExists(method string, path string) bool
```

***

### TsEndpointRegisterPublic

Registers a public endpoint (no authentication).

```go
TsEndpointRegisterPublic(method string, path string, handler func(body []byte) (int, []byte)) error
```

<table><thead><tr><th width="123">Parameter</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td><code>method</code></td><td><code>string</code></td><td>HTTP method (GET, POST...)</td></tr><tr><td><code>path</code></td><td><code>string</code></td><td>Endpoint path</td></tr><tr><td><code>handler</code></td><td><code>func(body []byte) (int, []byte)</code></td><td>Handler</td></tr></tbody></table>

***

### TsEndpointUnregisterPublic

Unregisters a public endpoint.

```go
TsEndpointUnregisterPublic(method string, path string) error
```

***

### TsEndpointExistsPublic

Checks whether a public endpoint exists.

```go
TsEndpointExistsPublic(method string, path string) bool
```

***

## Logging Functions

Functions for emitting entries to the centralized `LogManager`. Entries are kept in a 5000-element RAM ring buffer (oldest are evicted), printed to stdout (status `Debug` only if the server runs with `--debug`), and batch-broadcast to every subscribed client every 50 ms / 100 entries via the WebSocket.

The `Source` field is conventionally prefixed by owner type so the client can filter by source:

| Prefix            | Owner                  |
| ----------------- | ---------------------- |
| `server:<file>`   | built-in server code   |
| `listener:<name>` | listener plugins       |
| `agent:<id>`      | per-agent activity     |
| `axscript:<file>` | user-supplied AxScript |
| `service:<name>`  | service plugins        |

`Level` is the nesting depth (0 = top-level); the client renders deeper levels with extra indentation.

### TsLogAdd

Emits one entry to the LogManager.

```go
TsLogAdd(status adaptix.LogStatus, level int, source, category string, format string, args ...any)
```

| Parameter  | Type                | Description                                                                                                                                    |
| ---------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`   | `adaptix.LogStatus` | `LogStatusDebug`(0) / `LogStatusInfo`(1) / `LogStatusSuccess`(2) / `LogStatusWarn`(3) / `LogStatusError`(4)                                    |
| `level`    | `int`               | Nesting depth                                                                                                                                  |
| `source`   | `string`            | Source. If `category` is empty and `source` contains `:`, the part before the first colon becomes the source and the rest becomes the category |
| `category` | `string`            | Category. Empty lets the manager split it out of `source`                                                                                      |
| `format`   | `string`            | `fmt.Sprintf` format                                                                                                                           |
| `args`     | `...any`            | Format arguments                                                                                                                               |

***

### TsLogWriter

Returns an `io.Writer` adapter that marshals each line written to it as a separate `LogEntry`.

```go
TsLogWriter(status adaptix.LogStatus, source, category string) io.Writer
```

| Parameter  | Type                | Description                                |
| ---------- | ------------------- | ------------------------------------------ |
| `status`   | `adaptix.LogStatus` | Severity for every entry                   |
| `source`   | `string`            | Source tag for every entry                 |
| `category` | `string`            | Category for every entry. Empty is allowed |

Typical use inside a listener plugin:

```go
import (
    "log"
    adaptix "github.com/Adaptix-Framework/axc2/v2"
)

server := &http.Server{
    Addr:     fmt.Sprintf("%s:%d", t.Config.HostBind, t.Config.PortBind),
    Handler:  router,
    ErrorLog: log.New(Ts.TsLogWriter(adaptix.LogStatusWarn, logSrc, ""), "", 0),
}
```

***

## Payload Functions

The payload store — generated agent artifacts (`Payloads` table, content on the server disk).

### TsPayloadRegister

```go
TsPayloadRegister(agentType, filename string, content []byte, listeners []string, configJson, creator, buildId, watermark, description string) (adaptix.PayloadData, error)
```

Stores a payload: metadata row in the DB + content on disk (with SHA1/SHA256/MD5).

***

### TsPayloadRemove

Remove payload from payload storage.

```go
TsPayloadRemove(ids []int64, hard bool) error
```

***

***

## Utility Functions

### TsConvertCpToUTF8

Converts a string from a code page to UTF-8.

```go
TsConvertCpToUTF8(input string, codePage int) string
```

**Supported code pages:**

* 866 (Russian DOS)
* 1251 (Cyrillic Windows)
* 1252 (Western European Windows)
* 936 (Chinese GBK)
* 65001 (UTF-8)
* and many others...

***

### TsConvertUTF8toCp

Converts UTF-8 to the agent's code page.

```go
TsConvertUTF8toCp(input string, codePage int) string
```

***

### TsWin32Error

Returns a description of a Windows error code.

```go
TsWin32Error(errorCode uint) string
```

***

## Data Types

### adaptix.AgentData

```go
type AgentData struct {
    Crc          string   // CRC/watermark of the agent type
    Id           int64    // Unique agent identifier
    UID          []byte   // Optional plugin-defined identifier
    Name         string   // Agent type name
    SessionKey   []byte   // Session key for encryption
    Listener     string   // Listener name
    Async        bool     // Asynchronous mode
    ExternalIP   string   // External IP address
    InternalIP   string   // Internal IP address
    GmtOffset    int      // Timezone offset
    Sleep        uint     // Sleep interval (seconds)
    Jitter       uint     // Jitter (percent)
    Pid          string   // Process PID
    Tid          string   // Thread TID
    Arch         string   // Architecture (x86, x64)
    Elevated     bool     // Elevated privileges
    Process      string   // Process name
    Os           int      // OS type (0=Windows, 1=Linux, 2=macOS)
    OsDesc       string   // OS description
    Domain       string   // Domain
    Computer     string   // Computer name
    Username     string   // User name
    Impersonated string   // Impersonated user
    OemCP        int      // OEM code page
    ACP          int      // ANSI code page
    CreateTime   int64    // Creation time (Unix timestamp)
    LastTick     int      // Last response time
    KillDate     int      // Self-destruct date
    WorkingTime  int      // Working time
    Tags         string   // Tags
    Mark         string   // Mark (Inactive, Terminated, etc.)
    Color        string   // Color in the GUI
    TargetId     int64    // Associated target ID (0 = none)
    CustomData   []byte   // Arbitrary plugin data
}
```

***

### adaptix.TaskData

```go
type TaskData struct {
    Type        int      // Type: TASK_TYPE_TASK=1, TASK_TYPE_BROWSER=2, TASK_TYPE_JOB=3, TASK_TYPE_TUNNEL=4, TASK_TYPE_PROXY_DATA=5
    TaskId      int64    // Unique task ID
    AgentId     int64    // Agent ID
    Client      string   // Client (operator) name
    HookId      string   // Hook ID for callback
    HandlerId   string   // Handler ID for callback
    User        string   // User on the target machine
    Computer    string   // Computer name
    StartDate   int64    // Start time
    FinishDate  int64    // Finish time
    Data        []byte   // Binary task data
    CommandLine string   // Command line
    MessageType int      // Message type: INFO=5, ERROR=6, SUCCESS=7
    Message     string   // Message header
    ClearText   string   // Message text
    Completed   bool     // Completion flag
    Priority    uint     // Priority of the task in HostedQueue (higher = earlier)
    Sync        bool     // Sync to the GUI

    // OnDispatch runs after the task is taken from HostedQueue and before PackTasks. Not serialized — lost on server restart.
    OnDispatch     func(ts any, task *TaskData) `json:"-" msgpack:"-"`

    // OnComplete fires once when Completed becomes true: on the agent result (TsTaskUpdate) or immediately when OnDispatch itself sets Completed.
    OnComplete     func(ts any, task *TaskData) `json:"-" msgpack:"-"`

    // Repeat puts the task back on HostedQueue after a dispatch while Completed is false.
    Repeat         bool                         `json:"-" msgpack:"-"`

    // DispatchBudget is how many bytes OnDispatch may still put in task.Data for this poll. 0 means unknown.
    DispatchBudget int                          `json:"-" msgpack:"-"`
}
```

***

### adaptix.ListenerData

```go
type ListenerData struct {
    Name       string   // Unique listener name
    RegName    string   // Registered type
    Protocol   string   // Protocol
    Type       string   // Listener type
    BindHost   string   // Bind address
    BindPort   string   // Bind port
    AgentAddr  string   // Address used by the agent
    CreateTime int64    // Creation time
    Status     string   // Status (running, stopped, paused)
    Data       string   // Additional data (JSON)
    Watermark  string   // Watermark
}
```

***

### adaptix.TransferData

```go
type TransferData struct {
    FileId     int64    // Unique file ID
    AgentId    int64    // Agent ID
    AgentName  string   // Agent type name
    User       string   // User
    Computer   string   // Computer
    RemotePath string   // Path on the target machine
    LocalPath  string   // Local path on the server
    TotalSize  int64    // Total file size
    Progress   int64    // How much has been transferred (downloads: received, uploads: sent)
    ReadOffset int64    // (uploads only) Read offset, not serialized
    Date       int64    // Start date
    State      int      // State: RUNNING=1, STOPPED=2, FINISHED=3, CANCELED=4
    Tag        string   // Arbitrary tag (set via TsDownloadSetTag)
}
```

***

### adaptix.TunnelData

```go
type TunnelData struct {
    TunnelId  int64    // Unique tunnel ID
    AgentId   int64    // Agent ID
    Computer  string   // Computer
    Username  string   // User
    Process   string   // Process
    Type      string   // Type (socks4, socks5, lportfwd, rportfwd)
    Info      string   // Additional information
    Interface string   // Bind interface
    Port      string   // Port
    Client    string   // Client that created the tunnel
    Fhost     string   // Forward host
    Fport     string   // Forward port
    AuthUser  string   // Authentication user
    AuthPass  string   // Authentication password
}
```

***

### adaptix.PivotData

```go
type PivotData struct {
    PivotId       string   // Unique pivot ID (remains a string)
    PivotName     string   // Pivot name
    ParentAgentId int64    // Parent agent ID
    ChildAgentId  int64    // Child agent ID
}
```

***

### adaptix.CredsData

```go
type CredsData struct {
    CredId   int64    // Unique ID
    Username string   // User name
    Password string   // Password or hash
    Realm    string   // Domain/realm
    Type     string   // Type (NTLM, Plaintext, Kerberos)
    Tag      string   // Tag
    Date     int64    // Add date
    Storage  string   // Source (LSASS, SAM, DCSync)
    AgentId  int64    // Source agent ID
    Host     string   // Source host
}
```

***

### adaptix.TargetData

```go
type TargetData struct {
    TargetId int64     // Unique target ID
    Computer string    // Computer name
    Domain   string    // Domain
    Address  string    // IP address
    Os       int       // OS type
    OsDesk   string    // OS description
    Tag      string    // Tag
    Info     string    // Additional information
    Date     int64     // Add date
    Alive    bool      // Alive
    Agents   []int64   // List of agent IDs
}
```

***

### adaptix.ScreenData

```go
type ScreenData struct {
    ScreenId  int64    // Unique screenshot ID
    User      string   // User
    Computer  string   // Computer
    LocalPath string   // Local path on the server
    Note      string   // Note
    Date      int64    // Date
    Content   []byte   // Binary content (for writes; not serialized in listings)
}
```

***

### adaptix.StatTasks / adaptix.TaskStat

Agent task statistics (returned by `TsAgentGetHostedAll`, `TsAgentGetHostedTasks`, and `TsFrameTakeStatTasks`).

```go
type TaskStat struct {
    Count int `json:"count"` // number of tasks
    Bytes int `json:"bytes"` // total size
}

type StatTasks struct {
    Local   TaskStat `json:"local"`   // local (non-agent) tasks
    Task    TaskStat `json:"task"`    // regular commands
    Browser TaskStat `json:"browser"` // browser tasks
    Job     TaskStat `json:"job"`     // job tasks
    Tunnel  TaskStat `json:"tunnel"`  // tunnel tasks
    Proxy   TaskStat `json:"proxy"`   // proxy data
    Other   TaskStat `json:"other"`   // other types
    Packed  int      `json:"packed"`  // final packed block size
}
```

**Helpers:** `stat.Of(taskType)` — the stat for a task type; `stat.Commands()` — Task+Job; `stat.Total()` — sum of all categories; `stat.Empty()`; `stat.SizeString()` — human-readable size (`FormatByteSize`).

***

### axc2 helpers (command arguments and notes)

The `github.com/Adaptix-Framework/axc2/v2` package provides helpers for parsing `args map[string]any` inside `CreateCommand` and ready-made console notes.

```go
CoerceFloat64(v any) (float64, bool)

GetStringArg(args, key) (string, error)         GetStringArgDefault(args, key, def) string
GetIntArg(args, key) (int, error)               GetFloatArg(args, key) (float64, error)
GetFloatArgDefault(args, key, def) float64      GetBoolArg(args, key) bool
GetFileArg(args, key) ([]byte, error)

MakeProxyTask(packData []byte, priority uint) TaskData
FormatByteSize(n int) string
FormatTransferNote(received bool, nBytes, nRequests int) string
QuietFrameRecv(nBytes, nRequests int) bool
NoteFrameSent(ts, agentId) / NoteFrameRecv(ts, agentId)   // see Frame Manager
```

***

### Constants

```go
// Task types
const (
    TASK_TYPE_TASK    = 1   // Regular task
    TASK_TYPE_BROWSER = 2   // File/Process Browser
    TASK_TYPE_JOB     = 3   // Background job
    TASK_TYPE_TUNNEL  = 4   // Tunnel
)

// Console message types
const (
    CONSOLE_OUT_LOCAL         = 1
    CONSOLE_OUT_LOCAL_INFO    = 2
    CONSOLE_OUT_LOCAL_ERROR   = 3
    CONSOLE_OUT_LOCAL_SUCCESS = 4
    CONSOLE_OUT_INFO          = 5   // INFO
    CONSOLE_OUT_ERROR         = 6   // ERROR
    CONSOLE_OUT_SUCCESS       = 7   // SUCCESS
    CONSOLE_OUT               = 10
)

// Transfer states
const (
    TRANSFER_STATE_RUNNING  = 1
    TRANSFER_STATE_STOPPED  = 2
    TRANSFER_STATE_FINISHED = 3
    TRANSFER_STATE_CANCELED = 4
)

// Transfer direction (used in TYPE_TRANSFER_* sync packets)
const (
    TRANSFER_DOWNLOAD = 1
    TRANSFER_UPLOAD   = 2
)
```
