Skip to main content

Employees from code

Create and prepare an employee from your own system, then continue the same work in the Docana UI. An employee is an Assistant application with a goal, portrait, category, and persona. The application holds its agents, collections, website access, channels, and other settings. One agent usually does the work. An employee can also contain several cooperating agents.

The employee UI and the public interfaces share the same creation, preparation, knowledge, and credential services. You can use the preparation assistant from Claude, ChatGPT, or the CLI, or build the underlying agents directly with the existing APIs. The employee's ID is its application ID. The application carries an explicit employee profile. Existing Assistant applications without that profile remain regular applications.

For the same workflow in the product, see the employee walkthrough with screenshots. The Applications guide shows how an employee connects to its underlying workspace.

Employee creation enables skillsEnabled and codeExecutionEnabled in application settings. Generated files remain excluded from retrieval by default (codeExecutionOutputRetrievable: false). Drafts authored through preparation receive common PDF/chart instructions, including real output files, source checks, and download links. Existing employees can enable these capabilities through application settings or preparation.

Create and prepare​

Sign in with docana login, or set DOCANA_API_URL and a Full access DOCANA_API_KEY together. Run docana whoami to confirm the deployment before writing. REST requests use Authorization: ApiKey <key>; MCP also supports browser sign-in. Every operation checks the caller's existing application access. Preparing an employee and changing its settings require write permission.

To use the same role templates as the UI, run:

docana employees templates --locale en-US

The catalog returns 20 entries with an id, title, description, and an employee object containing name, job, group, avatar, and personaPreset. Choose an entry, customize its employee object, and save that object as employee.json for the existing create command. Keep the full employee.job instructions and append your team’s requirements to that string. The UI does the same when someone selects a role and adds context in the text area; there is no separate template ID required by the create API. pt-BR returns Portuguese text. MCP clients call listEmployeeTemplates with query: { "locale": "en-US" }, then pass the chosen employee fields as the body of createEmployee. Listing templates is read-only. Creation and preparation remain separate operations.

Save an employee definition as employee.json:

{
"name": "Robin",
"avatar": "sage",
"group": "FINANCE",
"personaPreset": "neutral",
"job": "Compare supplier invoices with purchase orders, flag discrepancies, and prepare a weekly report with verified totals."
}
docana employees create employee.json
# Returns { "success": true, "applicationId": 42 }

docana employees prepare 42 "Create the draft, define expectations for missing and conflicting data, and measure discrepancies and human handoffs."
# Returns { "threadId": "...", "text": "...", "tools": [...] }

docana employees prepare 42 "Also check that the report totals match the source invoices." --thread <thread-id>

Creation saves the employee identity and owner membership. Preparation builds drafts, connects available capabilities, defines evaluation scenarios, and configures performance measures. It uses the same scoped tools and saved conversation as the UI. The assistant considers source verification, conversation history, document and chart deliverables, bounded follow-ups, and requested routines when relevant to the job. Inspect its results and run representative tests; a generated plan does not prove the employee can do the job.

listEmployees separates a selected draft needing publication (needsPublication: true) from a published, enabled agent available for chat (chatAgentId). Neither field certifies that tests passed. Review & publish opens the draft for review without changing it. Publish the selected agent through the existing agent publication endpoint after reviewing its workflow and tests.

Preparation can call the existing publishAgent MCP operation after explicit user approval. The UI creation button starts draft preparation immediately. API and CLI clients still call creation and preparation separately. A new routine requested with enabled: true (or the default) on an unpublished employee is saved disabled with lifecycle-owned pending state. Publication activates that pending work. Explicitly disabled and imported routines remain paused. The publication response includes routineActivation counts and an optional unavailable flag, so clients can report activation failures without claiming publication failed.

The JSON preparation call can take several minutes. Continue with its returned threadId to preserve context. After a timeout or interruption, inspect employee status and preparation history before repeating a write: the turn may have completed some operations. Each turn allows up to 60 tool steps and 8 minutes of work, then reserves a final response to summarize verified results and remaining work. Repairs are limited to 3 rounds. Long sandbox sessions move to saving and verification before the overall limit. If the model ends a tool turn without an answer, a saved fallback message explains that the final summary is missing and points the user to recorded expectations. Preparation is not a durable background job.

Prepare from files or a voice brief​

Attach an existing job description or recording to the same preparation command:

docana employees prepare 42 "Use this brief to prepare a draft and ask about missing requirements." \
--attach ./job-description.pdf \
--attach ./voice-brief.webm

--attach is repeatable. Preparation accepts up to 10 files with a combined decoded size of 20 MB. The CLI reads local files and sends base64 data URLs. REST and MCP callers supply attachments alongside prompt:

{
"prompt": "Summarize this job brief and ask what is missing.",
"attachments": [
{
"name": "brief.txt",
"contentType": "text/plain",
"url": "data:text/plain;base64,UmV2aWV3IGludm9pY2VzLg=="
}
]
}

The file above contains “Review invoices.” Remote URLs are not accepted by this brief field. Supported content follows the existing chat attachment pipeline. Files and audio stay with the saved preparation conversation. For lasting searchable sources, use collection uploads and connectors. Incomplete attachment ingestion stops preparation so it cannot silently build from a partial brief.

The reply includes attachmentCount, the number of incoming attachments confirmed saved with that message. Check it against the number you sent before treating the brief as delivered. The creation form makes this check before opening the saved conversation.

The employee form accepts written, file, and voice briefs using the same preparation service as the API.
The UI and code share the employee definition and preparation conversation.

REST, MCP, and CLI operations​

Paths below are relative to /api/v1/employees/. MCP names match the documented operation IDs. MCP JSON bodies are nested in a body argument, alongside path parameters such as id.

ActionRESTMCP toolCLI
List role templatesGET /templates/?locale=en-USlistEmployeeTemplatesemployees templates --locale en-US
List employeesGET /listEmployeesemployees list --limit 25 --cursor <id>
Create employeePOST /createEmployeeemployees create <file>
Read identity and goalGET /{id}/getEmployeeemployees get <id>
Browse knowledge filesGET /{id}/knowledge/?limit=50&search=policylistEmployeeKnowledgeFilesemployees files <id> --search policy
Change portrait or categoryPATCH /{id}/updateEmployeeIdentityemployees identity <id> <file>
Prepare from a messagePOST /{id}/prepare-message/askEmployeePreparationemployees prepare <id> <prompt> --thread <id>
Resolve knowledge collectionPOST /{id}/knowledge/prepareEmployeeKnowledgeemployees knowledge <id>
List enabled test scenariosGET /{id}/expectations/listEmployeeExpectationsemployees expectations <id>
Read tests, sources, and workGET /{id}/status/getEmployeePreparationStatusemployees status <id>
Read performance measuresGET /{id}/performance/getEmployeePerformanceemployees performance <id>
Read website accessGET /{id}/websites/getEmployeeWebsitesemployees websites <id>
Save a website loginPATCH /{id}/websites/{siteId}/login/updateEmployeeWebsiteLoginemployees login <id> <siteId> --file <file>

For example, an MCP preparation invocation has this input:

{
"id": 42,
"body": {
"prompt": "Inspect the current draft and explain which expectations still need tests.",
"threadId": "your-preparation-thread-id"
}
}

The UI consumes POST /api/v1/employees/{id}/prepare/, which streams AI SDK UI messages. Its non-streaming counterpart, askEmployeePreparation, returns the conversation ID, answer text, and tool completion states. It omits internal reasoning and tool payloads. Both use one preparation engine.

During preparation, the server tracks IDs returned by test creation and waits on pending tests in batches. The internal waitForEmployeeTests tool takes no run IDs and waits for up to 30 seconds per call. It does not start another test. Completed results stop polling. Unavailable status reads remain unverified rather than becoming failed expectations. Large diagnostic payloads and old tool exchanges are compacted in model context, including conversations saved before this protection was added. Original tool records remain available in the conversation.

listEmployees returns up to 50 visible employees per page with a nextCursor. Pagination is applied in the database before loading agents. Portrait IDs are sage, iris, sunny, coral, bruno (Bruno Admin), hazel (Ellie), john, philip, hiro, henry, peter, mike, ana, marcellus, and timon. Categories use company-scoped stable keys. List them with docana categories list, then pass categoryKey when creating or editing an employee. The legacy group field remains supported for existing integrations. To discover persona presets and all field constraints, run docana api schema search employees or read the API reference. Persona settings remain available through applications persona and the existing application settings APIs.

Add substantial knowledge​

Resolve the employee's collection, then use existing document ingestion or source connectors:

docana employees knowledge 42
# Returns collection.id, collection.name, and collection.libraryId

docana documents push <collection-id> ./policies/*.pdf
docana connections connect GoogleDrive
docana collections link <collection-id> -c <connection-id> -f <folder-id> -n "Company policies"
docana collections sync <collection-id>

The UI accepts up to 1,000 knowledge files per batch and queues three transfers at a time. Drop a folder or select Choose folder to retain its root folder and nested file paths in the employee’s collection. Knowledge’s collection upload dialog and drop targets use the same folder resolution. Matching manual folders are reused; connector-synced folders stay separate. Empty directories contain no documents and are omitted. These files go into a collection. Message attachments use the existing chat attachment pipeline. Upload completion and indexing completion are separate states; inspect collection documents before assuming a source is searchable. MCP clients use the existing upload tools or document ingestion protocol, including chunked uploads for larger files.

Test, measure, and connect​

employees expectations lists enabled cases across the employee's agents. To retrieve each enabled scenario with its latest result, including scenarios never run, use GET /api/v1/employees/{id}/expectations/?includeResults=true. MCP clients pass { "id": 42, "includeResults": "true" } to listEmployeeExpectations. CLI clients can use docana api GET '/api/v1/employees/42/expectations/?includeResults=true'. This read returns { expectations: [...], results: [...] } with testCaseId, name, status, verdict, reason, timing, score, and a conversation ID when available. The default response remains { expectations: [...] } for clients that select scenarios to run. Result reads require employee read access. The default scenario list keeps its existing write-access requirement. The UI's Run tests button runs those cases through the existing test-case run API; use docana agents eval-case run --agent-id <agent-id> --case-id <case-id> for the same operation, then inspect each returned run. employees status summarizes observed test outcomes and recent execution activity. Its progress.executions contains up to five work runs from the last 30 days, excluding evaluation conversations. Each run includes durationMs (wall time from creation to the last update, including waits; null while running or when timestamps are invalid), nodeCount (recorded nodes, including nested steps), errorCount, and specArtifactVersion when available. These same fields are returned by REST and the getEmployeePreparationStatus MCP tool; execution IDs link to the existing agent execution APIs. It does not certify the current draft: changing a draft can make earlier test evidence stale.

employees performance returns per-agent Conversation Insights over the last 30 days, with bounded samples and explicit truncation flags. conversations counts distinct real-work conversations contributing collected fields, while analyses counts the extraction snapshots read. Each measure uses the latest saved observation per field and conversation, so repeated every-turn extractions do not overweight a conversation. Prompt edits preserve collected values under stable field IDs. New fields stay empty until collected, and unavailable observations do not revive older values. Evaluation conversations and experiment observations are excluded. The same response is used by REST, the getEmployeePerformance MCP tool, and the CLI. Numeric measures report averages, booleans report the share recorded as true, and categories report the most common value. Unknown values remain empty. These are captured observations, not a universal employee score. Configure measures through agents insights, and inspect executions through agents runs or the existing execution UI.

Routines, channels, collections, skills, application persona, and MCP connections keep their existing public contracts. The preparation assistant can configure the capabilities in its scoped catalog; other controls link to the corresponding existing setup screens. A request to connect a provider may still require its browser sign-in.

For a collector, preparation and the agent builder can create a table and columns in the current application, then configure a native saveTableRecord Tool call using the saved IDs. The same setup works through their UI and headless endpoints. Table and schema writes take effect immediately; the workflow remains a draft. See saving records from agents for mapping, retries, and notification limits.

Website access and credentials​

Use the existing application allowed-website APIs, MCP tools, or docana app <id> allowed-websites commands to register a specific website with the advanced browser. The preparation assistant can also register the requested site. Saving access is separate from verifying a successful sign-in; MFA, CAPTCHA, or unavailable browser infrastructure can still block work.

For a caller-owned website linked exclusively to the employee, the secure login operation accepts username, password, persistContext, and clearCredentials. Supply credentials through a secure form or a private local JSON file, then run:

docana employees login 42 <website-id> --file /private/path/website-login.json

Passwords are encrypted before storage and never returned. An omitted or blank password preserves the saved password; clearCredentials: true removes both login fields. Persistent browser context is an explicit opt-in. The employee preparation assistant does not accept credential arguments through its own tools: enter them through the secure operation instead of ordinary chat. Shared websites require their existing advanced settings.

Change the portrait​

Use PATCH /api/v1/employees/{id}/, the updateEmployeeIdentity MCP tool, or the CLI identity command. They share the same save operation as the employee profile editor.

# portrait.json contains: { "avatar": "iris" }
docana employees identity 42 portrait.json

The employee's goal and primary agent stay unchanged. Existing Twilio senders whose picture follows the employee receive the new portrait, including paused channels. Missing pictures are filled when a sender already exists. A custom channel logo is preserved. Meta and proxy pictures remain provider-managed. If the provider rejects the photo update, the identity save fails without saving the new portrait. Retry the same request after resolving the provider error. Category-only changes do not touch channel pictures.

Contact an employee on WhatsApp​

Ask preparation to open WhatsApp setup, or use Add a channel → WhatsApp beneath the employee’s portrait. The UI-only openEmployeeChannelSetup tool opens the existing dialog and changes no settings. Publish the primary agent before enabling the number. You can enable or pause the existing WhatsApp channel without leaving preparation. Once a number is assigned, the profile shows it and the dialog offers a QR code and a link to start a conversation. The QR code opens wa.me; it does not pair a personal WhatsApp account. Provider status shows whether setup still needs attention. New employee numbers default to public access. Send isPublic: false to make one private, or omit the field to preserve its saved choice. Enabled employee channels resolve to the published primary agent at the shared save service. The list API exposes a credential-free whatsapp contact summary including number, enabled state, access mode and routing readiness.

New Twilio setup uses the employee portrait when no custom logo is set. Later portrait saves keep that picture in sync through the identity operation above.

Twilio can assign a paid number through the configured provider account. The dialog explains this before you select Get number & enable. Meta and proxy configurations use their existing channel setup; connect the business number in advanced settings first. Disabling preserves the number, routing, privacy, voice settings, and credentials.

The UI and external assistants use the same operations:

OperationRESTMCP
Read the number and statusGET /api/v1/employees/{id}/channels/whatsapp/getEmployeeWhatsApp
Enable or pause WhatsAppPATCH /api/v1/employees/{id}/channels/whatsapp/updateEmployeeWhatsApp

Read the contact from the CLI:

docana employees whatsapp 12

Enable an existing connection with --enable, or pause it with --disable. Add --public or --private to explicitly choose access. Omit both flags to preserve the saved choice, or use the public default for a new number. To allow provisioning a paid Twilio number when none is assigned:

docana employees whatsapp 12 --enable --acknowledge-number-purchase

PATCH accepts enabled, optional isPublic, and optional acknowledgeNumberPurchase. Write access is required, credentials are never returned, and incomplete provider setup returns 409. Channel activation remains an explicit user action; the preparation assistant cannot enable channels on its own.

Follow a large upload​

The preparation page keeps the batch count and progress bar visible. Select View uploads to open the same file cards used in Knowledge, with relative folder paths, file status, and progress. Large queues show 25 files per page and support searching by file or folder name. Closing the dialog keeps transfers running while you continue preparing the employee. Saved files still need background processing before they are ready for retrieval.

Shared categories​

Employees and Applications use the same catalog. The following routes are relative to /api/v1/:

ActionRESTMCPCLI
List categoriesGET /application-categories/?locale=en-USlistApplicationCategoriesdocana categories list
Create a categoryPOST /application-categories/createApplicationCategorydocana categories create category.json
Rename or change an iconPATCH /application-categories/{key}/updateApplicationCategorydocana categories update <key> category.json

For creation, category.json contains a name and an optional icon, for example { "name": "Customer success", "icon": "support" }. Updates accept either field. Names are normalized and unique within the company. Creation and editing require company administrator access. Listing also returns canManage for the caller. The icon choices are documented in the request schema.

Use the returned stable key as categoryKey in createEmployee, updateEmployeeIdentity, createApplication, or updateApplication. CLI users can pass --category <key> to docana apps create. A category rename or icon change applies to every existing assignment. Unknown or foreign-company keys are rejected. Updates that omit both category fields preserve the assignment. A legacy group update selects that group; an explicit categoryKey: null update returns to the supplied group or Default.

The Prisma rollout is additive: ApplicationCategory stores company names and icons, while nullable Application.categoryKey links assignments. Existing applications with no key resolve their legacy group. The existing database enum and group column remain during the rolling deployment for backward compatibility. Their eventual removal requires a later migration after deployed readers stop depending on them. Both schema and concurrent-index migrations include rollback scripts.

Knowledge coverage​

employees status <id> and getEmployeePreparationStatus include knowledge: total files, ready, processing, failed, pages, filesWithPageCount, and a bounded types distribution. Counts are computed in the database across accessible connected source collections. Archived files, workflow artifacts, and temporary chat attachments are excluded. Page totals only include known positive page counts on completed files, so missing page metadata never becomes an invented count.

employees files <id> --limit 50 --cursor <next_cursor> --search policy browses the full source set. Results include file IDs, names, status, collection and library IDs, and an optional folder ID. Pagination uses decreasing document IDs and a nextCursor when more results exist. Search matches filenames without case sensitivity. File contents and private storage paths are not included.

MCP providers​

Employee preparation reuses the existing MCP server APIs. List available providers with listApplicationMcpServers, create a private server with createMcpServer, and select it with enableApplicationMcpServer. getMcpServerConnectionById checks the current user's authentication; testMcpServerConnectionById checks tool discovery. Selection alone does not prove a working connection.

The CLI exposes the same operations under docana mcp-servers and docana app <id> mcp. Use --help for each command's arguments. The preparation assistant can register a credential-free or OAuth-discovery endpoint and enable it within the employee application. It cannot read or accept provider secrets. Complete OAuth consent or enter credentials through MCP connections in the preparation UI. Registration requires company administrator permission; existing application selection follows application write access.

Portable employee and application packages​

Employees reuse the application transfer contract: docana.application, version 1. Standalone agent exports keep their existing format and endpoint. The application exporter calls the shared agent export utilities for inlined criteria, evaluations, routines, insights, and baseline mocks, then applies application-package cleanup.

docana employees export 42 --output robin.docana.json
docana employees import robin.docana.json --check
docana employees import robin.docana.json --name "Robin restored" --category FINANCE
docana employees import-report 43 --search policy --offset 0

# The same package and services for any application
docana applications export 42 --output application.docana.json
docana applications import application.docana.json --name "Restored application"

--check inspects the local file without a server mutation; the import API validates the full package. Export uses exclusive file creation and will not overwrite an existing output file. Packages are limited to 20 MB, 200 agents, 500 document templates, and 100,000 source references.

REST operationMCP tool
GET /api/v1/applications/{id}/export/exportApplication
POST /api/v1/applications/import/importApplication
GET /api/v1/applications/{id}/import-report/getApplicationImportReport

Import accepts { package, name?, categoryKey? }. Export and checklist access require application write permission; import requires application creation permission and available quota. Import creates a new owner-admin membership and restores definitions in one transaction. It never copies source memberships, provider authentication, file binaries, conversations, or execution logs.

The dependency manifest contains metadata-only references. Internal agent and document-template IDs are remapped to newly created records. Recognized external resource IDs become unresolved placeholders, including IDs in serialized tool arguments. Reconnect resources and update references in the draft before testing and publishing. Unstructured IDs or secrets written inside authored prompts cannot be identified reliably; review instructions, examples, and template content before sharing.

The checklist is stored as an application-owned artifact. Its API returns up to 50 references by default, with totalCount, filteredCount, and nextOffset. Pass offset, limit (1 to 100), and search to inspect large manifests without returning every file to the client. Original references remain available if the restored application is exported again.

Add an existing Assistant application to Employees​

Use this when you already have an application and want the employee preparation experience around it. Unlike package import, adoption keeps the existing ID and resources. It requires application write access and an active ASSISTANT application. Other application types are rejected.

docana employees application-setup 42 --limit 25

The response contains the application name and description, any existing employee profile, and a paginated list of eligible agents. Follow nextCursor with --cursor to see more agents. Choose the primary agent explicitly when there are several. A sole agent is selected automatically; an application without agents can be adopted and prepared afterward.

Save the reviewed identity in employee.json:

{
"avatar": "sage",
"job": "Review weekly supplier invoices, reconcile totals and flag missing evidence.",
"primaryAgentId": "your-existing-agent-id"
}
docana employees adopt 42 employee.json

REST uses GET /api/v1/applications/42/employee/ for the preview and POST to the same path with the JSON body above. MCP exposes getApplicationEmployeeSetup and adoptApplicationAsEmployee. The result is { "success": true, "applicationId": 42 }.

Only the employee profile is added. Existing agents, publication, knowledge, connections, persona, members and routines remain intact. Adoption does not make an unpublished agent available for chat or activate paused work. Repeating it preserves an existing employee profile. If another edit changes the application during adoption, the API returns 409; refresh the preview before retrying.

Read recurring responsibilities​

docana employees routines 42 --limit 25

GET /api/v1/employees/42/routines/ and the MCP tool listEmployeeRoutines return routines, total, nextCursor, and canWrite. Each routine includes its name, agent, enabled state, last run, and saved triggers. Scheduled triggers include the UTC cron expression and nextRunAt; disabled routines, disabled agents, disabled triggers, and triggers without a valid schedule have no next scheduled run. Document triggers retain their selected collection IDs; an empty list means the application's connected collections. API triggers describe on-demand work.

The directory's listEmployees response includes a responsibilities preview with a total and up to two routines per employee. Use the dedicated list endpoint for the rest. These fields describe saved configuration, not a guarantee that an external scheduler or a future execution will succeed. To edit, pause or enable a routine, use the existing routine APIs with its agentId and routine ID. Reading either endpoint starts no work.