@almadar/integrations 2.41.0 → 2.43.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BaseIntegration-CWdas-N_.d.ts → BaseIntegration-Dgwn1ZR6.d.ts} +5 -1
- package/dist/index.d.ts +40 -17
- package/dist/index.js +166 -3
- package/dist/index.js.map +1 -1
- package/dist/integrations/github/index.d.ts +1 -1
- package/dist/mocks/index.d.ts +1 -1
- package/dist/mocks/index.js +9 -1
- package/dist/mocks/index.js.map +1 -1
- package/dist/runtime/index.d.ts +3 -2
- package/dist/runtime/index.js +165 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/{store-DG5OGiuQ.d.ts → store-DP3gfEfJ.d.ts} +7 -101
- package/package.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LogMeta } from '@almadar/core';
|
|
1
|
+
import { LogMeta, ServiceHostPorts } from '@almadar/core';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Core types for Almadar integrations
|
|
@@ -138,6 +138,8 @@ interface IntegrationCallContext {
|
|
|
138
138
|
principal?: string;
|
|
139
139
|
/** The caller's roster role, from the same identity entity-ACL enforces against. */
|
|
140
140
|
role?: string;
|
|
141
|
+
/** The running app, lent for this call as the caller (`llm call-tools`). */
|
|
142
|
+
host?: ServiceHostPorts;
|
|
141
143
|
}
|
|
142
144
|
/**
|
|
143
145
|
* Factory for creating and managing integration instances
|
|
@@ -145,6 +147,8 @@ interface IntegrationCallContext {
|
|
|
145
147
|
declare class IntegrationFactory {
|
|
146
148
|
private instances;
|
|
147
149
|
private configs;
|
|
150
|
+
/** Names whose app-wide instance was registered directly (mock infrastructure). */
|
|
151
|
+
private registered;
|
|
148
152
|
/**
|
|
149
153
|
* Configure an integration (doesn't instantiate yet). A `principal` scopes
|
|
150
154
|
* the config to that principal; the app-wide config (no principal) is the
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { e as IntegrationLogger, c as IntegrationErrorCode, a as IntegrationConfig, B as BaseIntegration, d as IntegrationFactory, g as IntegrationParams, h as IntegrationResult, I as IntegrationCallContext } from './BaseIntegration-
|
|
2
|
-
export { b as IntegrationError, f as IntegrationParamValue, U as UnknownActionError, V as ValidationError, i as ValidationResult, j as getIntegrationFactory, r as resetIntegrationFactory, v as validateParams } from './BaseIntegration-
|
|
3
|
-
import { e as CredentialStore, d as CredentialPersistence, H as HookDeclaration } from './store-
|
|
4
|
-
export { A as ArxivActions, C as CLIActions, a as CREDENTIAL_ENTITY_TYPE, b as CREDENTIAL_MASTER_KEY_ENV, c as CredentialEntry, D as DatabaseActions, f as DatabaseDriver, g as DatabaseQueryParamValue, h as DatabaseQueryParams, i as DatabaseQueryResult, j as DatabaseRow, k as DeepAgentActions, l as DockerActions, E as EmailActions, G as GitHubActions, I as IconifyActions, m as IntegrationActionName, n as IntegrationContracts, o as IntegrationName, L as LLMIntegrationActions, M as MLActions, O as OAuthActions, p as OtelActions, Q as QueueActions, R as RedisActions, S as StorageActions, q as StripeActions, T as TwilioActions, W as WebhookActions, r as WikimediaActions, Y as YouTubeActions, s as allCredentialEnvVars, t as declaredCredentialEnvVars, u as serviceHooks } from './store-
|
|
5
|
-
import { LogMeta, EntityRow, EventPayload } from '@almadar/core';
|
|
1
|
+
import { e as IntegrationLogger, c as IntegrationErrorCode, a as IntegrationConfig, B as BaseIntegration, d as IntegrationFactory, g as IntegrationParams, h as IntegrationResult, I as IntegrationCallContext } from './BaseIntegration-Dgwn1ZR6.js';
|
|
2
|
+
export { b as IntegrationError, f as IntegrationParamValue, U as UnknownActionError, V as ValidationError, i as ValidationResult, j as getIntegrationFactory, r as resetIntegrationFactory, v as validateParams } from './BaseIntegration-Dgwn1ZR6.js';
|
|
3
|
+
import { e as CredentialStore, d as CredentialPersistence, H as HookDeclaration } from './store-DP3gfEfJ.js';
|
|
4
|
+
export { A as ArxivActions, C as CLIActions, a as CREDENTIAL_ENTITY_TYPE, b as CREDENTIAL_MASTER_KEY_ENV, c as CredentialEntry, D as DatabaseActions, f as DatabaseDriver, g as DatabaseQueryParamValue, h as DatabaseQueryParams, i as DatabaseQueryResult, j as DatabaseRow, k as DeepAgentActions, l as DockerActions, E as EmailActions, G as GitHubActions, I as IconifyActions, m as IntegrationActionName, n as IntegrationContracts, o as IntegrationName, L as LLMIntegrationActions, M as MLActions, O as OAuthActions, p as OtelActions, Q as QueueActions, R as RedisActions, S as StorageActions, q as StripeActions, T as TwilioActions, W as WebhookActions, r as WikimediaActions, Y as YouTubeActions, s as allCredentialEnvVars, t as declaredCredentialEnvVars, u as serviceHooks } from './store-DP3gfEfJ.js';
|
|
5
|
+
import { LogMeta, EntityRow, EventPayload, ServiceHostPorts } from '@almadar/core';
|
|
6
|
+
import { AgentChatMessage, AgentTool, AgentActivity, ToolCallingClient } from '@almadar/llm';
|
|
6
7
|
export { GitHubIntegration } from './integrations/github/index.js';
|
|
7
8
|
|
|
8
9
|
/**
|
|
@@ -620,16 +621,6 @@ declare class EsignIntegration extends BaseIntegration {
|
|
|
620
621
|
private downloadDocument;
|
|
621
622
|
}
|
|
622
623
|
|
|
623
|
-
/**
|
|
624
|
-
* LLM integration using @almadar/llm
|
|
625
|
-
*
|
|
626
|
-
* Provides 5 actions:
|
|
627
|
-
* - generate: Generate text content from a prompt
|
|
628
|
-
* - classify: Classify text into predefined categories
|
|
629
|
-
* - extract: Extract structured data from text using a schema
|
|
630
|
-
* - summarize: Summarize long text content
|
|
631
|
-
* - embed: Generate embeddings for an array of texts
|
|
632
|
-
*/
|
|
633
624
|
declare class LLMIntegration extends BaseIntegration {
|
|
634
625
|
private client;
|
|
635
626
|
private embeddings;
|
|
@@ -648,14 +639,46 @@ declare class LLMIntegration extends BaseIntegration {
|
|
|
648
639
|
* `EMBEDDING_PROVIDER` / `EMBEDDING_MODEL` / `EMBEDDING_API_KEY`.
|
|
649
640
|
*/
|
|
650
641
|
private getEmbeddings;
|
|
651
|
-
execute(action: string, params: IntegrationParams): Promise<IntegrationResult>;
|
|
642
|
+
execute(action: string, params: IntegrationParams, context?: IntegrationCallContext): Promise<IntegrationResult>;
|
|
652
643
|
private generate;
|
|
653
644
|
private classify;
|
|
654
645
|
private extract;
|
|
655
646
|
private summarize;
|
|
647
|
+
private callTools;
|
|
656
648
|
private embed;
|
|
657
649
|
}
|
|
658
650
|
|
|
651
|
+
/**
|
|
652
|
+
* `llm call-tools`: the model operates the running app AS THE CALLER through the
|
|
653
|
+
* host's ports. Each allowlisted input is one tool (its declared payload is the
|
|
654
|
+
* schema, its `@description` the text); each allowlisted entity is one read tool.
|
|
655
|
+
* Every tool call is an ordinary dispatch on the host (guards, policies and
|
|
656
|
+
* listens all apply) whose response goes back to the model, until it replies.
|
|
657
|
+
*/
|
|
658
|
+
|
|
659
|
+
interface ToolLoopRequest {
|
|
660
|
+
messages: readonly AgentChatMessage[];
|
|
661
|
+
tools: readonly AgentTool[];
|
|
662
|
+
instructions?: string;
|
|
663
|
+
maxSteps?: number;
|
|
664
|
+
}
|
|
665
|
+
/** Which model answered, for each `llm_response` step. */
|
|
666
|
+
interface ToolLoopModel {
|
|
667
|
+
provider: string;
|
|
668
|
+
model: string;
|
|
669
|
+
}
|
|
670
|
+
interface ToolLoopResult {
|
|
671
|
+
reply: string;
|
|
672
|
+
steps: AgentActivity[];
|
|
673
|
+
usage: {
|
|
674
|
+
promptTokens: number;
|
|
675
|
+
completionTokens: number;
|
|
676
|
+
totalTokens: number;
|
|
677
|
+
modelCalls: number;
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
declare function runToolLoop(client: ToolCallingClient, host: ServiceHostPorts, request: ToolLoopRequest, model: ToolLoopModel, now?: () => number): Promise<ToolLoopResult>;
|
|
681
|
+
|
|
659
682
|
declare class MLIntegration extends BaseIntegration {
|
|
660
683
|
private readonly eventsUrl;
|
|
661
684
|
private readonly timeoutMs;
|
|
@@ -1085,4 +1108,4 @@ declare class RiggerIntegration extends BaseIntegration {
|
|
|
1085
1108
|
private generate;
|
|
1086
1109
|
}
|
|
1087
1110
|
|
|
1088
|
-
export { AccountingIntegration, type AlmadarCheckoutSession, type AlmadarCustomer, type AlmadarInvoiceFailure, type AlmadarInvoicePayment, type AlmadarPortalSession, type AlmadarStripeEvent, type AlmadarStripeEventOk, type AlmadarSubscription, type AlmadarSubscriptionStatus, type AlmadarTier, ArxivIntegration, type ArxivResult, BankingIntegration, BaseIntegration, CLIIntegration, CREDENTIALS_FILE_ENV, CalendarIntegration, type CancelSubscriptionInput, ConsoleLogger, type CreateCheckoutInput, type CreateCustomerInput, type CreatePortalInput, CredentialPersistence, CredentialStore, CredentialsIntegration, DatabaseIntegration, DeepAgentIntegration, DockerIntegration, DriveIntegration, EmailIntegration, EsignIntegration, FileCredentialPersistence, HookDeclaration, type HookProviderInput, type HookProviderResult, IconifyIntegration, InMemoryPendingGrantStore, IntegrationCallContext, IntegrationConfig, type IntegrationConstructor, IntegrationErrorCode, IntegrationFactory, IntegrationLogger, IntegrationParams, IntegrationResult, LLMIntegration, MLIntegration, MetaAdsIntegration, type OAuthAuthorizeInput, OAuthGrantNotFoundError, OAuthIntegration, type OAuthProvider, OAuthSubjectMismatchError, type OAuthTokenInput, type OAuthTokenResult, OtelIntegration, type PendingAuthorization, type PendingGrantStore, PushIntegration, QueueIntegration, RedisIntegration, type RegisteredHookProvider, type RetryConfig, RiggerIntegration, type SqlGuardResult, StorageIntegration, StripeIntegration, type StripePriceMap, TwilioIntegration, type UpdateSubscriptionInput, type VerifyAndParseInput, WebhookIntegration, WikimediaIntegration, YouTubeIntegration, allHookDeclarations, assertReadOnlySelect, getActiveFactory, getInstalledCredentialStore, getIntegration, getRegisteredIntegrations, googleCalendarHookProvider, installActiveFactory, installCredentialStore, installPendingGrantStore, isKnownIntegration, parseCalendarPushNotification, registerIntegration, registeredHookProviders, resolveCredentialRef, runWithCredentialScope, uninstallCredentialStore, verifyAndParseStripeEvent, withRetry };
|
|
1111
|
+
export { AccountingIntegration, type AlmadarCheckoutSession, type AlmadarCustomer, type AlmadarInvoiceFailure, type AlmadarInvoicePayment, type AlmadarPortalSession, type AlmadarStripeEvent, type AlmadarStripeEventOk, type AlmadarSubscription, type AlmadarSubscriptionStatus, type AlmadarTier, ArxivIntegration, type ArxivResult, BankingIntegration, BaseIntegration, CLIIntegration, CREDENTIALS_FILE_ENV, CalendarIntegration, type CancelSubscriptionInput, ConsoleLogger, type CreateCheckoutInput, type CreateCustomerInput, type CreatePortalInput, CredentialPersistence, CredentialStore, CredentialsIntegration, DatabaseIntegration, DeepAgentIntegration, DockerIntegration, DriveIntegration, EmailIntegration, EsignIntegration, FileCredentialPersistence, HookDeclaration, type HookProviderInput, type HookProviderResult, IconifyIntegration, InMemoryPendingGrantStore, IntegrationCallContext, IntegrationConfig, type IntegrationConstructor, IntegrationErrorCode, IntegrationFactory, IntegrationLogger, IntegrationParams, IntegrationResult, LLMIntegration, MLIntegration, MetaAdsIntegration, type OAuthAuthorizeInput, OAuthGrantNotFoundError, OAuthIntegration, type OAuthProvider, OAuthSubjectMismatchError, type OAuthTokenInput, type OAuthTokenResult, OtelIntegration, type PendingAuthorization, type PendingGrantStore, PushIntegration, QueueIntegration, RedisIntegration, type RegisteredHookProvider, type RetryConfig, RiggerIntegration, type SqlGuardResult, StorageIntegration, StripeIntegration, type StripePriceMap, type ToolLoopRequest, type ToolLoopResult, TwilioIntegration, type UpdateSubscriptionInput, type VerifyAndParseInput, WebhookIntegration, WikimediaIntegration, YouTubeIntegration, allHookDeclarations, assertReadOnlySelect, getActiveFactory, getInstalledCredentialStore, getIntegration, getRegisteredIntegrations, googleCalendarHookProvider, installActiveFactory, installCredentialStore, installPendingGrantStore, isKnownIntegration, parseCalendarPushNotification, registerIntegration, registeredHookProviders, resolveCredentialRef, runToolLoop, runWithCredentialScope, uninstallCredentialStore, verifyAndParseStripeEvent, withRetry };
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import webpush from 'web-push';
|
|
|
13
13
|
import { Readable } from 'stream';
|
|
14
14
|
import { getAvailableProvider, LLMClient, EmbeddingClient } from '@almadar/llm';
|
|
15
15
|
import { z } from 'zod';
|
|
16
|
+
import { traceActivityPayload, findInputByAddress, payloadSchemaToJsonSchema, EventPayloadSchema } from '@almadar/core';
|
|
16
17
|
import { execSync, spawn } from 'child_process';
|
|
17
18
|
import { tmpdir } from 'os';
|
|
18
19
|
import * as oidc from 'openid-client';
|
|
@@ -421,6 +422,8 @@ var IntegrationFactory = class {
|
|
|
421
422
|
constructor() {
|
|
422
423
|
this.instances = /* @__PURE__ */ new Map();
|
|
423
424
|
this.configs = /* @__PURE__ */ new Map();
|
|
425
|
+
/** Names whose app-wide instance was registered directly (mock infrastructure). */
|
|
426
|
+
this.registered = /* @__PURE__ */ new Set();
|
|
424
427
|
}
|
|
425
428
|
/**
|
|
426
429
|
* Configure an integration (doesn't instantiate yet). A `principal` scopes
|
|
@@ -435,7 +438,8 @@ var IntegrationFactory = class {
|
|
|
435
438
|
* back to the app-wide config when no per-principal config exists.
|
|
436
439
|
*/
|
|
437
440
|
get(name, principal) {
|
|
438
|
-
const
|
|
441
|
+
const registered = this.registered.has(name) && !this.configs.has(instanceKey(name, principal));
|
|
442
|
+
const key = registered ? name : instanceKey(name, principal);
|
|
439
443
|
const cached = this.instances.get(key);
|
|
440
444
|
if (cached) {
|
|
441
445
|
return cached;
|
|
@@ -479,6 +483,7 @@ var IntegrationFactory = class {
|
|
|
479
483
|
* Register an integration instance directly (used by mock infrastructure)
|
|
480
484
|
*/
|
|
481
485
|
registerInstance(name, instance, principal) {
|
|
486
|
+
if (principal === void 0) this.registered.add(name);
|
|
482
487
|
this.instances.set(instanceKey(name, principal), instance);
|
|
483
488
|
}
|
|
484
489
|
/**
|
|
@@ -489,8 +494,10 @@ var IntegrationFactory = class {
|
|
|
489
494
|
invalidate(name) {
|
|
490
495
|
if (name === void 0) {
|
|
491
496
|
this.instances.clear();
|
|
497
|
+
this.registered.clear();
|
|
492
498
|
return;
|
|
493
499
|
}
|
|
500
|
+
this.registered.delete(name);
|
|
494
501
|
for (const key of this.instances.keys()) {
|
|
495
502
|
if (key === name || key.startsWith(`${name}\0`)) {
|
|
496
503
|
this.instances.delete(key);
|
|
@@ -502,6 +509,7 @@ var IntegrationFactory = class {
|
|
|
502
509
|
*/
|
|
503
510
|
clear() {
|
|
504
511
|
this.instances.clear();
|
|
512
|
+
this.registered.clear();
|
|
505
513
|
}
|
|
506
514
|
/**
|
|
507
515
|
* Clear all instances and configs
|
|
@@ -509,6 +517,7 @@ var IntegrationFactory = class {
|
|
|
509
517
|
reset() {
|
|
510
518
|
this.instances.clear();
|
|
511
519
|
this.configs.clear();
|
|
520
|
+
this.registered.clear();
|
|
512
521
|
}
|
|
513
522
|
};
|
|
514
523
|
var _factory = null;
|
|
@@ -2458,6 +2467,148 @@ var EsignIntegration = class extends BaseIntegration {
|
|
|
2458
2467
|
}
|
|
2459
2468
|
};
|
|
2460
2469
|
registerIntegration("esign", EsignIntegration);
|
|
2470
|
+
var DEFAULT_MAX_STEPS = 8;
|
|
2471
|
+
var TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
2472
|
+
function toolName(raw) {
|
|
2473
|
+
if (!TOOL_NAME.test(raw)) {
|
|
2474
|
+
throw new Error(`call-tools: tool name '${raw}' is not a valid tool name (letters, digits, _ and -, at most 64)`);
|
|
2475
|
+
}
|
|
2476
|
+
return raw;
|
|
2477
|
+
}
|
|
2478
|
+
function buildTools(host, tools) {
|
|
2479
|
+
const inputs = host.inputs();
|
|
2480
|
+
const out = /* @__PURE__ */ new Map();
|
|
2481
|
+
for (const tool of tools) {
|
|
2482
|
+
if (tool.event !== void 0) {
|
|
2483
|
+
const input = findInputByAddress(inputs, tool.event, host.caller);
|
|
2484
|
+
if (!input) throw new Error(`call-tools: '${tool.event}' is not a declared external input`);
|
|
2485
|
+
const name = toolName(tool.event.split(".").join("__"));
|
|
2486
|
+
out.set(name, {
|
|
2487
|
+
def: {
|
|
2488
|
+
type: "function",
|
|
2489
|
+
function: { name, description: input.description ?? tool.event, parameters: payloadSchemaToJsonSchema(input.payloadSchema) }
|
|
2490
|
+
},
|
|
2491
|
+
target: { kind: "input", address: tool.event, input }
|
|
2492
|
+
});
|
|
2493
|
+
} else if (tool.read !== void 0) {
|
|
2494
|
+
const name = toolName(`read__${tool.read}`);
|
|
2495
|
+
out.set(name, {
|
|
2496
|
+
def: {
|
|
2497
|
+
type: "function",
|
|
2498
|
+
function: { name, description: `Read the ${tool.read} rows you may see`, parameters: { type: "object", properties: {} } }
|
|
2499
|
+
},
|
|
2500
|
+
target: { kind: "read", entity: tool.read }
|
|
2501
|
+
});
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
return out;
|
|
2505
|
+
}
|
|
2506
|
+
function dispatchFailure(response) {
|
|
2507
|
+
if (response.rejections && response.rejections.length > 0) return response.rejections.map((r) => r.code).join(", ");
|
|
2508
|
+
if (response.guardFailed !== void 0) return `guard failed: ${response.guardFailed}`;
|
|
2509
|
+
if (!response.success) return response.error ?? "dispatch failed";
|
|
2510
|
+
const failed = (response.effectResults ?? []).find((r) => !r.success);
|
|
2511
|
+
if (failed) return failed.error ?? `${failed.effect} failed`;
|
|
2512
|
+
if (!response.transitioned) return "no transition";
|
|
2513
|
+
return void 0;
|
|
2514
|
+
}
|
|
2515
|
+
function parseArgs(args) {
|
|
2516
|
+
let value;
|
|
2517
|
+
try {
|
|
2518
|
+
value = JSON.parse(args === "" ? "{}" : args);
|
|
2519
|
+
} catch {
|
|
2520
|
+
value = void 0;
|
|
2521
|
+
}
|
|
2522
|
+
return EventPayloadSchema.safeParse(value);
|
|
2523
|
+
}
|
|
2524
|
+
async function runToolLoop(client, host, request, model, now = Date.now) {
|
|
2525
|
+
const tools = buildTools(host, request.tools);
|
|
2526
|
+
const defs = [...tools.values()].map((t) => t.def);
|
|
2527
|
+
const maxSteps = request.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
2528
|
+
const conversation = [
|
|
2529
|
+
...request.instructions !== void 0 ? [{ role: "system", content: request.instructions }] : [],
|
|
2530
|
+
...request.messages.map((m) => ({ role: m.role, content: m.content }))
|
|
2531
|
+
];
|
|
2532
|
+
const userPrompt = [...request.messages].reverse().find((m) => m.role === "user")?.content ?? "";
|
|
2533
|
+
const steps = [];
|
|
2534
|
+
const record = (activity) => {
|
|
2535
|
+
steps.push(activity);
|
|
2536
|
+
host.message(traceActivityPayload(activity));
|
|
2537
|
+
};
|
|
2538
|
+
const usage = { promptTokens: 0, completionTokens: 0, totalTokens: 0, modelCalls: 0 };
|
|
2539
|
+
while (usage.modelCalls < maxSteps) {
|
|
2540
|
+
const started = now();
|
|
2541
|
+
const turn = await client.callWithTools({ messages: conversation, tools: defs });
|
|
2542
|
+
const ended = now();
|
|
2543
|
+
usage.modelCalls += 1;
|
|
2544
|
+
if (turn.usage) {
|
|
2545
|
+
usage.promptTokens += turn.usage.promptTokens;
|
|
2546
|
+
usage.completionTokens += turn.usage.completionTokens;
|
|
2547
|
+
usage.totalTokens += turn.usage.totalTokens;
|
|
2548
|
+
}
|
|
2549
|
+
conversation.push(turn.message);
|
|
2550
|
+
const calls = turn.message.tool_calls ?? [];
|
|
2551
|
+
record({
|
|
2552
|
+
type: "llm_response",
|
|
2553
|
+
content: turn.message.content ?? "",
|
|
2554
|
+
llm: {
|
|
2555
|
+
service: "llm",
|
|
2556
|
+
provider: model.provider,
|
|
2557
|
+
model: model.model,
|
|
2558
|
+
systemPrompt: request.instructions ?? "",
|
|
2559
|
+
userPrompt,
|
|
2560
|
+
...calls.length > 0 ? { toolCallsJson: JSON.stringify(calls) } : {},
|
|
2561
|
+
durationMs: ended - started,
|
|
2562
|
+
...turn.usage ? { promptTokens: turn.usage.promptTokens, completionTokens: turn.usage.completionTokens } : {}
|
|
2563
|
+
},
|
|
2564
|
+
timestamp: ended
|
|
2565
|
+
});
|
|
2566
|
+
if (calls.length === 0) return { reply: turn.message.content ?? "", steps, usage };
|
|
2567
|
+
for (const call of calls) {
|
|
2568
|
+
const args = call.function.arguments;
|
|
2569
|
+
const tool = tools.get(call.function.name);
|
|
2570
|
+
const kind = tool === void 0 ? "invalid" : tool.target.kind;
|
|
2571
|
+
const label = tool === void 0 ? call.function.name : tool.target.kind === "input" ? tool.target.address : tool.target.entity;
|
|
2572
|
+
record({ type: "tool_call", tool: label, kind, argsText: args, timestamp: now() });
|
|
2573
|
+
let content;
|
|
2574
|
+
if (!tool) {
|
|
2575
|
+
content = JSON.stringify({ error: `'${call.function.name}' is not one of your tools` });
|
|
2576
|
+
record({ type: "tool_result", tool: label, kind, success: false, detail: "not an allowed tool", resultText: content, timestamp: now() });
|
|
2577
|
+
} else if (tool.target.kind === "read") {
|
|
2578
|
+
const rows = await host.read(tool.target.entity);
|
|
2579
|
+
content = JSON.stringify({ rows });
|
|
2580
|
+
record({ type: "tool_result", tool: label, kind, success: true, rows: rows.length, resultText: content, timestamp: now() });
|
|
2581
|
+
} else {
|
|
2582
|
+
const parsed = parseArgs(args);
|
|
2583
|
+
if (!parsed.success) {
|
|
2584
|
+
content = JSON.stringify({ error: "arguments must be a JSON object" });
|
|
2585
|
+
record({ type: "tool_result", tool: label, kind, success: false, detail: "arguments are not a JSON object", resultText: content, timestamp: now() });
|
|
2586
|
+
} else {
|
|
2587
|
+
const { input } = tool.target;
|
|
2588
|
+
const response = await host.dispatchInput(input.orbital, {
|
|
2589
|
+
targetTrait: input.trait,
|
|
2590
|
+
event: input.event,
|
|
2591
|
+
payload: parsed.data
|
|
2592
|
+
});
|
|
2593
|
+
const detail = dispatchFailure(response);
|
|
2594
|
+
content = JSON.stringify(response);
|
|
2595
|
+
record({ type: "tool_result", tool: label, kind, success: detail === void 0, ...detail !== void 0 ? { detail } : {}, resultText: content, timestamp: now() });
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
conversation.push({ role: "tool", content, tool_call_id: call.id });
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
throw new Error(`call-tools: no reply after ${maxSteps} model calls`);
|
|
2602
|
+
}
|
|
2603
|
+
|
|
2604
|
+
// src/integrations/llm/index.ts
|
|
2605
|
+
var CallToolsParamsSchema = z.object({
|
|
2606
|
+
messages: z.array(z.object({ role: z.enum(["user", "assistant"]), content: z.string() })),
|
|
2607
|
+
tools: z.array(z.object({ event: z.string().optional(), read: z.string().optional() })),
|
|
2608
|
+
instructions: z.string().optional(),
|
|
2609
|
+
maxSteps: z.number().int().positive().optional(),
|
|
2610
|
+
model: z.string().optional()
|
|
2611
|
+
});
|
|
2461
2612
|
var LLMIntegration = class extends BaseIntegration {
|
|
2462
2613
|
constructor(config) {
|
|
2463
2614
|
super(config);
|
|
@@ -2498,7 +2649,7 @@ var LLMIntegration = class extends BaseIntegration {
|
|
|
2498
2649
|
}
|
|
2499
2650
|
return this.embeddings;
|
|
2500
2651
|
}
|
|
2501
|
-
async execute(action, params) {
|
|
2652
|
+
async execute(action, params, context) {
|
|
2502
2653
|
const validation = this.validateParams(action, params);
|
|
2503
2654
|
if (!validation.valid) return this.validationFailure(action, validation.errors);
|
|
2504
2655
|
const startTime = Date.now();
|
|
@@ -2520,6 +2671,10 @@ var LLMIntegration = class extends BaseIntegration {
|
|
|
2520
2671
|
case "embed":
|
|
2521
2672
|
data = await this.executeWithRetry(() => this.embed(params));
|
|
2522
2673
|
break;
|
|
2674
|
+
// Never retried: a retry would re-fire inputs the first attempt already fired.
|
|
2675
|
+
case "call-tools":
|
|
2676
|
+
data = await this.callTools(params, context);
|
|
2677
|
+
break;
|
|
2523
2678
|
default:
|
|
2524
2679
|
throw new UnknownActionError(this.config.name, action);
|
|
2525
2680
|
}
|
|
@@ -2610,6 +2765,14 @@ Return ONLY valid JSON matching the schema.`,
|
|
|
2610
2765
|
});
|
|
2611
2766
|
return result;
|
|
2612
2767
|
}
|
|
2768
|
+
async callTools(params, context) {
|
|
2769
|
+
if (!context?.host) {
|
|
2770
|
+
throw new Error("llm.call-tools needs host ports: run it from a host that lends the running app (call-service on a server)");
|
|
2771
|
+
}
|
|
2772
|
+
const request = CallToolsParamsSchema.parse(params);
|
|
2773
|
+
const client = request.model !== void 0 ? new LLMClient({ provider: this.provider, model: request.model }) : this.getClient();
|
|
2774
|
+
return runToolLoop(client, context.host, request, { provider: client.getProvider(), model: client.getModelName() });
|
|
2775
|
+
}
|
|
2613
2776
|
async embed(params) {
|
|
2614
2777
|
const { texts } = params;
|
|
2615
2778
|
if (!Array.isArray(texts)) {
|
|
@@ -5837,6 +6000,6 @@ var RiggerIntegration = class extends BaseIntegration {
|
|
|
5837
6000
|
};
|
|
5838
6001
|
registerIntegration("rigger", RiggerIntegration);
|
|
5839
6002
|
|
|
5840
|
-
export { AccountingIntegration, ArxivIntegration, BankingIntegration, BaseIntegration, CLIIntegration, CREDENTIALS_FILE_ENV, CREDENTIAL_ENTITY_TYPE, CREDENTIAL_MASTER_KEY_ENV, CalendarIntegration, ConsoleLogger, CredentialStore, CredentialsIntegration, DatabaseIntegration, DeepAgentIntegration, DockerIntegration, DriveIntegration, EmailIntegration, EsignIntegration, FileCredentialPersistence, GitHubIntegration, IconifyIntegration, InMemoryPendingGrantStore, IntegrationError, IntegrationFactory, LLMIntegration, MLIntegration, MetaAdsIntegration, OAuthGrantNotFoundError, OAuthIntegration, OAuthSubjectMismatchError, OtelIntegration, PushIntegration, QueueIntegration, RedisIntegration, RiggerIntegration, StorageIntegration, StripeIntegration, TwilioIntegration, UnknownActionError, WebhookIntegration, WikimediaIntegration, YouTubeIntegration, allCredentialEnvVars, allHookDeclarations, assertReadOnlySelect, declaredCredentialEnvVars, getActiveFactory, getInstalledCredentialStore, getIntegration, getIntegrationFactory, getRegisteredIntegrations, googleCalendarHookProvider, installActiveFactory, installCredentialStore, installPendingGrantStore, isKnownIntegration, parseCalendarPushNotification, registerIntegration, registeredHookProviders, resetIntegrationFactory, resolveCredentialRef, runWithCredentialScope, serviceHooks, uninstallCredentialStore, validateParams, verifyAndParseStripeEvent, withRetry };
|
|
6003
|
+
export { AccountingIntegration, ArxivIntegration, BankingIntegration, BaseIntegration, CLIIntegration, CREDENTIALS_FILE_ENV, CREDENTIAL_ENTITY_TYPE, CREDENTIAL_MASTER_KEY_ENV, CalendarIntegration, ConsoleLogger, CredentialStore, CredentialsIntegration, DatabaseIntegration, DeepAgentIntegration, DockerIntegration, DriveIntegration, EmailIntegration, EsignIntegration, FileCredentialPersistence, GitHubIntegration, IconifyIntegration, InMemoryPendingGrantStore, IntegrationError, IntegrationFactory, LLMIntegration, MLIntegration, MetaAdsIntegration, OAuthGrantNotFoundError, OAuthIntegration, OAuthSubjectMismatchError, OtelIntegration, PushIntegration, QueueIntegration, RedisIntegration, RiggerIntegration, StorageIntegration, StripeIntegration, TwilioIntegration, UnknownActionError, WebhookIntegration, WikimediaIntegration, YouTubeIntegration, allCredentialEnvVars, allHookDeclarations, assertReadOnlySelect, declaredCredentialEnvVars, getActiveFactory, getInstalledCredentialStore, getIntegration, getIntegrationFactory, getRegisteredIntegrations, googleCalendarHookProvider, installActiveFactory, installCredentialStore, installPendingGrantStore, isKnownIntegration, parseCalendarPushNotification, registerIntegration, registeredHookProviders, resetIntegrationFactory, resolveCredentialRef, runToolLoop, runWithCredentialScope, serviceHooks, uninstallCredentialStore, validateParams, verifyAndParseStripeEvent, withRetry };
|
|
5841
6004
|
//# sourceMappingURL=index.js.map
|
|
5842
6005
|
//# sourceMappingURL=index.js.map
|