@signalwire/sdk 3.7.1 → 3.9.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/CHANGELOG.md +214 -0
- package/README.md +1 -0
- package/dist/AgentBase.d.ts +120 -3
- package/dist/AgentBase.js +291 -18
- package/dist/AgentBase.js.map +1 -1
- package/dist/AgentServer.d.ts +30 -6
- package/dist/AgentServer.js +28 -2
- package/dist/AgentServer.js.map +1 -1
- package/dist/AiEvents.d.ts +70 -0
- package/dist/AiEvents.js +94 -0
- package/dist/AiEvents.js.map +1 -0
- package/dist/ContextBuilder.d.ts +197 -14
- package/dist/ContextBuilder.js +422 -13
- package/dist/ContextBuilder.js.map +1 -1
- package/dist/FunctionResult.d.ts +129 -0
- package/dist/FunctionResult.js +170 -0
- package/dist/FunctionResult.js.map +1 -1
- package/dist/Logger.d.ts +1 -1
- package/dist/PostPrompt.d.ts +19 -0
- package/dist/PostPrompt.js +43 -0
- package/dist/PostPrompt.js.map +1 -1
- package/dist/SWMLService.d.ts +151 -10
- package/dist/SWMLService.js +377 -61
- package/dist/SWMLService.js.map +1 -1
- package/dist/SchemaUtils.js +14 -1
- package/dist/SchemaUtils.js.map +1 -1
- package/dist/SemanticGate.d.ts +61 -1
- package/dist/SemanticGate.js +108 -15
- package/dist/SemanticGate.js.map +1 -1
- package/dist/SessionManager.d.ts +17 -6
- package/dist/SessionManager.js +16 -3
- package/dist/SessionManager.js.map +1 -1
- package/dist/SwaigFunction.d.ts +86 -9
- package/dist/SwaigFunction.js +215 -59
- package/dist/SwaigFunction.js.map +1 -1
- package/dist/ToolMiddleware.d.ts +82 -0
- package/dist/ToolMiddleware.js +131 -0
- package/dist/ToolMiddleware.js.map +1 -0
- package/dist/TypeInference.d.ts +2 -2
- package/dist/TypeInference.js +1 -1
- package/dist/TypeInference.js.map +1 -1
- package/dist/ai-chat/ChatGateway.d.ts +5 -5
- package/dist/ai-chat/HandoffRouter.d.ts +3 -3
- package/dist/cli/tsdocs/api-index.json +1 -1
- package/dist/cli/tsdocs/topics.js +24 -4
- package/dist/cli/tsdocs/topics.js.map +1 -1
- package/dist/index.d.ts +23 -8
- package/dist/index.js +16 -5
- package/dist/index.js.map +1 -1
- package/dist/livewire/index.d.ts +3 -0
- package/dist/livewire/index.js +3 -0
- package/dist/livewire/index.js.map +1 -1
- package/dist/llms.txt +1 -0
- package/dist/patterns/Proposal.d.ts +146 -0
- package/dist/patterns/Proposal.js +212 -0
- package/dist/patterns/Proposal.js.map +1 -0
- package/dist/patterns/RequestList.d.ts +136 -0
- package/dist/patterns/RequestList.js +169 -0
- package/dist/patterns/RequestList.js.map +1 -0
- package/dist/relay/Call.d.ts +1 -1
- package/dist/relay/Call.js +1 -1
- package/dist/relay/Message.d.ts +1 -1
- package/dist/relay/Message.js +1 -1
- package/dist/relay/RelayClient.d.ts +0 -2
- package/dist/relay/RelayClient.js.map +1 -1
- package/dist/relay/RelayEvent.d.ts +3 -3
- package/dist/relay/RelayEvent.js +3 -3
- package/dist/relay/closedSets.d.ts +10 -10
- package/dist/relay/closedSets.js +2 -2
- package/dist/relay/types.d.ts +1 -1
- package/dist/rest/base/CrudResource.d.ts +1 -1
- package/dist/rest/base/CrudResource.js +1 -1
- package/dist/skills/SkillBase.d.ts +26 -3
- package/dist/skills/SkillBase.js +14 -3
- package/dist/skills/SkillBase.js.map +1 -1
- package/dist/speech/numbers.d.ts +66 -0
- package/dist/speech/numbers.js +281 -0
- package/dist/speech/numbers.js.map +1 -0
- package/dist/speech/spelling.d.ts +71 -0
- package/dist/speech/spelling.js +294 -0
- package/dist/speech/spelling.js.map +1 -0
- package/dist/testing/CallSimulator.d.ts +281 -0
- package/dist/testing/CallSimulator.js +666 -0
- package/dist/testing/CallSimulator.js.map +1 -0
- package/docs/agent-guide.md +4 -4
- package/docs/api-reference.md +285 -28
- package/docs/architecture.md +8 -4
- package/docs/cli-guide.md +2 -0
- package/docs/contexts-guide.md +47 -4
- package/docs/conversation_patterns.md +257 -0
- package/docs/mcp_integration.md +1 -1
- package/docs/pgi_agent_guide.md +2 -1
- package/docs/programmatically_governed_inference.md +2 -2
- package/docs/swaig-reference.md +95 -3
- package/docs/swml_service_guide.md +31 -6
- package/package.json +3 -1
package/dist/SWMLService.js
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* Uses SwmlBuilder for verb methods and Hono for HTTP serving.
|
|
7
7
|
*/
|
|
8
8
|
import { Hono } from 'hono';
|
|
9
|
+
import { RegExpRouter } from 'hono/router/reg-exp-router';
|
|
10
|
+
import { TrieRouter } from 'hono/router/trie-router';
|
|
9
11
|
import { cors } from 'hono/cors';
|
|
10
12
|
import { basicAuth } from 'hono/basic-auth';
|
|
11
13
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
@@ -15,9 +17,69 @@ import { SchemaUtils } from './SchemaUtils.js';
|
|
|
15
17
|
import { SslConfig } from './SslConfig.js';
|
|
16
18
|
import { ConfigLoader } from './ConfigLoader.js';
|
|
17
19
|
import { getLogger } from './Logger.js';
|
|
18
|
-
import { SwaigFunction } from './SwaigFunction.js';
|
|
20
|
+
import { SwaigFunction, NATIVE_WEBHOOK_URL, } from './SwaigFunction.js';
|
|
21
|
+
import { ResendDedupe } from './ToolMiddleware.js';
|
|
19
22
|
import { applyGateFields, _hasGateFields } from './SemanticGate.js';
|
|
20
23
|
import { FunctionResult } from './FunctionResult.js';
|
|
24
|
+
// ── Verb handler interfaces ────────────────────────────────────────────
|
|
25
|
+
/** RegExpRouter matchers by template (null: it can't take the template), for {@link routeMatches}. */
|
|
26
|
+
const REGEXP_MATCHERS = new Map();
|
|
27
|
+
/** Trie matchers by template, for {@link routeMatches}. */
|
|
28
|
+
const TRIE_MATCHERS = new Map();
|
|
29
|
+
/** The most path segments a trie match in {@link routeMatches} takes. */
|
|
30
|
+
const MAX_TRIE_SEGMENTS = 128;
|
|
31
|
+
/**
|
|
32
|
+
* Whether `path` matches the route `template`, as routing matches it: with
|
|
33
|
+
* Hono's own routers, RegExpRouter, else TrieRouter, as its default router
|
|
34
|
+
* chooses, so its whole template grammar applies. RegExpRouter can't take
|
|
35
|
+
* some templates, and answers a zero-length capture with no handler list;
|
|
36
|
+
* the trie router takes those. The trie's work grows with the square of the
|
|
37
|
+
* segments and this runs before auth, so it only takes paths of a length a
|
|
38
|
+
* callback has; a longer one isn't a match. Matchers are cached per template.
|
|
39
|
+
*/
|
|
40
|
+
function routeMatches(template, path) {
|
|
41
|
+
let regexp = REGEXP_MATCHERS.get(template);
|
|
42
|
+
if (regexp === undefined) {
|
|
43
|
+
// It refuses some templates when they're added, others on first match.
|
|
44
|
+
try {
|
|
45
|
+
regexp = new RegExpRouter();
|
|
46
|
+
regexp.add('ALL', template, true);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
regexp = null;
|
|
50
|
+
}
|
|
51
|
+
if (REGEXP_MATCHERS.size >= 512)
|
|
52
|
+
REGEXP_MATCHERS.clear();
|
|
53
|
+
REGEXP_MATCHERS.set(template, regexp);
|
|
54
|
+
}
|
|
55
|
+
if (regexp) {
|
|
56
|
+
try {
|
|
57
|
+
const handlers = regexp.match('ALL', path)[0];
|
|
58
|
+
if (handlers)
|
|
59
|
+
return handlers.length > 0;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// It can't take this template: the same on every request
|
|
63
|
+
REGEXP_MATCHERS.set(template, null);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (path.split('/').length > MAX_TRIE_SEGMENTS)
|
|
67
|
+
return false;
|
|
68
|
+
try {
|
|
69
|
+
let trie = TRIE_MATCHERS.get(template);
|
|
70
|
+
if (!trie) {
|
|
71
|
+
trie = new TrieRouter();
|
|
72
|
+
trie.add('ALL', template, true);
|
|
73
|
+
if (TRIE_MATCHERS.size >= 512)
|
|
74
|
+
TRIE_MATCHERS.clear();
|
|
75
|
+
TRIE_MATCHERS.set(template, trie);
|
|
76
|
+
}
|
|
77
|
+
return (trie.match('ALL', path)[0]?.length ?? 0) > 0;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
21
83
|
/**
|
|
22
84
|
* Registry for custom SWML verb handlers.
|
|
23
85
|
* Mirrors Python SDK's `VerbHandlerRegistry`.
|
|
@@ -348,17 +410,32 @@ export class SWMLService {
|
|
|
348
410
|
_proxyUrlBase = process.env['SWML_PROXY_URL_BASE'] ?? null;
|
|
349
411
|
_proxyUrlBaseFromEnv = !!process.env['SWML_PROXY_URL_BASE'];
|
|
350
412
|
_routingCallbacks = new Map();
|
|
413
|
+
/** The route-relative router {@link asRouter} returns, built on first use. */
|
|
414
|
+
_router;
|
|
415
|
+
/** Whether the HTTP routes enforce basic auth (credentials weren't generated). */
|
|
416
|
+
_enforceAuth = false;
|
|
351
417
|
// SWAIG tool registry — lifted from AgentBase so any SWMLService (sidecar,
|
|
352
418
|
// non-agent verb host) can register and dispatch SWAIG functions. Stores
|
|
353
419
|
// SwaigFunction instances (the canonical rich form) or raw descriptor maps
|
|
354
420
|
// for DataMap-style functions. AgentBase reads/writes this same registry.
|
|
355
421
|
toolRegistry = new Map();
|
|
422
|
+
/** Middleware around every tool call, as {@link addToolMiddleware} adds it. */
|
|
423
|
+
_toolMiddleware = [];
|
|
424
|
+
/**
|
|
425
|
+
* The transport-retry dedupe that runs first, or null when it's off.
|
|
426
|
+
* Created here, not lazily: a per-request copy shares the service's
|
|
427
|
+
* object, so every request sees one dedupe.
|
|
428
|
+
*/
|
|
429
|
+
_toolResendDedupe = new ResendDedupe();
|
|
430
|
+
/** Whether optional tool arguments take null, as {@link setNullableOptionalParameters} sets it. */
|
|
431
|
+
_nullableOptionalParameters = false;
|
|
356
432
|
constructor(opts) {
|
|
357
433
|
// swaig-test finds services a file constructs without exporting them.
|
|
358
434
|
if (process.env['SWAIG_CLI_MODE'] === 'true')
|
|
359
435
|
cliLoadedServices.push(this);
|
|
360
436
|
this.name = opts?.name ?? 'swml-service';
|
|
361
|
-
|
|
437
|
+
// Without a trailing slash, as the reference stores it.
|
|
438
|
+
this.route = (opts?.route ?? '/').replace(/(.)\/+$/, '$1');
|
|
362
439
|
this.host = opts?.host ?? '0.0.0.0';
|
|
363
440
|
this.port = opts?.port ?? parseInt(process.env['PORT'] ?? '3000', 10);
|
|
364
441
|
// Logger — public to match Python's `self.log`
|
|
@@ -414,9 +491,44 @@ export class SWMLService {
|
|
|
414
491
|
// `service: this` is the builder's public back-reference (the reference's
|
|
415
492
|
// `SWMLBuilder(service)`), so a caller holding the builder can reach its service.
|
|
416
493
|
this.swmlBuilder = new SwmlBuilder({ service: this, ...this._builderSchemaOptions });
|
|
417
|
-
this.
|
|
418
|
-
|
|
419
|
-
|
|
494
|
+
this._enforceAuth = enforceAuth;
|
|
495
|
+
this._app = this._buildServiceApp(this._routeBase());
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Build the app serving this service's routes under `base`: the service's
|
|
499
|
+
* route for its own app ({@link getApp}), or '' for the route-relative
|
|
500
|
+
* router {@link asRouter} returns. Each is built once; routing callbacks are
|
|
501
|
+
* looked up when a request arrives, so one registered or replaced later
|
|
502
|
+
* answers through any app or router taken before.
|
|
503
|
+
*
|
|
504
|
+
* The service's own app answers everything it's sent, so its security
|
|
505
|
+
* headers, CORS and basic auth apply to every request. The router
|
|
506
|
+
* (`scoped`) is mounted among other routes, so it has no middleware for
|
|
507
|
+
* every path: the service's routes and routing callbacks carry the security
|
|
508
|
+
* headers, CORS and basic auth in their own handler chains, with CORS
|
|
509
|
+
* preflight routes, and a neighbouring route is left alone. Routes the
|
|
510
|
+
* extension hook or a caller adds to the router check auth themselves, as
|
|
511
|
+
* the reference's router handlers do.
|
|
512
|
+
*/
|
|
513
|
+
_buildServiceApp(base, scoped = false) {
|
|
514
|
+
const app = new Hono();
|
|
515
|
+
const authMw = this._enforceAuth && this.authCredentials
|
|
516
|
+
? basicAuth({
|
|
517
|
+
verifyUser: (username, password) => this.validateBasicAuth(username, password),
|
|
518
|
+
})
|
|
519
|
+
: null;
|
|
520
|
+
// Contexts whose credentials have been accepted, so a request is checked
|
|
521
|
+
// once however many guarded handlers it passes through.
|
|
522
|
+
const authed = new WeakSet();
|
|
523
|
+
const checkAuth = authMw
|
|
524
|
+
? (c, next) => authed.has(c)
|
|
525
|
+
? next()
|
|
526
|
+
: authMw(c, async () => {
|
|
527
|
+
authed.add(c);
|
|
528
|
+
await next();
|
|
529
|
+
})
|
|
530
|
+
: null;
|
|
531
|
+
const securityHeaders = async (c, next) => {
|
|
420
532
|
await next();
|
|
421
533
|
c.res.headers.set('X-Content-Type-Options', 'nosniff');
|
|
422
534
|
c.res.headers.set('X-Frame-Options', 'DENY');
|
|
@@ -424,28 +536,43 @@ export class SWMLService {
|
|
|
424
536
|
c.res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
|
425
537
|
c.res.headers.set('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
|
|
426
538
|
c.res.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
|
427
|
-
}
|
|
539
|
+
};
|
|
428
540
|
// CORS — credentials only when origin is explicitly configured (wildcard + credentials violates spec)
|
|
429
541
|
const corsOrigins = process.env['SWML_CORS_ORIGINS'];
|
|
430
542
|
const corsOrigin = corsOriginsFromEnv(corsOrigins);
|
|
431
543
|
const corsCredentials = corsOrigin !== '*';
|
|
432
|
-
|
|
433
|
-
// Basic auth
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
544
|
+
const corsMw = cors({ origin: corsOrigin, credentials: corsCredentials });
|
|
545
|
+
// Basic auth is only enforced when explicitly provided or from env, not auto-generated.
|
|
546
|
+
const guards = [
|
|
547
|
+
securityHeaders,
|
|
548
|
+
corsMw,
|
|
549
|
+
...(checkAuth ? [checkAuth] : []),
|
|
550
|
+
];
|
|
551
|
+
// The service's own routes: on the router, with the guards in their
|
|
552
|
+
// chain and a preflight route; on the app, under the guards for '*'.
|
|
553
|
+
const on = app.on;
|
|
554
|
+
const own = (methods, path, handler) => {
|
|
555
|
+
if (scoped) {
|
|
556
|
+
on(methods, path, ...guards, handler);
|
|
557
|
+
on(['OPTIONS'], path, corsMw);
|
|
558
|
+
}
|
|
559
|
+
else {
|
|
560
|
+
on(methods, path, handler);
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
if (!scoped)
|
|
564
|
+
for (const guard of guards)
|
|
565
|
+
app.use('*', guard);
|
|
439
566
|
// Health endpoints
|
|
440
|
-
|
|
441
|
-
|
|
567
|
+
own(['GET'], '/health', (c) => c.json({ status: 'ok' }));
|
|
568
|
+
own(['GET'], '/ready', (c) => c.json({ status: 'ready' }));
|
|
442
569
|
// Main SWML endpoint — serves on both GET and POST
|
|
443
570
|
const handler = async (c) => {
|
|
444
571
|
const { bodyParams, headers } = await this._readRequest(c);
|
|
445
572
|
return c.json(await this._documentForRequest(c, bodyParams, headers));
|
|
446
573
|
};
|
|
447
|
-
const routePath =
|
|
448
|
-
const swaigPath =
|
|
574
|
+
const routePath = base || '/';
|
|
575
|
+
const swaigPath = `${base}/swaig`;
|
|
449
576
|
// SWAIG endpoint — GET returns the rendered SWML doc (sidecar / non-agent
|
|
450
577
|
// services use the document as-is; AgentBase overrides via render hook),
|
|
451
578
|
// POST validates and dispatches via onFunctionCall. Subclasses may
|
|
@@ -499,13 +626,69 @@ export class SWMLService {
|
|
|
499
626
|
return c.json(new FunctionResult(result).toDict());
|
|
500
627
|
return c.json(result);
|
|
501
628
|
};
|
|
502
|
-
|
|
503
|
-
|
|
629
|
+
// With or without a trailing slash, mounted or on its own.
|
|
630
|
+
for (const path of [swaigPath, `${swaigPath}/`])
|
|
631
|
+
own(['GET', 'POST'], path, swaigHandler);
|
|
504
632
|
// Subclass extension hook (AgentBase wires /post_prompt etc here).
|
|
505
|
-
this.registerAdditionalRoutes(
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
//
|
|
633
|
+
this.registerAdditionalRoutes(app);
|
|
634
|
+
for (const path of new Set([routePath, `${base}/`]))
|
|
635
|
+
own(['GET', 'POST'], path, handler);
|
|
636
|
+
// Routing callbacks last, so the SWAIG and main routes keep precedence.
|
|
637
|
+
// Looked up per request: one registered or replaced later still answers.
|
|
638
|
+
// A callback answers a request routing would send to its route under
|
|
639
|
+
// wherever the app is mounted. The guards are part of the route's chain,
|
|
640
|
+
// so Hono composes them (an app's onError included), but each runs only
|
|
641
|
+
// for a request a callback answers, so a neighbouring route is left alone.
|
|
642
|
+
const answering = new WeakMap();
|
|
643
|
+
const matchAt = (find) => async (c, next) => {
|
|
644
|
+
if (this._routingCallbacks.size > 0) {
|
|
645
|
+
const callbackFn = find(c);
|
|
646
|
+
if (callbackFn)
|
|
647
|
+
answering.set(c, callbackFn);
|
|
648
|
+
}
|
|
649
|
+
await next();
|
|
650
|
+
};
|
|
651
|
+
const whenAnswering = (mw) => (c, next) => answering.has(c) ? mw(c, next) : next();
|
|
652
|
+
const serve = async (c, next) => {
|
|
653
|
+
const callbackFn = answering.get(c);
|
|
654
|
+
if (!callbackFn)
|
|
655
|
+
return next();
|
|
656
|
+
if (c.req.method === 'OPTIONS')
|
|
657
|
+
return c.body(null, 204);
|
|
658
|
+
return this._serveRoutingCallback(c, callbackFn);
|
|
659
|
+
};
|
|
660
|
+
const callbackMethods = scoped ? ['GET', 'POST', 'OPTIONS'] : ['GET', 'POST'];
|
|
661
|
+
const callbackGuards = scoped ? guards.map(whenAnswering) : [];
|
|
662
|
+
// The mount itself, and the paths under it. Either way each callback is
|
|
663
|
+
// matched as its whole route, in registration order.
|
|
664
|
+
on(callbackMethods, '/', matchAt((c) => this._matchCallback(c, base)), ...callbackGuards, serve);
|
|
665
|
+
on(callbackMethods, '/*', matchAt((c) => this._matchCallback(c, base)), ...callbackGuards, serve);
|
|
666
|
+
return app;
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* The routing callback a request addresses, in an app built under `base`
|
|
670
|
+
* and mounted where routing matched it (the matched route's template,
|
|
671
|
+
* before its final `*`). A callback registered at `path` is served at
|
|
672
|
+
* `base + path`, as the reference's router serves it; the service's own app
|
|
673
|
+
* also serves it at `path` itself, where releases before 3.7.2 served it,
|
|
674
|
+
* and such an exact path takes precedence over another callback's
|
|
675
|
+
* `base + path`. Each candidate is matched as its whole route, mount and
|
|
676
|
+
* callback path together, by Hono's own routers, as routing matched it when
|
|
677
|
+
* callbacks were routes.
|
|
678
|
+
*/
|
|
679
|
+
_matchCallback(c, base) {
|
|
680
|
+
const mount = c.req.routePath.replace(/\/?\*$/, '').replace(/\/$/, '');
|
|
681
|
+
const path = c.req.path;
|
|
682
|
+
const paths = [...this._routingCallbacks.keys()];
|
|
683
|
+
const candidates = [...(base ? paths : []), ...paths.map((cb) => `${base}${cb}`)];
|
|
684
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
685
|
+
const candidate = candidates[i];
|
|
686
|
+
const template = `${mount}${candidate === '/' ? '' : candidate}` || '/';
|
|
687
|
+
if (routeMatches(template, path)) {
|
|
688
|
+
return this._routingCallbacks.get(paths[i % paths.length]);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return undefined;
|
|
509
692
|
}
|
|
510
693
|
// ────────────────────────────────────────────────────────────────────
|
|
511
694
|
// SWAIG tool registry (lifted from AgentBase)
|
|
@@ -520,7 +703,7 @@ export class SWMLService {
|
|
|
520
703
|
* `const` type parameters capture its literals and the handler's `args` is
|
|
521
704
|
* inferred precisely — `args.phone` typed `string`, an `enum` prop narrowed to
|
|
522
705
|
* its literal union, `required` keys present and the rest optional (see
|
|
523
|
-
*
|
|
706
|
+
* `ToolArgs`/`InferArgs`). The WRAPPED JSON-Schema object
|
|
524
707
|
* (`{ type:'object', properties }`) and a pre-built `Record` are still
|
|
525
708
|
* accepted and keep the prior open-record `args` behavior. The args type is a
|
|
526
709
|
* compile-time authoring convenience — at runtime args is the JSON the model
|
|
@@ -539,6 +722,120 @@ export class SWMLService {
|
|
|
539
722
|
this.toolRegistry.set(opts.name, fn);
|
|
540
723
|
return this;
|
|
541
724
|
}
|
|
725
|
+
/**
|
|
726
|
+
* Define a function the platform implements itself, under your own
|
|
727
|
+
* description and parameters.
|
|
728
|
+
*
|
|
729
|
+
* The platform runs its own implementation of a function whose
|
|
730
|
+
* `web_hook_url` is `"native"`, by name, and never calls a webhook. A tool
|
|
731
|
+
* defined with {@link defineTool} gets the agent's webhook URL, so it can't
|
|
732
|
+
* be one. Use this to describe a function the platform implements, such as
|
|
733
|
+
* `end_call`, in your own words, or to put it in a step's function list.
|
|
734
|
+
* @param name - The function's name, one the platform implements.
|
|
735
|
+
* @param description - The description the model reads.
|
|
736
|
+
* @param parameters - The JSON schema of its arguments, as the platform's
|
|
737
|
+
* implementation reads them. Default: none.
|
|
738
|
+
* @param fields - Other SWAIG fields, such as `fillers`. Its
|
|
739
|
+
* `web_hook_url` is always `"native"`.
|
|
740
|
+
* @returns This service, for chaining.
|
|
741
|
+
*/
|
|
742
|
+
defineNativeTool(name, description, parameters, fields = {}) {
|
|
743
|
+
return this.registerSwaigFunction({
|
|
744
|
+
function: name,
|
|
745
|
+
description,
|
|
746
|
+
parameters: parameters ?? { type: 'object', properties: {} },
|
|
747
|
+
...fields,
|
|
748
|
+
web_hook_url: NATIVE_WEBHOOK_URL,
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* Let the model send null for any tool's optional arguments.
|
|
753
|
+
*
|
|
754
|
+
* Some providers' strict schemas make every argument required and refuse a
|
|
755
|
+
* call that leaves one out, so an optional argument has to take null
|
|
756
|
+
* instead. With this on, each optional argument of every tool defined with
|
|
757
|
+
* {@link defineTool} takes null as well as its type, and a null reaches the
|
|
758
|
+
* handler as an argument not given. A tool's own `nullableOptional`
|
|
759
|
+
* overrides it. It applies when the SWML is rendered, so it covers tools
|
|
760
|
+
* defined before or after it.
|
|
761
|
+
* @param enabled - `true` to turn it on, `false` to turn it off.
|
|
762
|
+
* @returns This service, for chaining.
|
|
763
|
+
*/
|
|
764
|
+
setNullableOptionalParameters(enabled = true) {
|
|
765
|
+
this._nullableOptionalParameters = enabled;
|
|
766
|
+
return this;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* The agent's default for whether optional tool arguments take null.
|
|
770
|
+
* @internal
|
|
771
|
+
*/
|
|
772
|
+
_nullableOptionalDefault() {
|
|
773
|
+
return this._nullableOptionalParameters;
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Run `middleware` around every tool call, after any added before it.
|
|
777
|
+
*
|
|
778
|
+
* A middleware is `(name, args, rawData, callNext)`. It runs before the
|
|
779
|
+
* handler and calls `callNext(args, rawData)` for the rest of the chain and
|
|
780
|
+
* the handler, possibly with changed arguments. What it returns is the
|
|
781
|
+
* call's result: the handler's, a changed one, or its own without calling
|
|
782
|
+
* `callNext`, as a `FunctionResult` or an object. `callNext` returns a
|
|
783
|
+
* promise. One that throws {@link ToolRefusal} declines the call, and any
|
|
784
|
+
* other error gives the model the unknown-outcome result.
|
|
785
|
+
*
|
|
786
|
+
* It covers tools defined with {@link defineTool}, not DataMap or native
|
|
787
|
+
* tools, which run on the platform. Handlers for different calls interleave
|
|
788
|
+
* at every `await`, so guard shared state.
|
|
789
|
+
* @param middleware - The middleware.
|
|
790
|
+
* @returns This service, for chaining.
|
|
791
|
+
*
|
|
792
|
+
* @example
|
|
793
|
+
* ```ts
|
|
794
|
+
* agent.addToolMiddleware(async (name, args, rawData, callNext) => {
|
|
795
|
+
* const started = Date.now();
|
|
796
|
+
* const result = await callNext(args, rawData);
|
|
797
|
+
* console.log(`${name} took ${Date.now() - started} ms`);
|
|
798
|
+
* return result;
|
|
799
|
+
* });
|
|
800
|
+
* ```
|
|
801
|
+
*/
|
|
802
|
+
addToolMiddleware(middleware) {
|
|
803
|
+
// Rebind rather than push: a per-request copy shares this array
|
|
804
|
+
this._toolMiddleware = [...this._toolMiddleware, middleware];
|
|
805
|
+
return this;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Turn the dedupe of transport retries on or off. It's on by default.
|
|
809
|
+
*
|
|
810
|
+
* SignalWire sends a tool request again, with the same body, after a
|
|
811
|
+
* timeout, a failed connection or a 5xx, so a slow tool can run twice. The
|
|
812
|
+
* dedupe answers a retry with the first attempt's result: one that arrives
|
|
813
|
+
* while the first is still running waits for it. A retry is a call with the
|
|
814
|
+
* same `call_id`, `tool_call_id` and function name; a call the model makes
|
|
815
|
+
* again has a new `tool_call_id` and runs, and a call without one always
|
|
816
|
+
* runs. The state lives in the process: replicas each keep their own.
|
|
817
|
+
* @param enabled - `false` to run every request, retries included.
|
|
818
|
+
* @returns This service, for chaining.
|
|
819
|
+
*/
|
|
820
|
+
setToolResendDedupe(enabled = true) {
|
|
821
|
+
if (!enabled)
|
|
822
|
+
this._toolResendDedupe = null;
|
|
823
|
+
else
|
|
824
|
+
this._toolResendDedupe ??= new ResendDedupe();
|
|
825
|
+
return this;
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* The middleware around a call of `fn`, outermost first: the resend
|
|
829
|
+
* dedupe, the service's, then the tool's own.
|
|
830
|
+
* @internal
|
|
831
|
+
*/
|
|
832
|
+
_toolMiddlewareFor(fn) {
|
|
833
|
+
return [
|
|
834
|
+
...(this._toolResendDedupe ? [this._toolResendDedupe.middleware] : []),
|
|
835
|
+
...this._toolMiddleware,
|
|
836
|
+
...fn.middleware,
|
|
837
|
+
];
|
|
838
|
+
}
|
|
542
839
|
/**
|
|
543
840
|
* Register a SwaigFunction instance or a raw function descriptor (DataMap).
|
|
544
841
|
*
|
|
@@ -582,7 +879,9 @@ export class SWMLService {
|
|
|
582
879
|
if (!fn)
|
|
583
880
|
return null;
|
|
584
881
|
if (fn instanceof SwaigFunction) {
|
|
585
|
-
|
|
882
|
+
// Through the function's own execution, so a plain service's tools get
|
|
883
|
+
// the same vouched check, refusals and outcome rules as an agent's.
|
|
884
|
+
return fn._executeAs(undefined, args, rawData, undefined, this);
|
|
586
885
|
}
|
|
587
886
|
return null;
|
|
588
887
|
}
|
|
@@ -852,11 +1151,14 @@ export class SWMLService {
|
|
|
852
1151
|
// so /agent/handoff//next finds the callback registered at /handoff/next.
|
|
853
1152
|
const trimmed = path.replace(/\/{2,}/g, '/').replace(/^\/+|\/+$/g, '');
|
|
854
1153
|
const normalized = trimmed ? `/${trimmed}` : path.replace(/\/+$/, '');
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
return
|
|
1154
|
+
// An exact path first, then one under the service's route, as the served
|
|
1155
|
+
// routes resolve them; then any callback the path ends with.
|
|
1156
|
+
const keys = [...this._routingCallbacks.keys()];
|
|
1157
|
+
const base = this._routeBase();
|
|
1158
|
+
return (keys.find((cb) => normalized === cb) ??
|
|
1159
|
+
keys.find((cb) => normalized === `${base}${cb}`) ??
|
|
1160
|
+
keys.find((cb) => normalized.endsWith(cb)) ??
|
|
1161
|
+
null);
|
|
860
1162
|
}
|
|
861
1163
|
/**
|
|
862
1164
|
* Validate HTTP basic-auth from a plain headers dict (the primitive analog of
|
|
@@ -912,29 +1214,30 @@ export class SWMLService {
|
|
|
912
1214
|
normalized = `/${normalized}`;
|
|
913
1215
|
}
|
|
914
1216
|
this.log.info(`Registering routing callback at ${normalized}`);
|
|
1217
|
+
// The apps look callbacks up per request, so it answers from now on.
|
|
915
1218
|
this._routingCallbacks.set(normalized, callbackFn);
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
this.log.error(`error_in_routing_callback error=${err instanceof Error ? err.message : String(err)}`);
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Answer a request for a routing callback: run it (awaited) for a POST with
|
|
1222
|
+
* a body, redirect with 307 when it returns a route, and otherwise serve the
|
|
1223
|
+
* SWML for the request as the main route does, as the reference does. Auth
|
|
1224
|
+
* is the app's middleware.
|
|
1225
|
+
*/
|
|
1226
|
+
async _serveRoutingCallback(c, callbackFn) {
|
|
1227
|
+
const { bodyParams, headers } = await this._readRequest(c);
|
|
1228
|
+
if (c.req.method === 'POST' && Object.keys(bodyParams).length > 0) {
|
|
1229
|
+
try {
|
|
1230
|
+
const route = await callbackFn(bodyParams, headers);
|
|
1231
|
+
if (route != null) {
|
|
1232
|
+
this.log.info(`routing_request route=${route}`);
|
|
1233
|
+
return c.redirect(route, 307);
|
|
932
1234
|
}
|
|
933
1235
|
}
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
1236
|
+
catch (err) {
|
|
1237
|
+
this.log.error(`error_in_routing_callback error=${err instanceof Error ? err.message : String(err)}`);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
return c.json(await this._documentForRequest(c, bodyParams, headers));
|
|
938
1241
|
}
|
|
939
1242
|
/** The body (for a POST) and headers of a served request. */
|
|
940
1243
|
async _readRequest(c) {
|
|
@@ -1019,10 +1322,10 @@ export class SWMLService {
|
|
|
1019
1322
|
*
|
|
1020
1323
|
* Default implementation returns `null` (no-op).
|
|
1021
1324
|
*
|
|
1022
|
-
* @param
|
|
1023
|
-
* @param
|
|
1024
|
-
* @param
|
|
1025
|
-
* @param
|
|
1325
|
+
* @param _queryParams - URL query parameters from the request.
|
|
1326
|
+
* @param _bodyParams - Parsed POST body (empty object for GET requests).
|
|
1327
|
+
* @param _headers - HTTP request headers.
|
|
1328
|
+
* @param _callbackPath - The callback sub-path being handled, if any.
|
|
1026
1329
|
* @returns A `SwmlBuilder` whose document is sent as the response, or
|
|
1027
1330
|
* `null` to delegate to the next handler in the chain.
|
|
1028
1331
|
*/
|
|
@@ -1076,15 +1379,23 @@ export class SWMLService {
|
|
|
1076
1379
|
/**
|
|
1077
1380
|
* Get a router to embed this service's routes in a host web app.
|
|
1078
1381
|
*
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1382
|
+
* The router's routes are relative to the service's route, as Python's
|
|
1383
|
+
* `as_router()` is: the host mounts it with
|
|
1384
|
+
* `hostApp.route(path, service.asRouter())`, and the service's document is
|
|
1385
|
+
* served at `path`, its SWAIG endpoint at `path/swaig` and its routing
|
|
1386
|
+
* callbacks under `path`, with its own basic auth. The named
|
|
1387
|
+
* {@link HostAppRouter} type is the cross-port "embed my routes in a host
|
|
1388
|
+
* app" contract.
|
|
1083
1389
|
*
|
|
1084
1390
|
* @returns A mountable Hono sub-app carrying this service's routes.
|
|
1085
1391
|
*/
|
|
1086
1392
|
asRouter() {
|
|
1087
|
-
|
|
1393
|
+
this._router ??= this._buildServiceApp('', true);
|
|
1394
|
+
return this._router;
|
|
1395
|
+
}
|
|
1396
|
+
/** The service's route as a path prefix: '' for '/', else without a trailing slash. */
|
|
1397
|
+
_routeBase() {
|
|
1398
|
+
return this.route === '/' ? '' : this.route.replace(/\/+$/, '');
|
|
1088
1399
|
}
|
|
1089
1400
|
/**
|
|
1090
1401
|
* Start the HTTP server. Canonical entrypoint, matching Python's
|
|
@@ -1144,7 +1455,7 @@ export class SWMLService {
|
|
|
1144
1455
|
key: readFileSync(effectiveSslKey, 'utf-8'),
|
|
1145
1456
|
};
|
|
1146
1457
|
this.log.info(`${this.name} starting on https://${h}:${p}${this.route} (SSL enabled)`);
|
|
1147
|
-
const listener = getRequestListener(this.
|
|
1458
|
+
const listener = getRequestListener((req, env) => this.getApp().fetch(req, env));
|
|
1148
1459
|
this._server = createServer(serverOpts, listener);
|
|
1149
1460
|
this._server.listen(p, h);
|
|
1150
1461
|
}
|
|
@@ -1152,7 +1463,12 @@ export class SWMLService {
|
|
|
1152
1463
|
// HTTP mode
|
|
1153
1464
|
const { serve } = await import('@hono/node-server');
|
|
1154
1465
|
this.log.info(`${this.name} starting on http://${h}:${p}${this.route}`);
|
|
1155
|
-
this._server = serve({
|
|
1466
|
+
this._server = serve({
|
|
1467
|
+
// The current app: a routing callback added later may rebuild it.
|
|
1468
|
+
fetch: (req, env) => this.getApp().fetch(req, env),
|
|
1469
|
+
port: p,
|
|
1470
|
+
hostname: h,
|
|
1471
|
+
});
|
|
1156
1472
|
}
|
|
1157
1473
|
}
|
|
1158
1474
|
/**
|