twelveai 0.3.0 → 0.4.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/cli.js ADDED
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ TwelveAI
4
+ } from "./chunk-6RZKLIGP.js";
5
+
6
+ // src/cli.ts
7
+ import { readFileSync } from "fs";
8
+ var HELP = `twelveai <command> [args]
9
+
10
+ Conversation
11
+ chat "<message>" [--customer <id>] [--sandbox] [--reasoning off|auto|always]
12
+ classify "<message>" [--reasoning off|auto|always]
13
+
14
+ Manage (everything the console does)
15
+ agents list | create --file <agent.json> | enable <intent> | disable <intent> | delete <intent>
16
+ tools list | create --file <tool.json> | bind <name> --file <binding.json> | test <name>
17
+ plugins list | install <id> | uninstall <id>
18
+ customers list | set <externalId> [--tier <tier>] [--name <name>] [--email <email>]
19
+ settings get | set --file <settings.json>
20
+ billing (show balance) | topup <amountNgn>
21
+ usage (summary) | requests [--limit <n>] | request <id>
22
+ manifest (the per-agent tool-call contract)
23
+
24
+ Auth: set TWELVE_API_KEY (and optionally TWELVE_BASE_URL).`;
25
+ function flag(args, name) {
26
+ const i = args.indexOf(`--${name}`);
27
+ return i >= 0 ? args[i + 1] : void 0;
28
+ }
29
+ var has = (args, name) => args.includes(`--${name}`);
30
+ var positional = (args) => args.filter((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--")));
31
+ async function runCli(argv, deps) {
32
+ const [cmd, ...rest] = argv;
33
+ if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
34
+ deps.log(HELP);
35
+ return 0;
36
+ }
37
+ const apiKey = deps.env.TWELVE_API_KEY;
38
+ if (!apiKey) {
39
+ deps.error("Set TWELVE_API_KEY to use the CLI (find yours in the console under Settings).");
40
+ return 1;
41
+ }
42
+ const twelve = deps.client ?? new TwelveAI({ apiKey, baseUrl: deps.env.TWELVE_BASE_URL });
43
+ const m = twelve.manage;
44
+ const json = (v) => deps.log(JSON.stringify(v, null, 2));
45
+ const loadJson = (label) => {
46
+ const file = flag(rest, "file");
47
+ if (!file) {
48
+ deps.error(`--file <${label}.json> is required.`);
49
+ return null;
50
+ }
51
+ try {
52
+ return JSON.parse(deps.readFile(file));
53
+ } catch (e) {
54
+ deps.error(`Could not read ${file}: ${e.message}`);
55
+ return null;
56
+ }
57
+ };
58
+ const done = (r) => r.ok ? 0 : 1;
59
+ const pos = positional(rest);
60
+ const sub = pos[0];
61
+ switch (cmd) {
62
+ case "chat": {
63
+ if (!sub) return deps.error('Usage: twelveai chat "<message>"'), 1;
64
+ const r = await twelve.chat({
65
+ message: sub,
66
+ customerId: flag(rest, "customer"),
67
+ sandbox: has(rest, "sandbox") || void 0,
68
+ reasoning: flag(rest, "reasoning")
69
+ });
70
+ json(r);
71
+ return done(r);
72
+ }
73
+ case "classify": {
74
+ if (!sub) return deps.error('Usage: twelveai classify "<message>"'), 1;
75
+ const r = await twelve.classify({ message: sub, reasoning: flag(rest, "reasoning") });
76
+ json(r);
77
+ return done(r);
78
+ }
79
+ case "agents": {
80
+ if (sub === "list" || !sub) return json(await m.agents.list()), 0;
81
+ if (sub === "create") {
82
+ const b = loadJson("agent");
83
+ if (!b) return 1;
84
+ const r = await m.agents.create(b);
85
+ json(r);
86
+ return done(r);
87
+ }
88
+ if (sub === "enable" && pos[1]) {
89
+ const r = await m.agents.enable(pos[1]);
90
+ json(r);
91
+ return done(r);
92
+ }
93
+ if (sub === "disable" && pos[1]) {
94
+ const r = await m.agents.disable(pos[1]);
95
+ json(r);
96
+ return done(r);
97
+ }
98
+ if (sub === "delete" && pos[1]) {
99
+ const r = await m.agents.delete(pos[1]);
100
+ json(r);
101
+ return done(r);
102
+ }
103
+ deps.error("Usage: twelveai agents list | create --file a.json | enable <intent> | disable <intent> | delete <intent>");
104
+ return 1;
105
+ }
106
+ case "tools": {
107
+ if (sub === "list" || !sub) return json(await m.tools.list()), 0;
108
+ if (sub === "create") {
109
+ const b = loadJson("tool");
110
+ if (!b) return 1;
111
+ const r = await m.tools.create(b);
112
+ json(r);
113
+ return done(r);
114
+ }
115
+ if (sub === "bind" && pos[1]) {
116
+ const b = loadJson("binding");
117
+ if (!b) return 1;
118
+ const r = await m.tools.bind(pos[1], b);
119
+ json(r);
120
+ return done(r);
121
+ }
122
+ if (sub === "test" && pos[1]) {
123
+ const r = await m.tools.test(pos[1]);
124
+ json(r);
125
+ return done(r);
126
+ }
127
+ deps.error("Usage: twelveai tools list | create --file t.json | bind <name> --file b.json | test <name>");
128
+ return 1;
129
+ }
130
+ case "plugins": {
131
+ if (sub === "list" || !sub) return json(await m.plugins.list()), 0;
132
+ if (sub === "install" && pos[1]) {
133
+ const r = await m.plugins.install(pos[1]);
134
+ json(r);
135
+ return done(r);
136
+ }
137
+ if (sub === "uninstall" && pos[1]) {
138
+ const r = await m.plugins.uninstall(pos[1]);
139
+ json(r);
140
+ return done(r);
141
+ }
142
+ deps.error("Usage: twelveai plugins list | install <id> | uninstall <id>");
143
+ return 1;
144
+ }
145
+ case "customers": {
146
+ if (sub === "list" || !sub) return json(await m.customers.list({ limit: Number(flag(rest, "limit")) || 100 })), 0;
147
+ if (sub === "set" && pos[1]) {
148
+ const r = await m.customers.upsert({ externalId: pos[1], tier: flag(rest, "tier"), name: flag(rest, "name"), email: flag(rest, "email") });
149
+ json(r);
150
+ return done(r);
151
+ }
152
+ deps.error("Usage: twelveai customers list | set <externalId> --tier <tier>");
153
+ return 1;
154
+ }
155
+ case "settings": {
156
+ if (sub === "get" || !sub) return json(await m.settings.get()), 0;
157
+ if (sub === "set") {
158
+ const b = loadJson("settings");
159
+ if (!b) return 1;
160
+ const r = await m.settings.update(b);
161
+ json(r);
162
+ return done(r);
163
+ }
164
+ deps.error("Usage: twelveai settings get | set --file settings.json");
165
+ return 1;
166
+ }
167
+ case "billing":
168
+ return json(await m.billing.get()), 0;
169
+ case "topup": {
170
+ const amount = Number(sub);
171
+ if (!amount || amount < 5e3) return deps.error("Usage: twelveai topup <amountNgn> (minimum 5000)"), 1;
172
+ const r = await m.billing.topup(amount, flag(rest, "email"));
173
+ json(r);
174
+ return done(r);
175
+ }
176
+ case "usage":
177
+ return json(await m.usage.summary()), 0;
178
+ case "requests":
179
+ return json(await m.usage.events(Number(flag(rest, "limit")) || 20)), 0;
180
+ case "request": {
181
+ if (!sub) return deps.error("Usage: twelveai request <id>"), 1;
182
+ return json(await m.usage.event(sub)), 0;
183
+ }
184
+ case "manifest":
185
+ return json(await m.manifest()), 0;
186
+ default:
187
+ deps.error(`Unknown command "${cmd}".
188
+
189
+ ${HELP}`);
190
+ return 1;
191
+ }
192
+ }
193
+ var isMain = process.argv[1]?.endsWith("cli.js") || process.argv[1]?.endsWith("twelveai");
194
+ if (isMain) {
195
+ runCli(process.argv.slice(2), {
196
+ env: process.env,
197
+ log: (s) => console.log(s),
198
+ error: (s) => console.error(s),
199
+ readFile: (p) => readFileSync(p, "utf8")
200
+ }).then((code) => process.exit(code));
201
+ }
202
+ export {
203
+ runCli
204
+ };
@@ -0,0 +1,325 @@
1
+ /** Shared request/response types for the TwelveAI chat API. */
2
+ interface TwelveAIOptions {
3
+ /** Your workspace API key (sk_live_... / sk_test_...). */
4
+ apiKey: string;
5
+ /** Engine base URL. Defaults to the hosted platform. */
6
+ baseUrl?: string;
7
+ /**
8
+ * Auth your server adds when the SDK performs client-fetch hand-offs against
9
+ * YOUR OWN API (the engine hands the resolved request back without any
10
+ * credentials). Static headers, or a function returning them per request.
11
+ */
12
+ clientAuth?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
13
+ /** Custom fetch implementation (tests, polyfills). Defaults to global fetch. */
14
+ fetch?: typeof globalThis.fetch;
15
+ /** Max auto-resume rounds for client-fetch hand-offs per chat() call. Default 3. */
16
+ maxHandoffRounds?: number;
17
+ }
18
+ interface Attachment {
19
+ /** Public URL, or a data: URL. */
20
+ url?: string;
21
+ /** Base64 content (alternative to url). */
22
+ data?: string;
23
+ mediaType?: string;
24
+ /** A WhatsApp media id, if the engine should fetch it via your connected WhatsApp. */
25
+ whatsappMediaId?: string;
26
+ }
27
+ interface ChatInput {
28
+ /** The end user's message. Optional when resuming or sending only attachments. */
29
+ message?: string;
30
+ /** Your id for this end user (alias: userId). Required for customer-scoped agents. */
31
+ customerId?: string;
32
+ /** Continue an existing conversation with the token from the previous turn. */
33
+ continuation?: string;
34
+ /** The user approved a pending action (PIN/OTP collected on your side). */
35
+ confirmed?: boolean;
36
+ /** Sandbox: tools return sample data; nothing real is called or moved. */
37
+ sandbox?: boolean;
38
+ channel?: string;
39
+ /** Force a specific agent instead of routing. */
40
+ intent?: string;
41
+ /** Customer tier to sync for this turn's caps. */
42
+ tier?: string;
43
+ /** Routing reasoning: 'off' | 'auto' (default) | 'always'. */
44
+ reasoning?: 'off' | 'auto' | 'always';
45
+ /**
46
+ * Short-lived end-user session token, forwarded verbatim on tool bindings
47
+ * with auth type 'customer_token'. Never stored by the engine.
48
+ */
49
+ customerToken?: string;
50
+ /** Images / voice notes attached to this turn. */
51
+ attachments?: Attachment[];
52
+ metadata?: Record<string, unknown>;
53
+ }
54
+ interface ToolCall {
55
+ name: string;
56
+ arguments: Record<string, unknown>;
57
+ result: unknown;
58
+ }
59
+ interface HandoffRequest {
60
+ method: string;
61
+ url: string;
62
+ headers?: Record<string, string>;
63
+ body?: Record<string, unknown>;
64
+ }
65
+ interface PendingToolCall {
66
+ id: string;
67
+ name: string;
68
+ arguments: Record<string, unknown>;
69
+ /** Client-fetch hand-off: the resolved request your server should perform. */
70
+ request?: HandoffRequest;
71
+ }
72
+ interface ToolResult {
73
+ id: string;
74
+ result: unknown;
75
+ }
76
+ interface ChatResponse {
77
+ ok: boolean;
78
+ sandbox?: boolean;
79
+ /** The assistant's reply to show the user. */
80
+ message: string | null;
81
+ intent: string | null;
82
+ toolCalls: ToolCall[];
83
+ /** A write awaiting the user's confirmation (resend with confirmed: true). */
84
+ pendingConfirmation: {
85
+ tool: string;
86
+ arguments: Record<string, unknown>;
87
+ } | null;
88
+ /**
89
+ * Client-executed tool calls YOUR system must run. With auto-execution on
90
+ * (the default), read hand-offs are already completed by the SDK; anything
91
+ * left here is yours to handle (typically a money move awaiting PIN).
92
+ */
93
+ pendingToolCalls: PendingToolCall[] | null;
94
+ /** Pass this back on the next turn to continue the conversation. */
95
+ continuation: string | null;
96
+ escalated?: boolean;
97
+ policy?: string | null;
98
+ autonomy?: string | null;
99
+ fee?: {
100
+ feeNgn: number;
101
+ amountNgn: number;
102
+ totalNgn: number;
103
+ } | null;
104
+ usage?: {
105
+ inputTokens: number;
106
+ outputTokens: number;
107
+ };
108
+ billing?: Record<string, unknown>;
109
+ latencyMs?: number;
110
+ metadata?: Record<string, unknown>;
111
+ error?: string;
112
+ /** HTTP status of the underlying call. */
113
+ status: number;
114
+ /** Hand-offs the SDK auto-executed to complete this turn (for observability). */
115
+ executedHandoffs?: Array<{
116
+ name: string;
117
+ method: string;
118
+ url: string;
119
+ ok: boolean;
120
+ }>;
121
+ }
122
+ /**
123
+ * Executor for one client-fetch hand-off. Return the tool result the engine
124
+ * resumes with. The default executor performs `call.request` with your
125
+ * `clientAuth` headers and returns `{ ok, data }`.
126
+ */
127
+ type HandoffExecutor = (call: PendingToolCall) => Promise<unknown>;
128
+ interface ClassifyResponse {
129
+ ok: boolean;
130
+ /** The winning agent intent, or null when nothing matched. */
131
+ intent: string | null;
132
+ label: string | null;
133
+ /** Deterministic confidence in [0, 0.95]; 0 = no match. */
134
+ confidence: number;
135
+ alternatives: Array<{
136
+ intent: string;
137
+ label: string;
138
+ confidence?: number;
139
+ matchedKeywords?: string[];
140
+ }>;
141
+ /** The exact keywords that selected the winning intent (explainability). */
142
+ matchedKeywords?: string[];
143
+ /** Raw keyword-hit count for the winner, and its lead over the runner-up. */
144
+ score?: number;
145
+ margin?: number;
146
+ /** True when the winning intent is classifier-only (your systems handle it). */
147
+ classifyOnly?: boolean;
148
+ /** Extracted entities: amount, account_number, phone, bank {name, code}, currency. */
149
+ entities: Record<string, unknown>;
150
+ status: number;
151
+ error?: string;
152
+ }
153
+
154
+ /**
155
+ * Management API - everything the console can do, callable from code. Thin,
156
+ * typed-enough wrappers over the engine's management endpoints, all
157
+ * authenticated with the same x-api-key as chat. Every method resolves to
158
+ * `{ ok, status, ...payload }` and never throws on HTTP errors.
159
+ */
160
+ interface ManageResult {
161
+ ok: boolean;
162
+ status: number;
163
+ error?: string;
164
+ [key: string]: unknown;
165
+ }
166
+ interface CreateAgentInput {
167
+ intent: string;
168
+ label?: string;
169
+ keywords: string[];
170
+ /** With instructions (and optionally tools) this creates a FULL chat agent; without, a classifier-only intent. */
171
+ systemPrompt?: string;
172
+ tools?: string[];
173
+ requiresCustomer?: boolean;
174
+ }
175
+ interface CreateToolInput {
176
+ name: string;
177
+ description: string;
178
+ sideEffect: 'read' | 'write';
179
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
180
+ /** {placeholders} become the tool's arguments; {customer_id} is filled per turn. */
181
+ url: string;
182
+ execution?: 'hosted' | 'client';
183
+ /** A real example response - drives result parsing and the sandbox. */
184
+ sampleResponse?: unknown;
185
+ }
186
+ interface BindToolInput {
187
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
188
+ url: string;
189
+ resultPath?: string | null;
190
+ sampleResponse?: unknown;
191
+ execution?: 'hosted' | 'client';
192
+ auth?: Record<string, unknown>;
193
+ }
194
+ type Request = (method: string, path: string, body?: Record<string, unknown>) => Promise<ManageResult>;
195
+ /** Build the management namespaces over one authenticated request function. */
196
+ declare function buildManage(request: Request): {
197
+ agents: {
198
+ list: () => Promise<ManageResult>;
199
+ create: (input: CreateAgentInput) => Promise<ManageResult>;
200
+ update: (intent: string, patch: Record<string, unknown>) => Promise<ManageResult>;
201
+ enable: (intent: string) => Promise<ManageResult>;
202
+ disable: (intent: string) => Promise<ManageResult>;
203
+ delete: (intent: string) => Promise<ManageResult>;
204
+ };
205
+ tools: {
206
+ list: () => Promise<ManageResult>;
207
+ create: (input: CreateToolInput) => Promise<ManageResult>;
208
+ bind: (name: string, binding: BindToolInput) => Promise<ManageResult>;
209
+ test: (name: string) => Promise<ManageResult>;
210
+ importOpenApi: (input: {
211
+ url?: string;
212
+ spec?: unknown;
213
+ execution?: "hosted" | "client";
214
+ dryRun?: boolean;
215
+ auth?: Record<string, unknown>;
216
+ }) => Promise<ManageResult>;
217
+ };
218
+ plugins: {
219
+ list: () => Promise<ManageResult>;
220
+ install: (id: string) => Promise<ManageResult>;
221
+ uninstall: (id: string) => Promise<ManageResult>;
222
+ };
223
+ customers: {
224
+ list: (opts?: {
225
+ limit?: number;
226
+ range?: string;
227
+ }) => Promise<ManageResult>;
228
+ upsert: (input: {
229
+ externalId: string;
230
+ tier?: string | null;
231
+ name?: string;
232
+ email?: string;
233
+ status?: string;
234
+ }) => Promise<ManageResult>;
235
+ get: (externalId: string) => Promise<ManageResult>;
236
+ };
237
+ settings: {
238
+ get: () => Promise<ManageResult>;
239
+ update: (patch: Record<string, unknown>) => Promise<ManageResult>;
240
+ };
241
+ billing: {
242
+ get: () => Promise<ManageResult>;
243
+ topup: (amountNgn: number, email?: string) => Promise<ManageResult>;
244
+ };
245
+ usage: {
246
+ summary: () => Promise<ManageResult>;
247
+ events: (limit?: number) => Promise<ManageResult>;
248
+ event: (id: number | string) => Promise<ManageResult>;
249
+ analytics: (days?: number) => Promise<ManageResult>;
250
+ };
251
+ manifest: () => Promise<ManageResult>;
252
+ };
253
+ type Manage = ReturnType<typeof buildManage>;
254
+
255
+ /**
256
+ * The TwelveAI client. One call does the whole conversation protocol:
257
+ *
258
+ * const twelve = new TwelveAI({ apiKey: process.env.TWELVE_API_KEY! })
259
+ * const res = await twelve.chat({ message: "what's my balance?", customerId: 'cus_123' })
260
+ * console.log(res.message)
261
+ *
262
+ * Client-fetch hand-offs (tools configured as "my app calls it") are executed
263
+ * automatically against your own API - the engine never holds your credentials;
264
+ * you supply them once via `clientAuth` and the SDK completes the loop. Money
265
+ * moves are never auto-executed: they surface in `pendingToolCalls` /
266
+ * `pendingConfirmation` for your PIN flow, then you call `confirm()` or
267
+ * `resume()`.
268
+ */
269
+ declare class TwelveAI {
270
+ private readonly apiKey;
271
+ private readonly baseUrl;
272
+ private readonly fetchImpl;
273
+ private readonly clientAuth;
274
+ private readonly maxHandoffRounds;
275
+ /**
276
+ * Everything the console can do, from code: agents, tools, plugins,
277
+ * customers, settings, billing, usage. `twelve.manage.plugins.install('bills')`.
278
+ */
279
+ readonly manage: Manage;
280
+ constructor(options: TwelveAIOptions);
281
+ /**
282
+ * Low-level authenticated call to any engine endpoint. Returns
283
+ * `{ ok, status, ...payload }`; never throws on HTTP errors.
284
+ */
285
+ api(method: string, path: string, body?: Record<string, unknown>): Promise<ManageResult>;
286
+ /**
287
+ * Send one chat turn and return the completed result. Read hand-offs are
288
+ * auto-executed (see class docs); pass `autoExecute: false` to get the raw
289
+ * paused response instead, or `onHandoff` to execute them yourself.
290
+ */
291
+ chat(input: ChatInput, opts?: {
292
+ autoExecute?: boolean;
293
+ onHandoff?: HandoffExecutor;
294
+ }): Promise<ChatResponse>;
295
+ /** Resume a paused turn with tool results your system produced. */
296
+ resume(continuation: string, toolResults: ToolResult[], input?: Pick<ChatInput, 'customerId' | 'channel' | 'sandbox' | 'customerToken'>): Promise<ChatResponse>;
297
+ /**
298
+ * Approve a pending action (after your PIN/OTP step) - resends the turn with
299
+ * `confirmed: true` so the engine proceeds.
300
+ */
301
+ confirm(continuation: string, input?: Omit<ChatInput, 'continuation' | 'confirmed'>): Promise<ChatResponse>;
302
+ /**
303
+ * Level-0 integration: classify a message WITHOUT running the conversation.
304
+ * Returns the intent, a deterministic confidence score, and cheap extracted
305
+ * entities (amount / account number / phone) - you keep your existing flows
306
+ * and make the call yourself. Free: no tools run, nothing is stored.
307
+ */
308
+ classify(input: {
309
+ message: string;
310
+ reasoning?: 'off' | 'auto' | 'always';
311
+ }): Promise<ClassifyResponse>;
312
+ private chatBody;
313
+ private post;
314
+ /**
315
+ * Execute client-fetch hand-offs and resume until the turn completes. Only
316
+ * calls that carry a resolved `request` are auto-executed - a hand-off
317
+ * without one (e.g. a money move awaiting your PIN flow) stops the loop and
318
+ * is returned to you untouched.
319
+ */
320
+ private completeHandoffs;
321
+ /** Default hand-off executor: perform the request with your clientAuth headers. */
322
+ private performHandoff;
323
+ }
324
+
325
+ export { type Attachment as A, type BindToolInput as B, type ChatInput as C, type HandoffExecutor as H, type Manage as M, type PendingToolCall as P, TwelveAI as T, type ChatResponse as a, type ClassifyResponse as b, type CreateAgentInput as c, type CreateToolInput as d, type HandoffRequest as e, type ManageResult as f, type ToolCall as g, type ToolResult as h, type TwelveAIOptions as i, buildManage as j };