Web SDK

更新时间:
复制 MD 格式

Agentic Computer Web SDK is a JavaScript SDK provided by Wuying that lets you integrate agent management, session messaging, skill management, credit management, model configuration, and cloud desktop streaming into your web applications.

Overview

Agentic Computer Web SDK is a JavaScript SDK provided by Wuying for integrating agent management, session messaging, skill management, credit management, model configuration, and cloud desktop streaming into web applications. Use Agentic Computer Web SDK to build intelligent applications powered by Wuying agents, with conversational interaction, skill extensions, and model switching.

Features

Agentic Computer Web SDK provides the following core capabilities:

Feature

Description

Agent management

List agents, create and manage sessions, send text, image, and file messages, subscribe to real-time events, and get message history.

Skill management

List skill categories and installed skills, enable or disable skills, and install or uninstall skills.

Credit management

Query credit packages and bound agents, and check credit usage.

Model configuration

List available models for an agent and set a specific LLM model for a session.

Cloud desktop streaming

Start and manage streaming sessions for cloud desktops or cloud applications (browser environments only).

Runtime environments

Agentic Computer Web SDK supports both browser and Node.js runtime environments.

Runtime

Module format

Description

Browser

ESM (.mjs)

Supports all features, including cloud desktop streaming.

Node.js

CJS (.js) / ESM (.mjs)

Supports all features except cloud desktop streaming. TypeScript type definition files (.d.ts) are provided.

SDK architecture

Agentic Computer Web SDK uses a global singleton pattern with the Client class as the entry point. Each functional manager is built on demand.

The overall SDK architecture is as follows:

Client (global singleton)
├── AgentManager          // Multi-agent management: agent list, sessions, messages, events
├── SingleAgentManager    // Single-agent simplified mode: auto-binds agent and session
├── SkillManager          // Skill management: category queries, install/uninstall, enable/disable
├── CreditManager         // Credit management: plan queries, usage statistics
├── ModelManager          // Model configuration: model queries, session model switching
└── AspManager            // Streaming management: cloud computer/app streaming sessions (browser only)

Quick start

Browser (ESM)

<script type="module">
  import { Client } from './wuying-sdk.mjs';
</script>

Node.js

// ESM
import { Client } from '@aliyun/wuying-sdk';

// CommonJS
const { Client } = require('@aliyun/wuying-sdk');

Initialize the SDK with an AuthCode. The AuthCode is generated on the server side and passed to the frontend.

import { Client } from './wuying-sdk.mjs';

// Create a Client instance (global singleton)
const client = Client.create({
  authCode: 'your-auth-code',
});

// Build the required Manager
const agentManager = await client.buildAgentManager({});

// Query the agent list
const agentList = await agentManager.listAgents({});
console.log('Agent count:', agentList?.agents.length);

// Release resources when finished
await client.close();
Note

The AuthCode must be generated on the server side and passed to the frontend. Don't use AccessKey ID and AccessKey Secret (AK/SK) directly in frontend code.

1. Client class

Client is the SDK entry class and uses a global singleton pattern. After creating an instance with Client.create(), build functional managers as needed.

1.1 ClientOptions

Parameter

Type

Required

Description

authCode

string

Yes

The authentication code generated on the server side.

1.2 UserConfig

Optional user configuration parameters.

Parameter

Type

Required

Description

timeout

number

No

Request timeout in milliseconds. Default value: 30000.

maxRetries

number

No

Maximum number of retries. Default value: 3.

logger

Logger

No

Custom logger object.

clientId

string

No

Client identifier. Default value: 'sdk-client'.

imDataDir

string

No

Message data storage directory. Default value: '/openim_db'. Applies to Node.js environments only.

imPlatformId

number

No

Messaging platform identifier. Default value: 1. Applies to Node.js environments only.

1.3 Methods

Method

Description

Client.create(options, userConfig?)

Creates or gets the global singleton Client instance.

buildAgentManager(ctx)

Builds a multi-agent manager.

buildSingleAgentManager(ctx)

Builds a single-agent manager that automatically binds an agent and session.

buildSkillManager(ctx)

Builds a skill manager.

buildCreditManager(ctx)

Builds a credit manager.

buildModelManager(ctx)

Builds a model configuration manager.

buildAspManager(ctx)

Builds a streaming manager (browser environments only).

subscribeEvent(callback, ...opts)

Subscribes to global events.

listSubscriptions()

Lists all active event subscriptions.

logout()

Clears state while keeping the instance reusable.

close()

Destroys the instance and releases all internal resources.

Initialization example

import { Client } from './wuying-sdk.mjs';

const client = Client.create({
  authCode: 'your-auth-code',
}, {
  timeout: 30000,
  maxRetries: 3,
});

// Build the required Managers
const agentManager = await client.buildAgentManager({});
const skillManager = await client.buildSkillManager({});

// Release resources when finished
await client.close();

2. AgentManager class

A unified multi-agent, multi-session manager that provides agent queries, session management, message sending and receiving, and event subscriptions.

2.1 Agent operations

listAgents(ctx, req?)

Lists agents.

Parameter

Type

Required

Description

pageNum

number

No

Page number. Default value: 1.

pageSize

number

No

Number of items per page. Default value: 20.

keyword

string

No

Search keyword to filter agents.

queryFotaUpdate

boolean

No

Whether to query FOTA upgrade information. When set to true, the fotaUpdate field in the returned Agent object is populated.

Returns an AgentList object that contains agents (an array of Agent objects) and total (the total count).

2.2 Session operations

listSessions(ctx, req?)

Lists sessions.

Parameter

Type

Required

Description

agentID

string

No

Agent ID. Filters sessions by a specific agent.

offset

number

No

Offset. Default value: 0.

count

number

No

Number of items per page. Default value: 20.

keyword

string

No

Search keyword.

createSession(ctx, req)

Creates a session.

Parameter

Type

Required

Description

agentID

string

Yes

The ID of the agent to create a session for.

Returns a Session object.

dismissSession(ctx, req)

Dismisses an existing session. This operation is irreversible.

Parameter

Type

Required

Description

sessionID

string

Yes

The ID of the session to dismiss. Must be in numeric format (for example, "3539096907"). Use the groupId property of a Session object.

Warning

Dismissed sessions can't be recovered. Proceed with caution.

2.3 Message operations

Method

Description

sendTextMessage(ctx, req)

Sends a text message. Requires sessionID and content.

sendTextMessageWithSync(ctx, req)

Sends a text message and waits for the agent response. A timeout can be configured (default: 60 seconds).

sendImageMessage(ctx, req)

Sends an image message. Requires sessionID and imagePath.

sendFileMessage(ctx, req)

Sends a file message. Requires sessionID and filePath.

sendMergerMessage(ctx, req)

Sends a merged message. Requires sessionID, title, and summaries.

sendCompositeMessage(ctx, req)

Sends a composite message that can contain text, images, and files.

getSessionHistoryMessageList(ctx, req)

Gets the message history for a session. Supports pagination.

2.4 Event subscriptions

subscribeEvent(ctx, req, callback)

Subscribes to events for a specific session. Returns an EventHandle object. Call its unsubscribe() method to cancel the subscription.

Parameter

Type

Required

Description

sessionID

string

Yes

The ID of the session to subscribe events for.

eventTypes

EventType[]

No

Event types to subscribe to. If not specified, all event types are subscribed.

2.5 Complete example

import { Client, EventType } from './wuying-sdk.mjs';

async function agentExample() {
  const client = Client.create({ authCode: 'your-auth-code' });

  try {
    const agentMgr = await client.buildAgentManager({});

    // Query the agent list
    const agentList = await agentMgr.listAgents({}, { pageSize: 20 });
    if (!agentList?.agents.length) {
      console.error('No agents available');
      return;
    }
    const agent = agentList.agents[0];

    // Create a session
    const session = await agentMgr.createSession({}, { agentID: agent.id });

    // Subscribe to events
    const handle = agentMgr.subscribeEvent(
      {},
      { sessionID: session.id, eventTypes: [EventType.Message, EventType.StreamMessage] },
      (event) => {
        if (event.type === EventType.Message) {
          console.log('Message received:', event.message?.content);
        }
      }
    );

    // Send a message
    await agentMgr.sendTextMessage({}, {
      sessionID: session.id,
      content: 'Hello',
    });

    // Send a message and wait for the response
    const response = await agentMgr.sendTextMessageWithSync({}, {
      sessionID: session.id,
      content: 'What is the weather like today?',
      timeoutSeconds: 30,
    });
    console.log('Agent response:', response?.messages.map(m => m.content));

    // Unsubscribe
    handle.unsubscribe();
  } finally {
    await client.close();
  }
}

2.6 FOTA upgrade

The FOTA (Firmware Over-The-Air) upgrade feature performs firmware upgrades for agents whose underlying instances are cloud desktops.

Query FOTA information

Call listAgents with queryFotaUpdate: true. The fotaUpdate field in the returned Agent object is then populated. A non-empty fotaUpdate.newFotaVersion value indicates that a FOTA upgrade is available.

AgentFotaUpdate type

Field

Type

Description

newFotaVersion

string

Target FOTA version available for upgrade. A non-empty value indicates that an upgrade is available.

currentFotaVersion

string

Current FOTA version.

approveFotaUpdate(ctx, req)

Performs a FOTA upgrade.

Parameter

Type

Required

Description

resourceId

string

Yes

Target resource ID. Get it from agent.runtimeResourceInfo.resourceId.

appVersion

string

Yes

Target upgrade version. Get it from agent.fotaUpdate.newFotaVersion.

regionId

string

No

Region ID. Default value: cn-shanghai. You must explicitly specify the regionId when upgrading an agent that isn't in the default region.

FOTA upgrade example

const agentMgr = await client.buildAgentManager({});

// Query the agent list with FOTA information
const result = await agentMgr.listAgents({}, { queryFotaUpdate: true });

for (const agent of result?.agents ?? []) {
  if (agent.fotaUpdate?.newFotaVersion) {
    console.log(
      `Agent ${agent.name} has an available upgrade: ${agent.fotaUpdate.currentFotaVersion} → ${agent.fotaUpdate.newFotaVersion}`
    );

    // Perform the upgrade
    await agentMgr.approveFotaUpdate({}, {
      resourceId: agent.runtimeResourceInfo.resourceId,
      appVersion: agent.fotaUpdate.newFotaVersion,
    });
    console.log(`Agent ${agent.name} FOTA upgrade submitted`);
  }
}

2.7 Update agent instance

updateAgentInstance(ctx, req)

Updates the configuration of an agent's underlying instance, such as the instance type or image.

Parameter

Type

Required

Description

resourceId

string

Yes

The underlying resource ID of the agent. Get it from agent.runtimeResourceInfo.resourceId.

3. SingleAgentManager class

A simplified single-agent manager. It automatically binds an agent and its session, so there's no need to manually specify a sessionID for each operation. This is ideal for scenarios that use only one agent.

Method

Description

agent()

Gets the bound agent object.

groupID()

Gets the session group ID.

sendTextMessage(ctx, req)

Sends a text message without specifying a sessionID.

sendTextMessageWithSync(ctx, req)

Sends a message and waits for the response.

sendImageMessage(ctx, req)

Sends an image message.

sendFileMessage(ctx, req)

Sends a file message.

subscribeEvent(ctx, req, callback)

Subscribes to session events.

getSessionHistoryMessageList(ctx, req)

Gets message history.

Usage example

const sam = await client.buildSingleAgentManager({});

console.log('Agent:', sam.agent().name);

// Send a message directly without specifying a sessionID
const msg = await sam.sendTextMessage({}, { content: 'Hello' });
console.log('Sent successfully:', msg?.id);

4. SkillManager class

Skill manager. Provides skill category queries, installed skill queries, and the ability to enable/disable and install/uninstall skills.

4.1 Methods

Method

Description

listCategories(ctx)

Gets skill categories.

listInstalledSkills(ctx, req)

Lists skills installed on a specified desktop. Requires a desktopID. Optional parameters: categoryID (filter by category) and skillName (filter by skill name).

listAgentAuthedSkills(ctx, req)

Lists skills authorized for an agent. Requires a desktopID.

setSkillEnabled(ctx, req)

Enables or disables a skill. Waits for the operation to complete and returns the result.

entInstallSkills(ctx, req)

Installs skills. Waits for the operation to complete and returns the result.

entUninstallSkills(ctx, req)

Uninstalls skills. Waits for the operation to complete and returns the result.

4.2 Usage example

const skillMgr = await client.buildSkillManager({});

// Get skill categories
const categories = await skillMgr.listCategories({});
console.log('Categories:', categories.map(c => c.categoryName));

// Query installed skills
const installed = await skillMgr.listInstalledSkills({}, {
  desktopID: 'ecd-xxx',
});

// Enable a skill (automatically waits for the operation to complete)
const tasks = await skillMgr.setSkillEnabled({}, {
  desktopID: 'ecd-xxx',
  skillNames: ['agent-browser'],
  enabled: true,
});
for (const task of tasks) {
  console.log(`Task ${task.taskId}: ${task.operationStatus}`);
}

// Install a skill
const installTasks = await skillMgr.entInstallSkills({}, {
  desktopID: 'ecd-xxx',
  skillIds: ['skill-id-001'],
});

5. CreditManager class

Credit manager. Provides credit package queries and credit usage queries.

5.1 Methods

Method

Description

describeCreditPackageAgents(ctx, req?)

Lists agents bound to credit packages. Optional parameters: agentType (filter by agent type), agentIds (specify agent IDs), and fillAgent (whether to include detailed agent information). The response includes usedCredit, totalCredit, and expiredTime for each agent.

describeCreditUsageInfo(ctx, req?)

Queries credit usage information. Optional parameters: usageType (usage type), instanceIds (instance IDs), agentType (agent type), agentIds (agent IDs), and fillAgent (whether to include detailed agent information).

5.2 Usage example

const creditMgr = await client.buildCreditManager({});

// Query credit plans
const agents = await creditMgr.describeCreditPackageAgents({});
for (const agent of agents) {
  console.log(`Agent ${agent.agentId}: used ${agent.usedCredit}/${agent.totalCredit}, expires ${agent.expiredTime}`);
}

// Query credit usage
const usage = await creditMgr.describeCreditUsageInfo({}, {
  usageType: 'AGENT',
});
for (const item of usage.usageInfoList) {
  const data = item.usageInfo;
  console.log(`${item.usageInfoKey}: ${data.totalUsedCredit}/${data.totalCredit}`);
}

6. ModelManager class

Model configuration manager. Provides agent instance model configuration queries and session model settings.

6.1 Methods

Method

Description

getAgentInstanceModelConfig(ctx, req)

Gets the model configuration of an agent instance, including available model providers and LLMs.

setChannelGroupModel(ctx, req)

Sets the LLM model for a specific session.

6.2 getAgentInstanceModelConfig request parameters

Parameter

Type

Required

Description

agentInstanceId

string

Yes

Agent instance ID.

agentProvider

string

No

Agent type. Default value: OpenClaw.

agentPlatform

string

No

Agent platform. Valid values: ENTERPRISE, ENTERPRISE_JVS. Default value: ENTERPRISE.

channelSessionId

string

No

Session ID. Gets the model configuration for a specific session.

6.3 setChannelGroupModel request parameters

Parameter

Type

Required

Description

agentInstanceId

string

Yes

Agent instance ID.

groupId

string

Yes

Session group ID.

providerName

string

Yes

Model provider ID, for example, "bailian".

llmCode

string

Yes

Model ID, for example, "qwen3.5-plus".

6.4 Usage example

const modelMgr = await client.buildModelManager({});

// Query model configuration
const config = await modelMgr.getAgentInstanceModelConfig({}, {
  agentInstanceId: 'inst-xxx',
});

if (config) {
  console.log('Default model:', config.defaultModel);
  for (const provider of config.modelProviderList) {
    console.log(`Provider: ${provider.name}`);
    for (const llm of provider.llmInfoList) {
      console.log(`  - ${llm.name} (${llm.llmCode})`);
    }
  }
}

// Switch the session model
await modelMgr.setChannelGroupModel({}, {
  agentInstanceId: 'inst-xxx',
  groupId: 'grp-xxx',
  providerName: 'bailian',
  llmCode: 'qwen3.5-plus',
});

7. AspManager class

Streaming session manager. Manages the lifecycle of streaming sessions for cloud desktops or cloud applications. Browser environments only.

7.1 Methods

Method

Description

startAspStream(ctx, req)

Starts a streaming session.

stopAspStream()

Stops a streaming session and releases resources.

getAspStreamSession()

Gets the current streaming session information.

7.2 startAspStream request parameters

Parameter

Type

Required

Description

resourceId

string

Yes

Resource ID.

containerElementId

string

Conditional

Container element ID. Required in inline mode.

streamType

AspStreamType

No

Streaming type. Valid values: desktop (cloud desktop), application (cloud application). Default value: desktop.

regionId

string

No

Region ID. Default value: cn-shanghai.

openType

string

No

Open mode. Valid values: inline (embedded), newTab (new tab). Default value: inline.

containerUrl

string

No

Streaming container page URL. Use to specify a custom streaming page URL.

width

string

No

Width. Default value: '100%'.

height

string

No

Height. Default value: '100%'.

7.3 AspStreamStatus enum

Streaming session status enum. You can get the status through getAspStreamSession().status.

Value

Description

creating

Creating.

connecting

Connecting.

connected

Connected.

disconnected

Disconnected.

error

Error.

7.4 Example

const aspMgr = await client.buildAspManager({});

// Start cloud desktop streaming (inline mode)
await aspMgr.startAspStream({}, {
  resourceId: 'desktop-resource-id',
  streamType: 'desktop',
  containerElementId: 'stream-container',
  openType: 'inline',
  width: '100%',
  height: '100%',
});

// Query the streaming session status
const session = aspMgr.getAspStreamSession();
console.log('Status:', session?.status);

// Stop streaming
await aspMgr.stopAspStream();

8. Event types

The SDK supports the following event types, which you can use for event filtering with the subscribeEvent method.

Event type

Description

Message

A complete message is received.

StreamMessage

A streaming message fragment is received.

SessionStart

A session has started.

SessionFinish

A session has ended.

SessionFailed

A session has failed.

AgentStatus

An agent status change occurred.

SyncProgress

A sync progress update is available.

Connecting

A connection is being established.

Connected

A connection has been established.

ConnectFailed

A connection has failed.

Disconnect

A connection has been disconnected.

Error

An error has occurred.

Status

A general status change notification.

TokenExpired

The authentication token has expired.

KickedOffline

Kicked offline (another device signed in).

8.1 Global event subscriptions

You can subscribe to global events through client.subscribeEvent(). The following filter options are supported:

Filter option

Description

withEventTypes(...types)

Filter by event type.

withSessionIDs(...ids)

Filter by session ID.

withContentKeywords(...keywords)

Filter by message content keywords.

withSenderPattern(pattern)

Filter by sender pattern.

withTimeRange(start, end)

Filter events by time range.

withMetadataFilter(key, value)

Filter by metadata key-value pairs.

withCustomFilter(fn)

Custom filter function.

withAsyncDelivery(async)

Sets whether events are delivered asynchronously.

withCallback(callback)

Sets the event callback function.

withCallbackTimeout(ms)

Sets the callback timeout.

import { EventType, withEventTypes, withSessionIDs } from './wuying-sdk.mjs';

// Subscribe to all message events
const handle = client.subscribeEvent(
  (event) => { console.log('Message:', event.message?.content); },
  withEventTypes(EventType.Message, EventType.StreamMessage)
);

// Unsubscribe
handle.unsubscribe();

9. Async call mode

All manager methods use await to wait for a response by default. If you need async mode (the method returns null immediately and delivers results through a callback), use WithAsync.

import { WithAsync } from './wuying-sdk.mjs';

// Async mode: the method returns null immediately
const result = await agentManager.sendTextMessage(
  {},
  { sessionID: 'xxx', content: 'hello' },
  WithAsync((msg, err) => {
    if (err) console.error('Send failed:', err);
    else console.log('Message sent:', msg?.id);
  })
);
console.log(result); // null

10. Error handling

The SDK defines the following error types. All extend the SDKError base class.

Error class

Error code

Description

NetworkError

NETWORK_ERROR

Network error. Retryable.

TimeoutError

TIMEOUT

Request timeout. Retryable.

AuthError

AUTH_ERROR

Authentication error. Check your AuthCode.

PermissionError

PERMISSION_ERROR

Insufficient permissions.

BusinessError

BUSINESS_ERROR

Business logic error.

RateLimitError

RATE_LIMIT_ERROR

Rate limit exceeded. Retryable.

ServerError

SERVER_ERROR

Server error. Retryable.

APIError

API_ERROR

API call error. Contains the HTTP status code.

Use the isRetryable(error) function to check whether an error is retryable. NetworkError, TimeoutError, RateLimitError, and ServerError are all retryable errors.

import { AuthError, TimeoutError, NetworkError, isRetryable } from './wuying-sdk.mjs';

try {
  const agents = await agentMgr.listAgents({});
} catch (err) {
  if (err instanceof AuthError) {
    console.error('Authentication failed. Check the AuthCode.');
  } else if (err instanceof TimeoutError) {
    console.error('Request timed out');
  } else if (isRetryable(err)) {
    console.log('Retryable error. Consider retrying.');
  }
}

11. Base types

11.1 ExecutionContext

The first parameter of all manager methods is ExecutionContext, which passes execution context information.

Field

Type

Required

Description

signal

AbortSignal

No

Signal object for canceling requests.

traceId

string

No

Request trace ID for logging and debugging.

timeout

number

No

Request timeout in milliseconds.

11.2 Enum types

The SDK provides the following enum types:

Enum

Valid values

Description

MessageRole

user, assistant, system

Message role.

MessageType

text, image, file

Message content type.

AgentStatus

ready, building, error, unknown

Agent runtime status.

AgentOnlineStatus

online, offline

Agent online status.

SessionStatus

active, closed, expired

Session status.

AgentPlatform

ENTERPRISE, ENTERPRISE_JVS

Agent platform type.

11.3 Agent

An Agent object contains the following fields:

Field

Type

Description

id

string

Unique agent ID.

name

string

Agent name.

type

string

Agent type.

status

AgentStatus

Agent runtime status.

imId

string

IM identifier of the agent.

avatarUrl

string

Agent avatar URL.

description

string

Agent description.

runtimeId

string

Runtime instance ID.

runtimeType

string

Runtime type.

regionId

string

Region ID.

osType

string

OS type.

agentPlatform

string

Agent platform type. Valid values: ENTERPRISE, ENTERPRISE_JVS.

runtimeResourceInfo

object

Runtime resource information. Contains fields such as resourceId, resourceStatus, and resourceName. Populated only when returned by listAgents.

fotaUpdate

AgentFotaUpdate

FOTA upgrade information. Populated only when queryFotaUpdate is set to true in listAgents.

onlineStatus

AgentOnlineStatus

Agent online status.

11.4 Session

A Session object contains the following fields:

Field

Type

Description

id

string

Unique session ID.

agentId

string

ID of the associated agent.

userId

string

User ID of the session owner.

groupId

string

Session group ID (numeric format). Used for operations such as dismissSession.

conversationId

string

Conversation ID.

status

SessionStatus

Session status.

createdAt

Date

Session creation time.

11.5 Message

A Message object contains the following fields:

Field

Type

Description

id

string

Unique message ID.

sessionId

string

ID of the associated session.

role

MessageRole

Message role.

type

MessageType

Message type.

sender

string

Sender identifier.

timestamp

Date

Message timestamp.

content

string

Message text content.

textElem

TextElem

Text message element. Contains text content details.

streamTextElem

StreamTextElem

Streaming text message element. Contains streaming fragment content.

imageElem

ImageElem

Image message element.

fileElem

FileElem

File message element.

isFinal

boolean

Whether this is the final fragment of a streaming message.

roundID

string

Conversation round ID.

11.6 SyncMessageResponse

Return type of the sendTextMessageWithSync method. Contains the following fields:

Field

Type

Description

roundID

string

Conversation round ID.

messages

Message[]

List of messages returned synchronously.

11.7 Event

An Event object contains the following fields:

Field

Type

Description

type

EventType

Event type.

message

Message | null

Associated message object (populated for message-type events).

source

EventSource

Event source information.

timestamp

Date

Event timestamp.

sessionID

string

Associated session ID.

metadata

Record<string, string>

Event metadata.

12. Convenience methods

The SDK provides convenience methods that operate directly on Agent, Session, or Skill objects without manually passing ID parameters. These methods are syntactic sugar for the corresponding manager methods and automatically extract the object's ID for the call.

12.1 Agent convenience methods

Method

Description

agentListSessions(agent, ctx)

Lists sessions for the specified agent.

agentCreateSession(agent, ctx)

Creates a session for the specified agent.

agentListInstalledSkills(agent, ctx)

Lists installed skills for the specified agent.

12.2 Session convenience methods

Method

Description

sessionSendTextMessage(session, ctx, content)

Sends a text message (async, doesn't wait for a response).

sessionSendTextMessageSync(session, ctx, content, timeout?)

Sends a text message and waits synchronously for the complete response.

sessionSendImageMessage(session, ctx, imagePath)

Sends an image message.

sessionSendFileMessage(session, ctx, filePath)

Sends a file message.

sessionGetHistoryMessageList(session, ctx)

Gets the message history for the session.

sessionSubscribeEvent(session, ctx, callback)

Subscribes to events for the specified session.

12.3 Skill convenience methods

Method

Description

skillEnable(skill, ctx)

Enables the specified skill.

skillDisable(skill, ctx)

Disables the specified skill.

12.4 Example

import { agentListSessions, agentCreateSession, sessionSendTextMessage, sessionSendTextMessageSync, sessionSubscribeEvent, skillEnable } from './wuying-sdk.mjs';

// Agent convenience methods
const agent = agentList.agents[0];
const sessions = await agentListSessions(agent, {});
const newSession = await agentCreateSession(agent, {});

// Session convenience method: send a message and wait for the response
const response = await sessionSendTextMessageSync(newSession, {}, 'Hello, tell me about yourself');
console.log('Response:', response?.messages.map(m => m.content).join(''));

// Session convenience method: subscribe to events
const handle = sessionSubscribeEvent(newSession, {}, (event) => {
  console.log('Event received:', event.type, event.message?.content);
});

// Skill convenience methods
const skills = await agentListInstalledSkills(agent, {});
await skillEnable(skills[0], {});