Skip to main content
Version: v5.3

IafAISvc

Use the IafAISvc API to create and manage the AISvc service resources, such as agents, tools, teams and creating conversations.

createAgents​

Creates one or more Agent resources.

ParameterRequiredTypeDescription
agentsYesArray<Agent>Pass an array of Agent objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Agent>> - A promise with the created Agent objects.

Examples
const agents = [
{
_namespaces: ['building_1234'],
_name: 'HVAC Monitoring Agent',
_background: 'Monitors HVAC system performance and detects anomalies.',
_userType: 'hvac_monitor_agent',
_tools: ['temperature_sensor_tool', 'energy_usage_tool'],
// Note: persisted internally by AISvc as `agent.external_mcp_servers`.
_externalMcpServers: [
{
_userType: 'github_mcp',
_filter: { _names: ['search_repositories', 'list_issues'] }
}
],
_agentClass: 'HVACMonitoringAgent', // applicable only when Agent have custom source code
_config: {
_model: "gpt-4o",
_provider: "openai"
}
},
{
_namespaces: ['building_1234'],
_name: 'Lighting Optimization Agent',
_background: 'Optimizes lighting schedules based on occupancy and daylight levels.',
_userType: 'lighting_opt_agent',
_externalMcpServers: [
{ _userType: 'github_mcp' }
],
_config: {
_model: "gpt-4o",
_provider: "openai"
}
},
{
_name: 'File Helper Agent',
_description: 'Answers questions about files using MCP tools.',
_background: 'You are an assistant that can look up file information using the available tools.',
_userType: 'file_helper_agent',
_namespaces: ['building_1234'],
// `_provider` supports both `openai` and `anthropic`; use the LLM Models API to list a provider's models.
_config: { _model: 'gpt-4o', _provider: 'openai' },
// _userType of a PromptTemplate Resource; acts as agent instruction, parameterized at runtime
_promptTemplate: 'File_instruction_tmpl',
// `_tools` can mix regular tools (by `_userType`) and Twinit MCP tools (by `_name`) (no `_externalMcpServers` needed):
_tools: [
'GetFileUrlTool', // Regular system tool
'getFiles_IafFileSvc', // System MCP tool
'GetFileNameById' // Custom (user) MCP tool
]
},
];

IafAISvc.createAgents(agents, ctx, options);

createConversation​

Creates a new conversation or continues an existing one.Pass with and to attach supported images or PDFs. AISvc retains them for later turns and loads their content only when an agent selects them. To attach files that are not yet in File Service, use IafAISvc.createConversationWithFiles.

ParameterRequiredTypeDescription
requestYesConversationCreateRequestThe conversation create request object.
Optional has the shape
.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoConversationRequestOptionsJSON object for optional query parameters,
and for request headers under . Set there to choose the language
of the service-generated text this request produces — the progress captions the AI Service
emits and the message on an error it returns. Supported values are and ; any other
value falls back to . The agent's own answer follows its prompt and system message, not
this header.
Returns

Promise<Conversation> - A promise with the Conversation object.

Examples
//1. Create a new conversation with an initial message
const request = {
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'List all doors that are not compliant with Dutch standards.' }
};
const conversation = await IafAISvc.createConversation(request, ctx);

//2. Create a new conversation with continuation of an existing conversation
const request = {
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'Filter to show only entrance doors.' },
_id: '94a1eb2b-06bd-426e-a3ce-e7ab609ea231' // existing conversation id for continuation
};
const conversation = await IafAISvc.createConversation(request, ctx);

//3. Create a new conversation with MCP server
const request = {
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'Retrieve all entrance doors and compare their open/closed status with the outside temperature. Return the doors where the outside temperature is below 5°C and the door has remained open for more than 2 minutes.' },
_externalMcpAuthTokens: [{ _userType: 'openapi_weather', _token: 'a454abe5635ssw345s23' }]
};
const conversation = await IafAISvc.createConversation(request, ctx);

//4. Create a conversation with immutable File Service version attachments
const request = {
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'Summarize the attached inspection report and image.' },
_attachments: [
{
_fileId: '7b28c85a-fb75-4fc3-bc3b-bf52f7c6444e',
_fileVersionId: 'ef607614-9e45-48e2-bd72-e8a3fe31c132'
},
{
_fileId: '88dd95ec-f102-4b38-a946-6ff97564a184',
_fileVersionId: '965ab5f6-3b97-4595-a87b-235b23bb620e'
}
]
};
const conversation = await IafAISvc.createConversation(request, ctx);

//5. Ask for Japanese progress and error text
const conversation = await IafAISvc.createConversation(
request, ctx, { headers: { 'Accept-Language': 'ja' } }
);

createConversationWithFiles​

Creates a new conversation or continues an existing one with files attached directly.Each file is first stored in File Service with a resumable upload. Once every upload has finished, the stored files are added to as references and the request is sent with IafAISvc.createConversation. A file that fails to upload rejects the call and the conversation is not sent.Only images and PDFs are supported as attachments; the AI Service rejects other types. Uploaded files stay in File Service, tagged , and can be attached again on later turns by their and .

ParameterRequiredTypeDescription
requestYesConversationCreateRequestThe conversation create request object. Existing
references are kept, and the uploaded files are added after them.
filesYesArray<ConversationFile>Files to upload and attach.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoConversationRequestOptionsSame as for IafAISvc.createConversation.
uploadOptionsNoConversationFileUploadOptionsUpload target and progress callbacks.
Returns

Promise<Conversation> - A promise with the Conversation object.

Examples
// Browser: files picked in an <input type="file" multiple>
const conversation = await IafAISvc.createConversationWithFiles(
{
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'Summarize the attached inspection report and image.' }
},
Array.from(fileInput.files),
ctx,
undefined,
{
onProgress: ({ filename, percentage, totalBytesUploaded, totalBytes }) =>
console.log(filename, percentage + '%', 'overall', totalBytesUploaded, '/', totalBytes),
onFileComplete: ({ filename, _fileId, _fileVersionId }) => console.log('uploaded', filename, _fileId, _fileVersionId),
onComplete: (attachments) => console.log('all files uploaded, sending conversation', attachments)
}
);

// Node.js: a stream from disk, with an explicit name
const conversation = await IafAISvc.createConversationWithFiles(
request,
[{ file: fs.createReadStream('/tmp/report.pdf'), filename: 'inspection-report.pdf' }],
ctx
);

createExternalMcpServerConfigs​

Creates one or more External MCP Server Config resources.

ParameterRequiredTypeDescription
externalMcpServerConfigsYesArray<ExternalMcpServerConfig>Array of External MCP Server Config definitions.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints.
Returns

Promise<Page<ExternalMcpServerConfig>> - A promise with the created External MCP Server Config objects.

Examples
const configs = [
{
_namespaces: ['building_1234'],
_name: 'Open Weather MCP Server',
_userType: 'open_weather_mcp_server',
_connection: {
_url: 'https://mcp.open-mcp.org/api/server/open-weather@latest/mcp',
_headers: { Authorization: { type: 'secret', value: 'OPEN_WEATHER_API_KEY' } }
}
}
];
await IafAISvc.createExternalMcpServerConfigs(configs, ctx);

createKnowledgeBases​

Creates one or more KnowledgeBase resources in a single transaction.

ParameterRequiredTypeDescription
knowledgeBasesYesArray<KnowledgeBase>Array of KnowledgeBase objects to create. Pass a one-element array to create a single entry.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters (e.g., pagination or query hints).
Returns

Promise<Page<KnowledgeBase>> - A promise with the created KnowledgeBase objects. If any creation fails, nothing is persisted.

Examples
const knowledgeBases = [
{ _name: 'Warranty Docs', _fileId: '94a1eb2b-06bd-426e-a3ce-e7ab609ea231', _fileVersionId: '35a1ab2c-16bd-426e-b3ce-a7ab609ea482', _userType: 'warranty_documents', _namespaces: ['ws1'] },
{ _name: 'Training Material', _fileId: '14b1db2b-16cd-426e-b3ce-c3ab609ea912', _fileVersionId: '51b1db2b-26cd-426e-b3ce-c3ab609ea913', _userType: 'training_materials', _namespaces: ['ws1'] }
];
await IafAISvc.createKnowledgeBases(knowledgeBases, ctx);

createMcpToolFilters​

Creates one or more MCP Tool Filter resources.

ParameterRequiredTypeDescription
mcpToolFiltersYesArray<McpToolFilter>Array of MCP Tool Filter definitions that control tool visibility.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints.
Returns

Promise<Page<McpToolFilter>> - A promise with the created MCP Tool Filter objects.

Examples
const filters = [
{
_namespaces: ['building_1234'],
_name: 'search-by-name',
_description: 'Filters tools that support name based lookup',
_userType: 'search_tool_filter',
_criteria: {
_name: { $regex: '.*search.*' }
}
}
];
await IafAISvc.createMcpToolFilters(filters, ctx);

createMcpTools​

Creates one or more MCP Tool resources.

ParameterRequiredTypeDescription
mcpToolsYesArray<McpTool>Array of MCP Tool definitions that describe the MCP wrapper for an existing script.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters such as pagination hints..
Returns

Promise<Page<McpTool>> - A promise with the created MCP Tool objects.

Examples
const mcpTools = [
{
_namespaces: ['building_1234'],
_name: 'AssetLookupMcpTool',
_description: 'Wraps an existing script that searches for assets.',
_schema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Free-text string used to match asset names, tags, or metadata.' },
maxResults: { type: 'number', description: 'Optional maximum number of assets to return.' }
},
required: ['query']
},
_script: { _userType: 'asset_scripts', _scriptName: 'assetLookup' }
}
];
await IafAISvc.createMcpTools(mcpTools, ctx);

createPermissions​

Creates permissions for AISvc resources such as Agents, Tools, Teams, and Conversations.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> - A CreatePermissionsResponse object that contains the successful and failed permissions in separate arrays.

createPromptTemplates​

Creates one or more Prompt Template resources.

ParameterRequiredTypeDescription
promptTemplatesYesArray<PromptTemplate>Non-empty array of Prompt Templates to create.
ctxYesCtxContext containing auth token and namespaces (nsfilter).
optionsNoObjectOptional control options (if supported by platform helper utilities).
Returns

Promise<Page<PromptTemplate>> - Page of created Prompt Templates.

Examples
const ctx = {
_namespaces: ['building_1234'],
authToken: '<token>'
};

// Example A: without arguments
const createdA = await IafAISvc.createPromptTemplates(
[
{
_name: 'HelloPrompt',
_userType: 'hello_prompt',
_namespaces: ['building_1234'],
_template: 'Say hello to the user.'
}
],
ctx
);

// Example B: with arguments (one required)
const createdB = await IafAISvc.createPromptTemplates(
[
{
_name: 'GreetUser',
_userType: 'greet_user',
_description: 'Greets a user by name.',
_namespaces: ['building_1234'],
_template: 'Hello {{name}}, welcome to {{site}}.',
_arguments: [
{ _name: 'name', _description: 'User name', _required: true },
{ _name: 'site', _description: 'Site/building label', _required: false }
]
}
],
ctx
);

createTeam​

Creates a Team resource.A Team runs in supervisory mode when any team agent has a non-empty (then is ignored and supervisors route at runtime); otherwise it runs in static-flow mode driven by the graph.

ParameterRequiredTypeDescription
teamYesTeamPass a Team object you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional control parameters, such as pagination options.
Returns

Promise<Team> - A promise with the created Team object.

Examples
// Static-flow team: a fixed __start__ -> ... -> __end__ path.
const teamObj = {
"_name": "SP - Telemetry Fetcher Team - new",
"_agents": [
{ "_userType": "sp_telemetry_fetcher" },
{ "_userType": "sp_anamoly_pressure_checker" }
],
"_flow": [
{ "to": "sp_telemetry_fetcher", "from": "__start__" },
{ "to": "sp_anamoly_pressure_checker", "from": "sp_telemetry_fetcher" },
{ "to": "__end__", "from": "sp_anamoly_pressure_checker" }
],
"_namespaces": [
"Amoghtestworkspace_m8NrvPU3"
]
}
``````javascript
// Supervisory team (co-supervisor chain): each agent with a `_subAgents` list is a
// supervisor; `_order` sets the chain position (first is the entry point) and the
// optional `_onfailure` names a fallback agent. `_flow` is empty in this mode.
const supervisoryTeamObj = {
"_name": "Platform Co-Supervisor Team",
"_agents": [
{
"_userType": "content_supervisor",
"_order": 1,
"_subAgents": [
{ "_userType": "file_specialist" },
{ "_userType": "model_specialist" }
]
},
{
"_userType": "operations_supervisor",
"_order": 2,
"_subAgents": [
{ "_userType": "telemetry_specialist" },
{ "_userType": "access_specialist" }
]
}
],
"_flow": [],
"_namespaces": [
"Amoghtestworkspace_m8NrvPU3"
]
}

createTools​

Creates one or more Tool resources.

ParameterRequiredTypeDescription
toolsYesArray<Tool>Pass an array of Tool objects you define.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectPass a JSON object for optional query parameters.
Returns

Promise<Page<Tool>> - A promise with the created Tool objects.

Examples
const tools = [
{
_namespaces: ['building_1234'],
_name: 'Temperature Sensor Tool',
_description: 'Provides real-time temperature readings.',
_userType: 'temperature_sensor_tool',
_toolClass: 'TemperatureSensorTool',
},
{
_namespaces: ['building_1234'],
_name: 'Energy Usage Tool',
_description: 'Calculates energy consumption patterns.',
_userType: 'energy_usage_tool',
},
];

IafAISvc.createTools(tools, ctx, options);

deleteAgent​

Deletes an Agent resource .

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

deleteAllConversations​

Permanently deletes every user's Conversations in one namespace, together with all their turns, attachment references, token usage and traces. The delete is irreversible, and runs as a single transaction: either every conversation in the namespace is deleted, or none is.Allowed for a user with the Platform Manager role, or for a user holding DELETE on all conversations in the namespace ( or ). DELETE on individual conversations is not enough, and the request is rejected with a 403.Because there is no undo, the caller has to confirm the delete explicitly by passing , and the context must name exactly one namespace. The request is rejected with a 400 otherwise.

ParameterRequiredTypeDescription
criteriaYesConversationDeleteAllCriteriaPass to confirm deleting every conversation in the namespace.
ctxYesCtxContext with exactly one namespace in , and authentication token information.
Returns

Promise<ConversationDeleteAllResult> - A promise with the number of conversations deleted.

Examples
const { _deleted } = await IafAISvc.deleteAllConversations({ _scope: 'all' }, { ...ctx, _namespaces: ['building_1234'] });

deleteConversation​

Permanently deletes a Conversation together with its turns, attachment references, token usage and traces. The delete is irreversible: deleted data cannot be recovered and the conversation cannot be resumed. Files in the File Service that were attached to it are kept.A user with the Platform Manager role can delete any user's conversation in the namespace. Everyone else needs DELETE permission on the conversation, or the request is rejected with a 403. A conversation that does not exist in the namespace is a 404.

ParameterRequiredTypeDescription
idYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteConversation('8f2dfd89-94f4-4fea-a1a1-d1c6dfdb90c3', ctx);

deleteExternalMcpServerConfig​

Deletes an External MCP Server Config resource.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteExternalMcpServerConfig(configId, ctx);

deleteKnowledgeBase​

Deletes a KnowledgeBase resource.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

deleteMcpTool​

Deletes an MCP Tool resource by id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
const toolId = 'd8a53325-dbb5-4a2d-a655-ef5fa74591d3';
await IafAISvc.deleteMcpTool(toolId, ctx);

deleteMcpToolFilter​

Deletes an MCP Tool Filter resource.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteMcpToolFilter(filterId, ctx);

deletePermission​

Deletes a permission when you pass its id.

ParameterRequiredTypeDescription
idYesStringThe Permission object's id.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<String> - {ok:204} response.

deletePromptTemplate​

Deletes a Prompt Template by id.

ParameterRequiredTypeDescription
idYesstringPrompt Template UUID.
ctxYesCtxContext containing auth token and namespaces (nsfilter).
Returns

Promise<void> - Resolves on 204 No Content.

Examples
await IafAISvc.deletePromptTemplate('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

deleteTeam​

Deletes a Team resource.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

deleteTool​

Deletes a Tool resource.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<String> - {ok:204} response.

Examples
await IafAISvc.deleteTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getAgent​

Gets an Agent resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the Agent object.

Examples
const agent = await IafAISvc.getAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', ctx);

getAgents​

Gets Agent resource objects that match your criteria in the namespace. System agents are also included in the results.

ParameterRequiredTypeDescription
criteriaNoAgentCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsPass a JSON object for optional control parameters, such as pagination and sorting options.
Returns

Promise<Page<Agent>> - A promise with a page that contains the Agent objects.

Examples
// Get all agents
const allAgents = await IafAISvc.getAgents({}, ctx);

// Get agents by userType
const hvacAgents = await IafAISvc.getAgents({ _userType: 'hvac_monitor_agent' }, ctx, { _pageSize: 50 });

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getAgents({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getAgentSourceCode​

Retrieves source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Agent's SourceCode.

Examples
const agentCode = await IafAISvc.getAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', ctx);

getConversation​

Gets a Conversation resource by its id.

ParameterRequiredTypeDescription
idYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoConversationOptionsJSON object for optional query parameters.
Returns

Promise<Conversation> - A promise with the Conversation object.

getConversations​

Gets Conversation objects in the namespace, newest first by default. Pass / in to order by creation or last-update time instead.By default only the conversations the requesting user created are returned. Pass to return every user's conversations in the namespace; that requires READ on all conversations ( or ), and a caller who can read only individually shared conversations is rejected with a 403.

ParameterRequiredTypeDescription
criteriaNoConversationCriteriaOptional filters. Pass {} or undefined for the requesting user's own conversations.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsPass a JSON object for optional control parameters, such as pagination and sorting options.
Returns

Promise<Page<Conversation>> - A promise with a page that contains the Conversation objects.

Examples
// Get the requesting user's conversations
const conversations = await IafAISvc.getConversations({}, ctx, { _pageSize: 50 });
``````javascript
// Get every user's conversations in the namespace (requires READ on all conversations)
const allConversations = await IafAISvc.getConversations({ allUsers: true }, ctx, { _pageSize: 50 });
``````javascript
// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getConversations({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getConversationTokenUsage​

Gets a Conversation's token total together with the breakdown of what incurred it.The breakdown is one entry per source and served model, summed across every turn in the conversation, heaviest first — which agent, on which model, over how many AI calls. The entries sum to , so a caller can see the parts account for the whole.A conversation that predates token tracking reports zeros and an empty list.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<TokenUsageBreakdown> - A promise with the conversation's token usage.

Examples
// What did this conversation cost, and which agent drove it?
const usage = await IafAISvc.getConversationTokenUsage(conversationId, ctx);
console.log(usage._usage._total, usage._sources[0]._displayName, usage._sources[0]._calls);

getConversationTrace​

Gets a Conversation's archived execution trace.The trace records what the team actually did to produce each answer: the prior turns and knowledge-base text put in front of the model, which agents ran and what each produced, every supervisor routing decision, and every tool call with its arguments and its result. It is what answers "why did the AI say that" after the fact, when reproducing the conversation would give a different answer because the data, the knowledge base and the model's sampling have moved on.Captured for every conversation regardless of how it was run. Unlike the events IafAISvc.streamConversation delivers, which exist only while a streaming conversation runs, the trace is stored until the service's retention period purges it. A conversation that predates the feature, or whose trace has aged out, returns an empty page rather than an error.Events are returned in execution order and is never truncated: a tool result that was capped on the stream is returned here in full. Because of that, pages are capped at 200 events, and a above the cap is rejected rather than silently reduced.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
criteriaNoTraceCriteriaOptional filters. Pass or undefined for every event.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as
pagination options. must be between 1 and 200.
Returns

Promise<Page<TraceEvent>> - A promise with a page that contains the TraceEvent objects.

Examples
// The whole trace for a conversation
const trace = await IafAISvc.getConversationTrace(conversationId, {}, ctx, { _pageSize: 50 });
trace._list.forEach(e => console.log(e._sequence, e._eventType, e._agentName));
``````javascript
// Just the tool activity. An array is sent as a repeated query parameter
// (?_eventType=tool_invoked&_eventType=tool_result), which is the form the service accepts -
// a comma-joined value is rejected with a 400 naming it.
const toolCalls = await IafAISvc.getConversationTrace(
conversationId,
{ _eventType: ['tool_invoked', 'tool_result'] },
ctx
);
``````javascript
// Narrowed to one turn, equivalent to calling IafAISvc.getTurnTrace
const turnTrace = await IafAISvc.getConversationTrace(conversationId, { _turnId: turnId }, ctx);

getConversationTurn​

Gets a single turn of a Conversation.The turn is looked up within the conversation you pass, so a belonging to a different conversation is reported as not found rather than returned.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
turnIdYesStringPass the Turn's id, as returned by IafAISvc.getConversationTurns.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Turn> - A promise with the Turn object.

Examples
const turn = await IafAISvc.getConversationTurn(conversationId, turnId, ctx);

getConversationTurns​

Gets the turns of a Conversation, oldest first.A turn is one exchange: the prompt a user sent together with the answer the team produced for it. Unlike the option on IafAISvc.getConversation, each turn carries its own , which IafAISvc.getConversationTurn and IafAISvc.getTurnTokenUsage require.Turns do not include the conversation summary or the embedding vector.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as
pagination options.
Returns

Promise<Page<Turn>> - A promise with a page that contains the Turn objects.

Examples
// First page of turns, with the token cost of each
const turns = await IafAISvc.getConversationTurns(conversationId, ctx, { _pageSize: 25 });
turns._list.forEach(t => console.log(t._id, t._usage._total));

getExternalMcpServerConfig​

Gets an External MCP Server Config resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<ExternalMcpServerConfig> - A promise with the External MCP Server Config object.

Examples
const config = await IafAISvc.getExternalMcpServerConfig('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getExternalMcpServerConfigs​

Gets External MCP Server Config resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoExternalMcpServerConfigCriteriaFilter parameters such as _name, _userType or query. Pass {} to list every config in the namespaces in ctx.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsOptional control parameters, such as pagination and sorting options.
Returns

Promise<Page<ExternalMcpServerConfig>> - A promise with a page that contains the External MCP Server Config objects.

Examples
// Every config in the namespaces in ctx, 25 per page
const page = await IafAISvc.getExternalMcpServerConfigs({}, ctx, { _pageSize: 25 });

// By exact name, or any of several names
const weather = await IafAISvc.getExternalMcpServerConfigs({ _name: 'weather_mcp' }, ctx);
const several = await IafAISvc.getExternalMcpServerConfigs({ _name: ['weather_mcp', 'traffic_mcp'] }, ctx);

// By user type, narrowed by a partial match on name or description
const forecasts = await IafAISvc.getExternalMcpServerConfigs({ _userType: 'openapi_weather', query: 'forecast' }, ctx);

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getExternalMcpServerConfigs({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getKnowledgeBase​

Gets a KnowledgeBase resource by its id.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the KnowledgeBase object.

Examples
const kb = await IafAISvc.getKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', ctx);

getKnowledgeBases​

Gets KnowledgeBase resources matching criteria.

ParameterRequiredTypeDescription
criteriaNoKnowledgeBaseCriteriaFilter parameters (e.g., _userType, _vectorizedStatus).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsOptional control parameters like pagination and sorting options.
Returns

Promise<Page<KnowledgeBase>> - A promise with a page of KnowledgeBase objects.

Examples
const page = await IafAISvc.getKnowledgeBases({ _userType: 'warranty_documents' }, ctx, { _pageSize: 50 });

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getKnowledgeBases({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getLlmModels​

Gets the available LLM models for a provider.Note: AISvc requires the query param for namespace-scoped requests.

ParameterRequiredTypeDescription
criteriaYesLlmModelCriteriaFilter parameters, such as the LLM provider and namespace filter.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters.
Returns

Promise<Page<LlmModel>> - A promise with a page that contains the provider model list.

Examples
// OpenAI models
const openaiModels = await IafAISvc.getLlmModels({ _provider: 'openai', nsfilter: 'building_1234' }, ctx);

// Anthropic models
const anthropicModels = await IafAISvc.getLlmModels({ _provider: 'anthropic', nsfilter: 'building_1234' }, ctx);

getLlmProviders​

Gets the available LLM providers.By default this returns a plain list of provider identifiers (e.g. ). Pass as the criteria to instead receive detailed provider objects that also include the credentials-vault secret name each provider's API key must be stored under: .

ParameterRequiredTypeDescription
criteriaNoLLMProviderCriteriaOptional query parameters, such as .
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsOptional control parameters.
Returns

Promise<(Array<String> | {```_providers```})> - By default, an array of provider names. With , an object with a array of LLMProvider entries.

Examples
// Default — provider names
const providers = await IafAISvc.getLlmProviders({}, ctx);

// Detailed — includes the secret name for each provider
const detailed = await IafAISvc.getLlmProviders({ detailed: true }, ctx);

getMcpTool​

Gets an MCP Tool resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpTool> - A promise with the MCP Tool object.

Examples
const tool = await IafAISvc.getMcpTool('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getMcpToolFilter​

Gets an MCP Tool Filter resource object by its id.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpToolFilter> - A promise with the MCP Tool Filter object.

Examples
const filter = await IafAISvc.getMcpToolFilter('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getMcpToolFilters​

Gets MCP Tool Filter resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoGetMcpToolFilterCriteriaFilter parameters such as _name, _userType, or query.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsOptional control parameters, such as pagination and sorting options.
Returns

Promise<Page<McpToolFilter>> - A promise with a page that contains the MCP Tool Filter objects.

Examples
const page = await IafAISvc.getMcpToolFilters({ _userType: 'search_tool_filter' }, ctx, { _pageSize: 25 });

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getMcpToolFilters({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getMcpTools​

Gets MCP Tool resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoMcpToolCriteriaQuery filters. Supported keys: _name, _type, _toolConfig._serviceName, _script._userType, _script._scriptName, filter, query. When filter is provided, AISvc ignores other criteria fields.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsOptional control parameters, such as pagination and sorting options.
Returns

Promise<Page<McpTool>> - A promise with a page that contains the MCP Tool objects.

Examples
const page = await IafAISvc.getMcpTools({ _type: 'user_mcp_tool' }, ctx, { _pageSize: 25 });
// Get MCP Tools by script userType
const userTypeMatch = await IafAISvc.getMcpTools({ '_script._userType': 'asset_scripts' }, ctx);

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getMcpTools({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getPermissions​

Gets permissions for AISvc resources.

ParameterRequiredTypeDescription
criteriaYesPermissionCriteriaPass a PermissionCriteria object with the properties and values to filter your search.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<Page<Permission>> - A Page object with the Permission objects you want.

getPromptTemplate​

Gets a Prompt Template by id.

ParameterRequiredTypeDescription
idYesstringPrompt Template UUID.
ctxYesCtxContext containing auth token and namespaces (nsfilter).
Returns

Promise<PromptTemplate> - Prompt Template object.

Examples
const template = await IafAISvc.getPromptTemplate('d8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getPromptTemplates​

Gets Prompt Template resource objects that match criteria.

ParameterRequiredTypeDescription
criteriaNoPromptTemplateCriteriaOptional query filters: _name, _userType, query.
ctxYesCtxContext containing auth token and namespaces (nsfilter).
optionsNoObjectOptional control options (e.g., _pageSize, _offset).
Returns

Promise<Page<PromptTemplate>> - Page of Prompt Templates.

Examples
const page = await IafAISvc.getPromptTemplates(
{ _userType: 'greet_user', query: 'welcome' },
ctx,
{ _pageSize: 25, _offset: 0 }
);

getTeam​

Gets a Team resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the Team object.

getTeams​

Gets Team resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoTeamCriteriaPass a JSON object with filter parameters, such as "_name" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsControl parameters, such as pagination and sorting options.
Returns

Promise<Page<Team>> - A promise with a page that contains the Team objects.

Examples
// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getTeams({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getTool​

Gets a Tool resource object by its id.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the Tool object.

Examples
const tool = await IafAISvc.getTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', ctx);

getTools​

Gets Tool resource objects that match your criteria.

ParameterRequiredTypeDescription
criteriaNoToolCriteriaPass a JSON object with filter parameters, such as "_userType" or "query".
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcListOptionsPass a JSON object for optional control parameters, such as pagination and sorting options.
Returns

Promise<Page<Tool>> - A promise with a page that contains the Tool objects.

Examples
// Get all tools
const allTools = await IafAISvc.getTools({}, ctx);

// Get tools by userType
const sensorTools = await IafAISvc.getTools({ _userType: 'temperature_sensor_tool' }, ctx, { _pageSize: 50 });

// Most recently updated first; use _sortBy: 'createdAt' to sort by creation time
const recent = await IafAISvc.getTools({}, ctx, { _sortBy: 'updatedAt', _sortOrder: 'desc', _pageSize: 25 });

getToolSourceCode​

Retrieves source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<SourceCode> - A Promise resolving to the Tool's SourceCode.

Examples
const toolCode = await IafAISvc.getToolSourceCode('tool-id-1234', ctx);

getTurnTokenUsage​

Gets a single turn's token total together with the breakdown of what incurred it.The same shape as IafAISvc.getConversationTokenUsage, narrowed to one turn. This is where a single expensive turn becomes visible — typically one agent with a high count from looping over a tool.A turn's summarisation cost is added shortly after the answer is returned, so a turn read immediately after a conversation request can report a slightly lower total than the same turn read a moment later.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
turnIdYesStringPass the Turn's id, as returned by IafAISvc.getConversationTurns.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<TokenUsageBreakdown> - A promise with the turn's token usage.

Examples
const usage = await IafAISvc.getTurnTokenUsage(conversationId, turnId, ctx);

getTurnTrace​

Gets a single turn's archived execution trace: the same record as IafAISvc.getConversationTrace, narrowed to one turn, and the usual starting point when one answer is being investigated. Each event's _sequence starts from 1 for the turn. The turn id comes back on the conversation request as _turnId, so a caller that has just run a turn does not need to list the conversation's turns first. The turn is looked up within the conversation you pass, so a turn id that belongs to a different conversation is reported as not found.

ParameterRequiredTypeDescription
conversationIdYesStringPass the Conversation's id.
turnIdYesStringPass the Turn's id, as returned on the conversation request or by IafAISvc.getConversationTurns.
criteriaNoTraceCriteriaOptional filters. The _turnId filter is ignored here, because the turn comes from turnId.
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoAisvcOptionsPass a JSON object for optional control parameters, such as pagination options. _pageSize must be between 1 and 200.
Returns

Promise<Page<TraceEvent>> - A promise with a page that contains the TraceEvent objects.

Examples
const trace = await IafAISvc.getTurnTrace(conversationId, turnId, {}, ctx);
``````javascript
// What did each agent produce on this turn?
const messages = await IafAISvc.getTurnTrace(
conversationId, turnId, { _eventType: 'agent_message' }, ctx
);
messages._list.forEach(e => console.log(e._payload.agentName, e._payload.content));

streamConversation​

Streams a new or resumed conversation over Server-Sent Events.Unlike IafAISvc.createConversation, which resolves once the full answer is ready, this method opens a long-lived SSE connection to the AI Service and calls onEvent for every event the server sends, so progress, tool calls and the answer itself can be shown as they happen.Each event is a ConversationStreamEvent: its type is the SSE event name and its payload the parsed JSON body. See ConversationStreamEvent for every event type, the order they arrive in, and the payload each one carries, including the attachment events.

ParameterRequiredTypeDescription
requestYesConversationCreateRequestThe same request body as IafAISvc.createConversation: the team id, the input message, an optional conversation id to continue, optional external MCP auth tokens and optional File Service attachments.
onEventYesConversationStreamEventHandlerCalled for every server event. A throw inside it is logged and ignored, so the stream keeps running.
ctxNoCtxContext, such as namespaces and authentication token.
optionsNoConversationRequestOptionsOptional query parameters, and request headers under headers. Set Accept-Language to 'en' or 'ja' to choose the language of the progress and error text on this stream. Accept, Content-Type and Cache-Control are fixed by the SSE transport and cannot be overridden.
Returns

ConversationStreamHandle - A handle to abort the stream or wait for it to end.

Examples
// 1. Basic streaming — log progress and render tokens as they arrive.
const handle = IafAISvc.streamConversation(
{
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'List all doors that are not compliant with Dutch standards. Then summarize the attached inspection report.' },
_attachments: [{
_fileId: '7b28c85a-fb75-4fc3-bc3b-bf52f7c6444e',
_fileVersionId: 'ef607614-9e45-48e2-bd72-e8a3fe31c132'
}]
},
(event) => {
switch (event.type) {
case 'conversation': console.log('conversation id', event.payload.id); break;
case 'process-status': console.log('status:', event.payload.description); break;
case 'agent-invoked': console.log('agent invoked:', event.payload.agentName); break;
case 'tool-invoked': console.log('tool called:', event.payload.toolName, event.payload.input); break;
case 'tool-result': console.log('tool result:', event.payload.toolName, event.payload.truncated ? '[truncated]' : event.payload.output); break;
case 'attachment-status': console.log('attachment:', event.payload.name, event.payload.status); break;
case 'agent-message': process.stdout.write(event.payload.delta); break;
case 'token-usage': console.log('\ntokens:', event.payload._message._total); break;
case 'complete': console.log('\nDone. Conversation:', event.payload._id, 'turn:', event.payload._turnId); break;
case 'error': console.error('stream error:', event.payload); break;
}
},
ctx
);

// Wait until the stream finishes (or fails).
await handle.done;

// 2. Aborting mid-stream (e.g. user navigates away).
setTimeout(() => handle.abort(), 5000);

// 3. Continuing an existing conversation.
IafAISvc.streamConversation(
{ _teamId, _id: existingConversationId, _input: { message: 'Filter to entrance doors.' } },
(event) => { if (event.type === 'agent-message') buffer += event.payload.delta; },
ctx
);

streamConversationWithFiles​

Streams a new or resumed conversation over Server-Sent Events with files attached directly.Each file is first stored in File Service with a resumable upload. Once every upload has finished, the stored files are added to as references and the conversation is streamed with IafAISvc.streamConversation, so receives the same events. Upload progress is reported through .A file that fails to upload is reported as an event, rejects, and the conversation is not sent. Only images and PDFs are supported as attachments; the AI Service rejects other types.

ParameterRequiredTypeDescription
requestYesConversationCreateRequestSame body shape as IafAISvc.streamConversation.
Existing references are kept, and the uploaded files are added after them.
filesYesArray<ConversationFile>Files to upload and attach.
onEventYesConversationStreamEventHandlerCalled for every server event, as for IafAISvc.streamConversation. A failed upload is reported as an 'error' event.
ctxNoCtxContext, such as namespaces and authentication token.
optionsNoConversationRequestOptionsSame as for IafAISvc.streamConversation.
uploadOptionsNoConversationFileUploadOptionsUpload target and progress callbacks.
Returns

ConversationStreamHandle - A handle to abort the uploads or the stream, or wait for it to end.

Examples
const handle = IafAISvc.streamConversationWithFiles(
{
_teamId: 'f73d1653-bf1d-4f00-ad58-543ac48f80a3',
_input: { message: 'What does the attached floor plan show?' }
},
Array.from(fileInput.files),
(event) => {
switch (event.type) {
case 'agent-message': render(event.payload.delta); break;
case 'complete': console.log('Done. Conversation:', event.payload._id); break;
case 'error': console.error('error:', event.payload); break;
}
},
ctx,
undefined,
{
onProgress: ({ totalBytesUploaded, totalBytes }) => setUploadProgress(totalBytesUploaded / totalBytes),
onComplete: () => setUploadProgress(1)
}
);

await handle.done;

updateAgent​

Updates an existing Agent resource. Editable fields: _name, _background, _userType, _tools, _externalMcpServers, _agentClass, _promptTemplate.

ParameterRequiredTypeDescription
idYesStringPass the Agent's id.
agentYesAgentPass an Agent object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Agent> - A promise with the updated Agent object.

Examples
const updates = {
_name: 'Updated Agent Name',
_background: 'Updated background context.',
// `_tools` can mix regular tools (by `_userType`) and Twinit MCP tools (by `_name`) (no `_externalMcpServers` needed):
_tools: ['new_tool_type', 'getFiles_IafFileSvc'],
// Note: persisted internally by AISvc as `agent.external_mcp_servers`.
_externalMcpServers: [
{ _userType: 'github_mcp', _filter: { _names: ['search_repositories'] } }
],
// _userType of a PromptTemplate Resource; acts as agent instruction, parameterized at runtime
_promptTemplate: 'platform_resource_universal_tmpl',
_config: {
_model: "gpt-4o",
_provider: "openai"
}
};
const updatedAgent = await IafAISvc.updateAgent('e8a53325-fbb5-4a2d-a955-ef5fa74591df', updates, ctx);

updateExternalMcpServerConfig​

Updates an existing External MCP Server Config resource.

ParameterRequiredTypeDescription
idYesStringThe External MCP Server Config id.
externalMcpServerConfigYesExternalMcpServerConfigExternal MCP Server Config object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<ExternalMcpServerConfig> - A promise with the updated External MCP Server Config object.

Examples
const updated = await IafAISvc.updateExternalMcpServerConfig(configId, {
_namespaces: ['building_1234'],
_name: 'Open Weather MCP Server Updated',
_userType: 'open_weather_mcp_server',
_connection: {
_url: 'https://mcp.open-mcp.org/api/server/open-weather@latest/mcp',
_headers: { Authorization: { type: 'secret', value: 'OPEN_WEATHER_API_KEY' } }
}
}, ctx);

updateKnowledgeBase​

Updates an existing KnowledgeBase resource. Editable fields: _name, _userType.

ParameterRequiredTypeDescription
idYesStringThe KnowledgeBase id.
knowledgeBaseYesKnowledgeBaseKnowledgeBase object with updated properties.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<KnowledgeBase> - A promise with the updated KnowledgeBase object.

Examples
const updates = { _name: 'Updated Name',_fileId: '15a1ac2b-96ba-626e-b3ce-e7ab609ea612', _fileVersionId: '55a1bc2a-06bb-923e-a3cd-a7ab609ea609'};
await IafAISvc.updateKnowledgeBase('94a1eb2b-06bd-426e-a3ce-e7ab609ea231', updates, ctx);

updateMcpTool​

Updates an existing user MCP Tool resource.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool's id.
mcpToolYesMcpToolMCP Tool object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpTool> - A promise with the updated MCP Tool object.

Examples
const toolId = 'd8a53325-dbb5-4a2d-a655-ef5fa74591d3';
const updatedMcpPlayoad={
_namespaces: ['building_1234'],
_name: 'AssetLookupMcpTool_Updated',
_description: 'Searches assets by tag',
_schema: {
type: 'object',
properties: {
query: { type: 'string', description: 'Free-text string used to match asset names, tags, or metadata.' },
maxResults: { type: 'number', description: 'Optional maximum number of assets to return.' }
},
required: ['query']
},
_script: { _userType: 'asset_scripts', _scriptName: 'assetLookup' }
}
const updatedTool = await IafAISvc.updateMcpTool(toolId,updatedMcpPlayoad, ctx);

updateMcpToolFilter​

Updates an existing MCP Tool Filter resource. Editable fields: _name, _description, _namespaces, _userType, _criteria.

ParameterRequiredTypeDescription
idYesStringThe MCP Tool Filter id.
mcpToolFilterYesMcpToolFilterMCP Tool Filter object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<McpToolFilter> - A promise with the updated MCP Tool Filter object.

Examples
const updated = await IafAISvc.updateMcpToolFilter(filterId, {
_description: 'Updated description',
_criteria: { _serviceName: { $in: ['IafItemSvc'] } }
}, ctx);

updatePermissions​

Updates permissions for AISvc resources. If a permission you pass doesn't exist, the method creates the permission.

ParameterRequiredTypeDescription
permissionsYesArray<Permission>Pass an array of Permission objects.
ctxNoCtxContext, such as authorization token requirements, namespaces, or session storage.
Returns

Promise<CreatePermissionsResponse> - A CreatePermissionsResponse object that contains the successful and failed permissions in separate arrays.

updatePromptTemplate​

Updates an existing Prompt Template by id.

ParameterRequiredTypeDescription
idYesstringPrompt Template UUID.
promptTemplateYesPromptTemplateFull update payload (required fields must be provided).
ctxYesCtxContext containing auth token and namespaces (nsfilter).
Returns

Promise<PromptTemplate> - Updated Prompt Template object.

Examples
const id = 'd8a53325-dbb5-4a2d-a655-ef5fa74591d3';
const updatePayload = {
_name: 'GreetUser',
_userType: 'greet_user',
_description: 'Updated description',
_namespaces: ['building_1234'],
_template: 'Hello {{name}}, welcome to {{site}}.',
_arguments: [
{ _name: 'name', _required: true },
{ _name: 'site', _required: false }
]
};
const updated = await IafAISvc.updatePromptTemplate(id, updatePayload, ctx);

updateTeam​

Updates an existing Team resource. Editable fields: _name, _agents, _flow.

ParameterRequiredTypeDescription
idYesStringPass the Team's id.
teamYesObjectPass a Team object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Team> - A promise with the updated Team object.

updateTool​

Updates an existing Tool resource. Editable fields: _name, _description, _userType, _toolClass.

ParameterRequiredTypeDescription
idYesStringPass the Tool's id.
toolYesToolPass a Tool object with the properties you want to update.
ctxNoCtxContext, such as namespaces and authentication token information.
Returns

Promise<Tool> - A promise with the updated Tool object.

Examples
const updates = {
_description: 'Updated description.',
_toolClass: 'AdvancedEnergyTool',
};
const updatedTool = await IafAISvc.updateTool('a8a53325-dbb5-4a2d-a655-ef5fa74591d3', updates, ctx);

uploadAgentSourceCode​

Uploads source code for an Agent resource.

ParameterRequiredTypeDescription
agentIdYesStringThe Agent's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional upload parameters. Pass an object with a filename field to override the uploaded file name when sourceCode._file is provided.
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as string
const sourceCode = { "_content": "import { Agent } from '@dtplatform/agent-core';\nimport { IafItemSvc } from '@dtplatform/platform-api';\n\ninterface ChillerRequest {\n chillerId: string;\n capacityKw: number;\n metric: string; // e.g. \"chiller_load_kw\"\n thresholdPct: number; // e.g. 0.9 for 90%\n lookbackDays?: number;\n}\n\ntype Reading = {\n _id: string;\n _ts: string; // timestamp in UTC\n chiller_load_kw: number;\n chiller_load_pct: number;\n};\n\ntype Data = {\n _list: Reading[];\n};\n\nexport default class ChillerForecastAgent extends Agent {\n requestContext: any = {}\n constructor(options: any, requestContext: any) {\n super(options);\n this.requestContext = requestContext;\n }\n\n async processRequest(\n type: string,\n state?: any,\n prompt?: string,\n tools?: any[],\n userId?: string,\n sessionId?: string,\n chatHistory?: [],\n additionalParams?: Record<string, string>,\n ): Promise<any> {\n\n // ------------------------------\n // 1. Interpret prompt (simple parsing via LLM)\n // ------------------------------\n const llmRes: any = await this.simpleCall(`Extract structured JSON from the following prompt. \n Fields: chillerId and lookbackDays (optional).\n Prompt: ${prompt}`);\n\n //console.log(llmRes, \">>llmRes\")\n console.log(llmRes?.content, \">>llmRes?.content\")\n\n let chillerReq: ChillerRequest;\n\n try {\n let rawContent: string = llmRes?.content || \"\";\n\n // Remove Markdown code fences if they exist\n rawContent = rawContent.replace(/```json|```/gi, \"\").trim();\n\n // Try to extract JSON block if extra text is present\n const jsonMatch = rawContent.match(/\{[\s\S]*\}/);\n if (jsonMatch) {\n rawContent = jsonMatch[0];\n }\n\n chillerReq = JSON.parse(rawContent);\n\n } catch (err) {\n console.error(\"Failed to parse chiller request:\", err);\n return {\n messages: [\n {\n role: \"assistant\",\n content: JSON.stringify({ error: \"Invalid LLM JSON response\", raw: llmRes })\n }\n ]\n };\n }\n\n const lookback = chillerReq.lookbackDays ?? 90;\n const startDate = new Date();\n startDate.setDate(startDate.getDate() - lookback);\n\n const aggs = [\n {\n $match: {\n \"_tsMetadata._sourceId\": { \"$regex\": `.*${chillerReq.chillerId}.*` } ,\n \"_ts\": { $gte: startDate.toISOString() }\n }\n },\n { $sort: { ts: 1 } },\n { $limit: 10 }\n\n ];\n\n console.log('Aggs::', JSON.stringify(aggs))\n \n let res = await IafItemSvc.aggregateReadings('68c50a58993fee0ea750db6f', aggs, this.requestContext, {});\n let finalRes = this.predictChiller90(res);\n console.log(finalRes, 'finalRes')\n return {\n messages: [\n {\n role: \"assistant\",\n content: `Chiller will cross 90% load around:\", ${finalRes}`\n }\n ]\n };\n }\n\n\n predictChiller90(data: Data): Date | null {\n // Step 1: clean duplicates by unique timestamp\n const readings: Reading[] = Object.values(\n data._list.reduce<Record<string, Reading>>((acc, item) => {\n acc[item._ts] = item; // overwrite duplicates\n return acc;\n }, {})\n );\n\n if (readings.length < 2) return null; // not enough data to predict\n\n // Step 2: sort by timestamp\n readings.sort((a, b) => new Date(a._ts).getTime() - new Date(b._ts).getTime());\n\n // Step 3: convert timestamps to epoch ms\n const points = readings.map(r => ({\n ts: new Date(r._ts).getTime(),\n load: r.chiller_load_pct\n }));\n\n // Step 4: calculate slope & intercept (linear regression)\n const n = points.length;\n const sumX = points.reduce((s, p) => s + p.ts, 0);\n const sumY = points.reduce((s, p) => s + p.load, 0);\n const sumXY = points.reduce((s, p) => s + p.ts * p.load, 0);\n const sumX2 = points.reduce((s, p) => s + p.ts * p.ts, 0);\n\n const denominator = n * sumX2 - sumX * sumX;\n if (denominator === 0) return null; // avoid division by zero\n\n const slope = (n * sumXY - sumX * sumY) / denominator;\n const intercept = (sumY - slope * sumX) / n;\n\n // Step 5: solve for timestamp when load = 0.9\n const targetLoad = 0.9;\n const targetTs = (targetLoad - intercept) / slope;\n\n if (isNaN(targetTs) || !isFinite(targetTs)) return null;\n\n return new Date(targetTs);\n }\n\n}\n"};
await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);

//Upload source code as file
const sourceCode = {_file:fileStream};
await IafAISvc.uploadAgentSourceCode('1201ae31-d2c3-4428-8122-17cd4ce802f3', sourceCode, ctx);

uploadToolSourceCode​

Uploads source code for a Tool resource.

ParameterRequiredTypeDescription
toolIdYesStringThe Tool's id.
sourceCodeYesSourceCodeObject containing source code (_content and optional _id).
ctxNoCtxContext, such as namespaces and authentication token information.
optionsNoObjectOptional upload parameters. Pass an object with a filename field to override the uploaded file name when sourceCode._file is provided.
Returns

Promise<SourceCode> - A Promise resolving to the uploaded SourceCode.

Examples
//Upload source code as String
const sourceCode = { _content: "import { AbstractTool } from '@dtplatform/agent-core';\nimport * as PlatformAPI from '@dtplatform/platform-api';\nconst { IafItemSvc } = PlatformAPI;\nimport { z } from 'zod';\n\nconst toolSchema = z.object({\n name: z.string().optional().nullable().describe('Filter by asset name. Supports regex'),\n dtCategory: z.string().optional().nullable().describe('Filter by the dtCategory property. Supports regex'),\n dtType: z.string().optional().nullable().describe('Filter by dtType property. Supports regex'),\n _pageSize: z.string().optional().nullable().describe('Sets the number of results to return per Page in the response'),\n _offset: z.string().optional().nullable().describe('Sets the number of results to skip in the Page response. For example, set to `10` to skip the first 10 results.')\n});\n\nexport default class GetAssetsTool extends AbstractTool {\n name: string = 'GetAssetsTool';\n description: string = 'Helps to retrieve Assets based on the provided criteria.';\n requestContext: any = {};\n schema: any = toolSchema;\n\n constructor(...args: any[]) {\n super(...args);\n const [{ requestContext }] = args;\n this.requestContext = requestContext;\n }\n\n async _call(args: z.infer<typeof toolSchema>) {\n let criteria: any = { '$or': [] };\n let options: any = {};\n let response: any = {};\n\n if (args.name || args.dtCategory || args.dtType) {\n if (args.name) {\n criteria['$or'].push({\n 'Asset Name': {\n '$regex': this.toRegexString(args.name),\n '$options': 'i'\n }\n });\n }\n if (args.dtCategory) {\n criteria['$or'].push({\n 'properties.dtCategory.val': {\n '$regex': this.toRegexString(args.dtCategory),\n '$options': 'i'\n }\n });\n }\n if (args.dtType) {\n criteria['$or'].push({\n 'properties.dtType.val': {\n '$regex': this.toRegexString(args.dtType),\n '$options': 'i'\n }\n });\n }\n\n if (args._pageSize) {\n options['_pageSize'] = parseInt(args._pageSize, 10);\n }\n if (args._offset) {\n options['_offset'] = parseInt(args._offset, 10);\n }\n\n let colQuery = {\n query: {\n _userType: 'iaf_ext_asset_coll',\n _itemClass: 'NamedUserCollection'\n }\n };\n\n const colOptions = {\n project: { _userType: 1, _itemClass: 1 },\n sort: { _name: 1 },\n page: { _offset: 0, _pageSize: 1 }\n };\n\n const colResponse = await IafItemSvc.getNamedUserItems(\n colQuery,\n this.requestContext,\n colOptions\n );\n\n\n\n let assetCollection: any = null;\n if (colResponse && Array.isArray(colResponse._list) && colResponse._list.length > 0) {\n assetCollection = colResponse._list[0];\n if (assetCollection && assetCollection._id) {\n response = await IafItemSvc.getRelatedItems(\n assetCollection._id,\n {query: criteria},\n this.requestContext,\n options \n );\n }\n }\n }\n return response;\n }\n\n toRegexString(str) {\n const quoted = str.match(/^'(.*)'$/);\n if (quoted) {\n const escaped = quoted[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');\n return `.*(${escaped}).*`;\n }\n const terms = str\n .split(/\s+/)\n .map(term => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));\n return `.*(${terms.join('|')}).*`;\n }\n}\n" };
await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);

//Upload source code as file
const sourceCode = {_file: fileStream}
await IafAISvc.uploadToolSourceCode('5202ae41-a2c4-1429-7126-17ab4dc80245', sourceCode, ctx);