Worker Agent Reference
This page is a machine-oriented reference for coding agents that generate Tianji Worker source code. For the user-facing setup and operation guide, read Worker Getting Started.
For an installable bundle that also covers common operations, download the Tianji Worker Skill.
Read this page completely before generating code. Do not infer Node.js, browser, or Cloudflare Worker APIs that are not declared here.
Give this page to an Agent
If you are a Tianji user, copy this page's URL and send it to an Agent that can access web pages:
Read this reference completely before writing code:
https://tianji.dev/docs/worker/agent-reference
If the Agent cannot access the URL, copy and paste the entire page into the conversation instead. Then describe the Worker's purpose, input, environment-variable names, external APIs, temporary data, and expected output. Never include real Secret values.
The Worker Getting Started guide provides a ready-to-copy request template and the complete user workflow.
Choose the target
There are two valid generation targets:
| Target | Output |
|---|---|
| Tianji dashboard | One self-contained source file using plain JavaScript syntax |
| Tianji CLI project | src/index.ts; TypeScript and bundled npm dependencies are allowed |
Dashboard code should use plain JavaScript unless the Tianji instance explicitly enables ENABLE_FUNCTION_WORKER_TYPESCRIPT_SUPPORT. A CLI project uses Vite to compile TypeScript before deployment.
Generate a Module Worker. Do not generate the legacy global function fetch(...) {} format.
export default {
async fetch(payload, context) {
return { ok: true };
},
};
Shared modules
Workers can use static imports from published workspace modules with aliases such as @shared/math. Inspect the module's exports and declarations in the dashboard before importing it; do not invent aliases or exported functions.
Each binding pins a specific module revision. Saving or testing code with an existing import keeps its current pin; a newly added alias resolves to the latest published revision when bindings are not supplied explicitly. Updating a shared module does not automatically upgrade an existing Worker's pin. A Worker can bind at most 16 shared modules, and shared modules cannot import dependencies themselves.
Use the Worker editor to inspect bindings and test the code together with its selected revisions. A plain dashboard Worker cannot resolve arbitrary npm imports; CLI dependencies must be bundled and compatible with the sandbox.
Runtime types
Use this contract for reasoning and TypeScript generation:
type JsonValue =
| null
| string
| number
| boolean
| JsonValue[]
| { [key: string]: JsonValue };
interface WorkerRequestContext {
method: string;
url: string;
headers: Record<string, string | string[] | undefined>;
}
interface WorkerContext {
type: 'http' | 'cron' | 'manual' | 'test';
env: Record<string, string>;
request?: WorkerRequestContext;
}
interface TianjiWorker {
fetch(
payload: Record<string, unknown>,
context: WorkerContext
): unknown | Promise<unknown>;
}
interface RequestConfig {
url: string;
method?: string;
headers?: Record<string, string>;
params?: Record<string, unknown>;
data?: unknown;
timeout?: number;
}
interface RequestResult {
status: number;
headers: Record<string, unknown>;
data: unknown;
}
declare function request(config: RequestConfig): Promise<RequestResult>;
interface KVScope {
get<T extends JsonValue = JsonValue>(key: string): Promise<T | undefined>;
set(key: string, value: JsonValue, ttlMilliseconds?: number): Promise<void>;
delete(key: string): Promise<boolean>;
}
declare const kv: KVScope & { workspace: KVScope };
The types above document runtime globals. Do not include the declare statements in dashboard JavaScript output. A CLI TypeScript project may include declarations when type checking needs them.
Input contract
payloadis always an object.- For HTTP execution, Tianji merges query parameters and the request body. Body fields overwrite query fields with the same name.
- A cron execution without input receives
{}. - Treat every payload field as untrusted. Check its type, required status, format, length, and allowed range before using it.
- Do not assume query parameters have already been converted to numbers or booleans.
- Reject or return a clear error for invalid input rather than silently constructing unsafe requests.
context.request exists only when context.type === 'http'. Guard access to it:
if (context.type !== 'http') {
return { error: 'HTTP trigger required' };
}
const method = context.request.method;
Output contract
- Return JSON-compatible objects and arrays, a string, or a number.
- For an HTTP trigger, Tianji serializes object results as JSON.
- Do not return secrets or internal error objects.
- Normalize upstream API responses into a stable result owned by the worker.
- Use
console.log,console.warn, andconsole.errorfor execution logs.
Sandbox contract
The Worker sandbox provides standard JavaScript built-ins, captured console methods, request, and kv.
The sandbox is not Node.js and not a browser. Do not generate code that uses:
process,Buffer, filesystem, child processes, sockets, or other Node.js APIs.- DOM APIs, browser storage, or browser
fetch. - Cloudflare Worker bindings or event handlers.
- Undocumented globals.
For outbound HTTP, use request with an Axios-style configuration:
const response = await request({
method: 'POST',
url: context.env.API_URL,
headers: { Authorization: `Bearer ${context.env.API_TOKEN}` },
data: { value: payload.value },
timeout: 10_000,
});
Check required URLs and credentials before calling request. Handle remote failures and avoid placing credentials in query strings.
Environment and Secret contract
Environment values are available only through context.env:
const apiUrl = context.env.API_URL;
const apiToken = context.env.API_TOKEN;