@cubos/agent-sdk 0.0.1159021 → 0.0.1159588

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.
@@ -1,7 +1,7 @@
1
1
  import type { Transport } from "../http.js";
2
2
  import type { Schemas } from "../schemas.js";
3
3
  /** `Channel` and its Create/Update inputs are discriminated unions over `type`
4
- * (telegram, whapi, whatsapp, external), so no per-type methods are needed. */
4
+ * (telegram, whatsapp, external), so no per-type methods are needed. */
5
5
  export declare function channelsApi(t: Transport, tenantSlug: string): {
6
6
  list: (signal?: AbortSignal) => Promise<(({
7
7
  agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
@@ -28,20 +28,6 @@ export declare function channelsApi(t: Transport, tenantSlug: string): {
28
28
  user_onboarding_mode: string;
29
29
  } & {
30
30
  type: "telegram";
31
- }) | ({
32
- agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
33
- created_at: string;
34
- default_user_role_slugs: string[];
35
- disabled_at: string | null;
36
- health_status: string | null;
37
- id: string;
38
- phone_number: string | null;
39
- profile_name: string | null;
40
- slug: string;
41
- user_onboarding_mode: string;
42
- whapi_channel_id: string | null;
43
- } & {
44
- type: "whapi";
45
31
  }) | ({
46
32
  agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
47
33
  banned_at: string | null;
@@ -84,20 +70,6 @@ export declare function channelsApi(t: Transport, tenantSlug: string): {
84
70
  user_onboarding_mode: string;
85
71
  } & {
86
72
  type: "telegram";
87
- }) | ({
88
- agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
89
- created_at: string;
90
- default_user_role_slugs: string[];
91
- disabled_at: string | null;
92
- health_status: string | null;
93
- id: string;
94
- phone_number: string | null;
95
- profile_name: string | null;
96
- slug: string;
97
- user_onboarding_mode: string;
98
- whapi_channel_id: string | null;
99
- } & {
100
- type: "whapi";
101
73
  }) | ({
102
74
  agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
103
75
  banned_at: string | null;
@@ -128,20 +100,6 @@ export declare function channelsApi(t: Transport, tenantSlug: string): {
128
100
  user_onboarding_mode: string;
129
101
  } & {
130
102
  type: "telegram";
131
- }) | ({
132
- agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
133
- created_at: string;
134
- default_user_role_slugs: string[];
135
- disabled_at: string | null;
136
- health_status: string | null;
137
- id: string;
138
- phone_number: string | null;
139
- profile_name: string | null;
140
- slug: string;
141
- user_onboarding_mode: string;
142
- whapi_channel_id: string | null;
143
- } & {
144
- type: "whapi";
145
103
  }) | ({
146
104
  agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
147
105
  banned_at: string | null;
@@ -198,20 +156,6 @@ export declare function channelsApi(t: Transport, tenantSlug: string): {
198
156
  user_onboarding_mode: string;
199
157
  } & {
200
158
  type: "telegram";
201
- }) | ({
202
- agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
203
- created_at: string;
204
- default_user_role_slugs: string[];
205
- disabled_at: string | null;
206
- health_status: string | null;
207
- id: string;
208
- phone_number: string | null;
209
- profile_name: string | null;
210
- slug: string;
211
- user_onboarding_mode: string;
212
- whapi_channel_id: string | null;
213
- } & {
214
- type: "whapi";
215
159
  }) | ({
216
160
  agent: import("../generated/schema.js").components["schemas"]["AgentRef"];
217
161
  banned_at: string | null;
@@ -3615,7 +3615,7 @@ export interface paths {
3615
3615
  };
3616
3616
  /**
3617
3617
  * List channels
3618
- * @description Lists every channel in the tenant, ordered by slug. Each item is a union discriminated by `type` (`telegram`, `whapi`, `whatsapp`, or `external`) carrying that variant's cached identity (Telegram bot fields, Whapi phone/health/profile, native WhatsApp pairing/profile, external connection-secret hint). Bot tokens and connection secrets are never returned.
3618
+ * @description Lists every channel in the tenant, ordered by slug. Each item is a union discriminated by `type` (`telegram`, `whatsapp`, or `external`) carrying that variant's cached identity (Telegram bot fields, native WhatsApp pairing/profile, external connection-secret hint). Bot tokens and connection secrets are never returned.
3619
3619
  */
3620
3620
  get: {
3621
3621
  parameters: {
@@ -3660,7 +3660,7 @@ export interface paths {
3660
3660
  put?: never;
3661
3661
  /**
3662
3662
  * Create channel
3663
- * @description Creates a channel bound to an agent. The body is discriminated by `type`: `telegram` and `whapi` probe the provider with the supplied token before persisting (returns 502 if the provider rejects or is unreachable) and cache the resulting identity, storing the token encrypted at rest; `external` mints a connection secret returned in plaintext once; native `whatsapp` starts unpaired and is paired separately. A duplicate slug yields 409.
3663
+ * @description Creates a channel bound to an agent. The body is discriminated by `type`: `telegram` probes the provider with the supplied token before persisting (returns 502 if the provider rejects or is unreachable) and caches the resulting identity, storing the token encrypted at rest; `external` mints a connection secret returned in plaintext once; native `whatsapp` starts unpaired and is paired separately. A duplicate slug yields 409.
3664
3664
  */
3665
3665
  post: {
3666
3666
  parameters: {
@@ -3739,7 +3739,7 @@ export interface paths {
3739
3739
  };
3740
3740
  /**
3741
3741
  * Get channel
3742
- * @description Fetches one channel by slug as a union discriminated by `type`. Carries the bound agent slug and the variant's cached identity (Telegram bot fields, Whapi phone/health/profile, native WhatsApp pairing/profile, external connection-secret hint). Bot tokens and connection secrets are never returned.
3742
+ * @description Fetches one channel by slug as a union discriminated by `type`. Carries the bound agent slug and the variant's cached identity (Telegram bot fields, native WhatsApp pairing/profile, external connection-secret hint). Bot tokens and connection secrets are never returned.
3743
3743
  */
3744
3744
  get: {
3745
3745
  parameters: {
@@ -3787,7 +3787,7 @@ export interface paths {
3787
3787
  post?: never;
3788
3788
  /**
3789
3789
  * Delete channel
3790
- * @description Permanently deletes the channel by slug, cascading to its subtype row (`channels_telegram`, `channels_whapi`, `channels_external`, `channels_whatsapp`). The bound agent and the conversations the channel produced remain. A native WhatsApp channel's linked device is removed from the phone right after, best-effort, by the instance holding its session; with no live session it stays in the phone's linked devices.
3790
+ * @description Permanently deletes the channel by slug, cascading to its subtype row (`channels_telegram`, `channels_external`, `channels_whatsapp`). The bound agent and the conversations the channel produced remain. A native WhatsApp channel's linked device is removed from the phone right after, best-effort, by the instance holding its session; with no live session it stays in the phone's linked devices.
3791
3791
  */
3792
3792
  delete: {
3793
3793
  parameters: {
@@ -3842,7 +3842,7 @@ export interface paths {
3842
3842
  head?: never;
3843
3843
  /**
3844
3844
  * Update channel
3845
- * @description Partially updates a channel; absent fields stay as they are. The body is discriminated by `type` and must match the channel's current type (400 otherwise). Supplying a new Telegram `bot_token` or Whapi `token` re-probes the provider (502 on failure) and refreshes the cached identity. The `disabled` flag toggles `disabled_at`: `true` stamps now only when not already disabled, `false` clears it. Renaming to a taken slug yields 409. The change reloads the channel worker with the new config.
3845
+ * @description Partially updates a channel; absent fields stay as they are. The body is discriminated by `type` and must match the channel's current type (400 otherwise). Supplying a new Telegram `bot_token` re-probes the provider (502 on failure) and refreshes the cached identity. The `disabled` flag toggles `disabled_at`: `true` stamps now only when not already disabled, `false` clears it. Renaming to a taken slug yields 409. The change reloads the channel worker with the new config.
3846
3846
  */
3847
3847
  patch: {
3848
3848
  parameters: {
@@ -10457,7 +10457,7 @@ export interface paths {
10457
10457
  post?: never;
10458
10458
  /**
10459
10459
  * Delete task template
10460
- * @description Deletes one task template by slug, cascading to its declared parameters and its per-agent enablement rows. Returns 404 when no template matches.
10460
+ * @description Deletes one task template by slug, cascading to its declared parameters, its per-agent enablement rows and its scheduled runs. The background tasks those runs spawned are kept, detached from the run. Returns 404 when no template matches.
10461
10461
  */
10462
10462
  delete: {
10463
10463
  parameters: {
@@ -10497,6 +10497,15 @@ export interface paths {
10497
10497
  };
10498
10498
  content?: never;
10499
10499
  };
10500
+ /** @description The background tasks of the template's scheduled runs kept being written to while it was deleted. Nothing was removed; retry after `Retry-After`. The body's `error` is `delete_contended`. */
10501
+ 503: {
10502
+ headers: {
10503
+ /** @description Seconds to wait before retrying. */
10504
+ "Retry-After"?: number;
10505
+ [name: string]: unknown;
10506
+ };
10507
+ content?: never;
10508
+ };
10500
10509
  };
10501
10510
  };
10502
10511
  options?: never;
@@ -12655,7 +12664,8 @@ export interface components {
12655
12664
  capabilities_md: string;
12656
12665
  /**
12657
12666
  * Format: int32
12658
- * @description Per-agent wall-clock cap (seconds) for the `eval` built-in tool.
12667
+ * @description Per-agent CPU-time cap (seconds) for the `eval` built-in tool; time the script
12668
+ * spends waiting on tool calls, fetches or a sleep does not count.
12659
12669
  */
12660
12670
  code_execution_timeout_seconds: number;
12661
12671
  /**
@@ -13162,9 +13172,6 @@ export interface components {
13162
13172
  Channel: (components["schemas"]["TelegramChannel"] & {
13163
13173
  /** @enum {string} */
13164
13174
  type: "telegram";
13165
- }) | (components["schemas"]["WhapiChannel"] & {
13166
- /** @enum {string} */
13167
- type: "whapi";
13168
13175
  }) | (components["schemas"]["WhatsappChannel"] & {
13169
13176
  /** @enum {string} */
13170
13177
  type: "whatsapp";
@@ -13216,7 +13223,7 @@ export interface components {
13216
13223
  slug: string;
13217
13224
  };
13218
13225
  /** @enum {string} */
13219
- ChannelType: "telegram" | "whapi" | "whatsapp" | "external";
13226
+ ChannelType: "telegram" | "whatsapp" | "external";
13220
13227
  /**
13221
13228
  * @description Body of the 409: who holds the lease and until when. A client that wants
13222
13229
  * the call sleeps until `claim_expires_at` and asks again — which is also why
@@ -13845,7 +13852,8 @@ export interface components {
13845
13852
  capabilities_md?: string | null;
13846
13853
  /**
13847
13854
  * Format: int32
13848
- * @description Per-agent wall-clock cap (seconds) for the `eval` built-in tool. Omit ⇒ default 30.
13855
+ * @description Per-agent CPU-time cap (seconds) for the `eval` built-in tool; time the script
13856
+ * spends waiting on tool calls, fetches or a sleep does not count. Omit ⇒ default 30.
13849
13857
  */
13850
13858
  code_execution_timeout_seconds?: number | null;
13851
13859
  /**
@@ -13998,9 +14006,6 @@ export interface components {
13998
14006
  CreateChannelInput: (components["schemas"]["CreateTelegramChannelInput"] & {
13999
14007
  /** @enum {string} */
14000
14008
  type: "telegram";
14001
- }) | (components["schemas"]["CreateWhapiChannelInput"] & {
14002
- /** @enum {string} */
14003
- type: "whapi";
14004
14009
  }) | (components["schemas"]["CreateWhatsappChannelInput"] & {
14005
14010
  /** @enum {string} */
14006
14011
  type: "whatsapp";
@@ -14050,9 +14055,6 @@ export interface components {
14050
14055
  CreatedChannel: (components["schemas"]["TelegramChannel"] & {
14051
14056
  /** @enum {string} */
14052
14057
  type: "telegram";
14053
- }) | (components["schemas"]["WhapiChannel"] & {
14054
- /** @enum {string} */
14055
- type: "whapi";
14056
14058
  }) | (components["schemas"]["WhatsappChannel"] & {
14057
14059
  /** @enum {string} */
14058
14060
  type: "whatsapp";
@@ -14226,14 +14228,6 @@ export interface components {
14226
14228
  */
14227
14229
  user_id: string;
14228
14230
  };
14229
- CreateWhapiChannelInput: {
14230
- agent_slug: string;
14231
- default_user_role_slugs?: string[] | null;
14232
- slug: string;
14233
- /** @description Whapi channel token (copied from the Whapi dashboard). */
14234
- token: string;
14235
- user_onboarding_mode?: string | null;
14236
- };
14237
14231
  CreateWhatsappChannelInput: {
14238
14232
  agent_slug: string;
14239
14233
  default_user_role_slugs?: string[] | null;
@@ -14428,7 +14422,7 @@ export interface components {
14428
14422
  slug: string | null;
14429
14423
  };
14430
14424
  /** @enum {string} */
14431
- EventType: "user_message" | "task_prompt" | "agent_directive" | "agent_message" | "agent_file" | "llm_call" | "tool_result" | "turn_done" | "todo_update" | "memory_lookup" | "media_transcription" | "sub_conversation_started" | "sub_conversation_finished" | "eval_subcall_request" | "eval_subcall_result" | "compaction_done" | "filesystem_root" | "harness_error" | "guardrail_verdict" | "client_tool_call" | "title_generated" | "context_update";
14425
+ EventType: "user_message" | "task_prompt" | "agent_directive" | "agent_message" | "agent_file" | "llm_call" | "tool_result" | "turn_done" | "todo_update" | "memory_lookup" | "media_transcription" | "sub_conversation_started" | "sub_conversation_finished" | "eval_subcall_request" | "eval_subcall_result" | "compaction_done" | "filesystem_root" | "harness_error" | "guardrail_verdict" | "client_tool_call" | "title_generated" | "context_update" | "time_notice";
14432
14426
  ExternalChannel: {
14433
14427
  agent: components["schemas"]["AgentRef"];
14434
14428
  connection_secret_hint: string;
@@ -15976,7 +15970,8 @@ export interface components {
15976
15970
  capabilities_md?: string | null;
15977
15971
  /**
15978
15972
  * Format: int32
15979
- * @description Per-agent wall-clock cap (seconds) for the `eval` built-in tool.
15973
+ * @description Per-agent CPU-time cap (seconds) for the `eval` built-in tool; time the script
15974
+ * spends waiting on tool calls, fetches or a sleep does not count.
15980
15975
  */
15981
15976
  code_execution_timeout_seconds?: number | null;
15982
15977
  /**
@@ -16110,9 +16105,6 @@ export interface components {
16110
16105
  UpdateChannelInput: (components["schemas"]["UpdateTelegramChannelInput"] & {
16111
16106
  /** @enum {string} */
16112
16107
  type: "telegram";
16113
- }) | (components["schemas"]["UpdateWhapiChannelInput"] & {
16114
- /** @enum {string} */
16115
- type: "whapi";
16116
16108
  }) | (components["schemas"]["UpdateWhatsappChannelInput"] & {
16117
16109
  /** @enum {string} */
16118
16110
  type: "whatsapp";
@@ -16354,14 +16346,6 @@ export interface components {
16354
16346
  description?: string | null;
16355
16347
  display_name?: string | null;
16356
16348
  };
16357
- UpdateWhapiChannelInput: {
16358
- agent_slug?: string | null;
16359
- default_user_role_slugs?: string[] | null;
16360
- disabled?: boolean | null;
16361
- slug?: string | null;
16362
- token?: string | null;
16363
- user_onboarding_mode?: string | null;
16364
- };
16365
16349
  UpdateWhatsappChannelInput: {
16366
16350
  agent_slug?: string | null;
16367
16351
  default_user_role_slugs?: string[] | null;
@@ -16483,27 +16467,6 @@ export interface components {
16483
16467
  token: string;
16484
16468
  };
16485
16469
  Value: unknown;
16486
- WhapiChannel: {
16487
- agent: components["schemas"]["AgentRef"];
16488
- /** Format: date-time */
16489
- created_at: string;
16490
- default_user_role_slugs: string[];
16491
- /** Format: date-time */
16492
- disabled_at: string | null;
16493
- health_status: string | null;
16494
- /** Format: uuid */
16495
- id: string;
16496
- /** @description Cached from `GET /health` at probe time; never the token. */
16497
- phone_number: string | null;
16498
- /**
16499
- * @description The channel's own WhatsApp profile name (from `GET /health`), the
16500
- * analogue of Telegram's `bot_display_name`. `null` until connected.
16501
- */
16502
- profile_name: string | null;
16503
- slug: string;
16504
- user_onboarding_mode: string;
16505
- whapi_channel_id: string | null;
16506
- };
16507
16470
  WhatsappChannel: {
16508
16471
  agent: components["schemas"]["AgentRef"];
16509
16472
  /**
package/dist/index.js.map CHANGED
@@ -7,7 +7,7 @@
7
7
  "/** Percent-encodes one path segment. Slugs are `[a-z0-9-]` and ids are UUIDs,\n * but tenant slugs and model ids come from user input and reach these URLs. */\nexport const enc = encodeURIComponent;\n\nexport const tenantPath = (tenantSlug: string) => `/api/v1/tenants/${enc(tenantSlug)}`;\n\n/** Drops a slug rename that isn't one, so the server's uniqueness pre-check\n * doesn't reject an entity for colliding with itself. */\nexport function withoutNoopRename<T extends { slug?: string | null }>(\n input: T,\n currentSlug: string,\n): T {\n if (input.slug && input.slug === currentSlug) return { ...input, slug: undefined };\n return input;\n}\n",
8
8
  "import type { Transport } from \"../http.js\";\nimport type { Schemas } from \"../schemas.js\";\nimport { enc, tenantPath, withoutNoopRename } from \"./paths.js\";\n\nexport function agentsApi(t: Transport, tenantSlug: string) {\n const base = `${tenantPath(tenantSlug)}/agents`;\n const agent = (slug: string) => `${base}/${enc(slug)}`;\n\n return {\n list: (signal?: AbortSignal) => t.request<Schemas[\"AgentListItem\"][]>(\"GET\", base, { signal }),\n\n get: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"Agent\"]>(\"GET\", agent(slug), { signal }),\n\n create: (input: Schemas[\"CreateAgentInput\"]) =>\n t.request<Schemas[\"Agent\"]>(\"POST\", base, { body: input }),\n\n update: (currentSlug: string, input: Schemas[\"UpdateAgentInput\"]) =>\n t.request<Schemas[\"Agent\"]>(\"PATCH\", agent(currentSlug), {\n body: withoutNoopRename(input, currentSlug),\n }),\n\n delete: (slug: string) => t.request<void>(\"DELETE\", agent(slug), { raw: true }),\n\n countTokens: (slug: string, input: Schemas[\"DraftAgentConfig\"], signal?: AbortSignal) =>\n t.request<Schemas[\"CountTokensResponse\"]>(\"POST\", `${agent(slug)}/count-tokens`, {\n body: input,\n signal,\n }),\n\n // MCPs, skills and task templates are attached per agent; availability is\n // the OR of global, agent and conversation config (see CLAUDE.md), so these\n // grant at the agent level only.\n listMcps: (agentSlug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AgentMcpItem\"][]>(\"GET\", `${agent(agentSlug)}/mcps`, { signal }),\n\n addMcp: (agentSlug: string, mcpSlug: string) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/mcps/${enc(mcpSlug)}`, { raw: true }),\n\n removeMcp: (agentSlug: string, mcpSlug: string) =>\n t.request<void>(\"DELETE\", `${agent(agentSlug)}/mcps/${enc(mcpSlug)}`, { raw: true }),\n\n /** `null` restores \"all of the MCP's tools\"; a list narrows to those. */\n updateMcpTools: (agentSlug: string, mcpSlug: string, enabledTools: string[] | null) =>\n t.request<void>(\"PATCH\", `${agent(agentSlug)}/mcps/${enc(mcpSlug)}`, {\n body: { enabled_tools: enabledTools },\n raw: true,\n }),\n\n replaceMcpRoles: (agentSlug: string, mcpSlug: string, roleSlugs: string[]) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/mcps/${enc(mcpSlug)}/roles`, {\n body: { role_slugs: roleSlugs } satisfies Schemas[\"ReplaceAgentMcpRolesInput\"],\n raw: true,\n }),\n\n updateMcpRoleTools: (\n agentSlug: string,\n mcpSlug: string,\n roleSlug: string,\n enabledTools: string[] | null,\n ) =>\n t.request<void>(\"PATCH\", `${agent(agentSlug)}/mcps/${enc(mcpSlug)}/roles/${enc(roleSlug)}`, {\n body: { enabled_tools: enabledTools },\n raw: true,\n }),\n\n listSkills: (agentSlug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AgentSkillItem\"][]>(\"GET\", `${agent(agentSlug)}/skills`, { signal }),\n\n addSkill: (agentSlug: string, skillSlug: string) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/skills/${enc(skillSlug)}`, { raw: true }),\n\n removeSkill: (agentSlug: string, skillSlug: string) =>\n t.request<void>(\"DELETE\", `${agent(agentSlug)}/skills/${enc(skillSlug)}`, { raw: true }),\n\n replaceSkillRoles: (agentSlug: string, skillSlug: string, roleSlugs: string[]) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/skills/${enc(skillSlug)}/roles`, {\n body: { role_slugs: roleSlugs } satisfies Schemas[\"ReplaceAgentSkillRolesInput\"],\n raw: true,\n }),\n\n listTaskTemplates: (agentSlug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AgentTaskTemplateItem\"][]>(\"GET\", `${agent(agentSlug)}/task-templates`, {\n signal,\n }),\n\n addTaskTemplate: (agentSlug: string, templateSlug: string) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/task-templates/${enc(templateSlug)}`, {\n raw: true,\n }),\n\n removeTaskTemplate: (agentSlug: string, templateSlug: string) =>\n t.request<void>(\"DELETE\", `${agent(agentSlug)}/task-templates/${enc(templateSlug)}`, {\n raw: true,\n }),\n\n replaceTaskTemplateRoles: (agentSlug: string, templateSlug: string, roleSlugs: string[]) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/task-templates/${enc(templateSlug)}/roles`, {\n body: { role_slugs: roleSlugs } satisfies Schemas[\"ReplaceAgentTaskTemplateRolesInput\"],\n raw: true,\n }),\n\n // Read-only from the agent's conversations: `memory_write` files into a\n // base only when it is also attached to the conversation or its user.\n listKnowledgeBases: (agentSlug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"KnowledgeBaseListItem\"][]>(\"GET\", `${agent(agentSlug)}/knowledge-bases`, {\n signal,\n }),\n\n attachKnowledgeBase: (agentSlug: string, kbSlug: string) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/knowledge-bases/${enc(kbSlug)}`, { raw: true }),\n\n detachKnowledgeBase: (agentSlug: string, kbSlug: string) =>\n t.request<void>(\"DELETE\", `${agent(agentSlug)}/knowledge-bases/${enc(kbSlug)}`, {\n raw: true,\n }),\n\n listAutoCallTools: (agentSlug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AutoCallToolsConfig\"]>(\"GET\", `${agent(agentSlug)}/auto-call-tools`, {\n signal,\n }),\n\n putAutoCallTools: (agentSlug: string, tools: Schemas[\"AutoCallToolRef\"][]) =>\n t.request<void>(\"PUT\", `${agent(agentSlug)}/auto-call-tools`, {\n body: { tools } satisfies Schemas[\"PutAutoCallToolsInput\"],\n raw: true,\n }),\n };\n}\n",
9
9
  "import type { Transport } from \"../http.js\";\nimport type { Schemas } from \"../schemas.js\";\nimport { enc, tenantPath, withoutNoopRename } from \"./paths.js\";\n\nexport function aiProvidersApi(t: Transport, tenantSlug: string) {\n const base = `${tenantPath(tenantSlug)}/ai-providers`;\n const provider = (slug: string) => `${base}/${enc(slug)}`;\n\n return {\n /** The provider types the running plugins serve, with the configuration each takes —\n * what a provider can be created as right now. */\n types: (signal?: AbortSignal) =>\n t.request<Schemas[\"AiProviderType\"][]>(\"GET\", `${tenantPath(tenantSlug)}/ai-provider-types`, {\n signal,\n }),\n\n /** Includes providers shared by the `_root` tenant, flagged `shared: true`. */\n list: (signal?: AbortSignal) => t.request<Schemas[\"AiProvider\"][]>(\"GET\", base, { signal }),\n\n get: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AiProvider\"]>(\"GET\", provider(slug), { signal }),\n\n create: (input: Schemas[\"CreateAiProviderInput\"]) =>\n t.request<Schemas[\"AiProvider\"]>(\"POST\", base, { body: input }),\n\n update: (currentSlug: string, input: Schemas[\"UpdateAiProviderInput\"]) =>\n t.request<Schemas[\"AiProvider\"]>(\"PATCH\", provider(currentSlug), {\n body: withoutNoopRename(input, currentSlug),\n }),\n\n delete: (slug: string) => t.request<void>(\"DELETE\", provider(slug), { raw: true }),\n\n listModels: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"AiProviderModel\"][]>(\"GET\", `${provider(slug)}/models`, { signal }),\n\n /** Re-probes the upstream catalog. 409 while another reconcile is running. */\n refreshModels: (slug: string) =>\n t.request<Schemas[\"AiProviderModel\"][]>(\"POST\", `${provider(slug)}/models/refresh`),\n\n updateModel: (slug: string, modelId: string, input: Schemas[\"UpdateProviderModelInput\"]) =>\n t.request<void>(\"PATCH\", `${provider(slug)}/models/${enc(modelId)}`, {\n body: input,\n raw: true,\n }),\n };\n}\n",
10
- "import type { Transport } from \"../http.js\";\nimport type { Schemas } from \"../schemas.js\";\nimport { enc, tenantPath } from \"./paths.js\";\n\n/** `Channel` and its Create/Update inputs are discriminated unions over `type`\n * (telegram, whapi, whatsapp, external), so no per-type methods are needed. */\nexport function channelsApi(t: Transport, tenantSlug: string) {\n const base = `${tenantPath(tenantSlug)}/channels`;\n const channel = (slug: string) => `${base}/${enc(slug)}`;\n\n return {\n list: (signal?: AbortSignal) => t.request<Schemas[\"Channel\"][]>(\"GET\", base, { signal }),\n\n get: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"Channel\"]>(\"GET\", channel(slug), { signal }),\n\n create: (input: Schemas[\"CreateChannelInput\"]) =>\n t.request<Schemas[\"CreatedChannel\"]>(\"POST\", base, { body: input }),\n\n update: (slug: string, input: Schemas[\"UpdateChannelInput\"]) =>\n t.request<Schemas[\"Channel\"]>(\"PATCH\", channel(slug), { body: input }),\n\n delete: (slug: string) => t.request<void>(\"DELETE\", channel(slug), { raw: true }),\n\n /** Invalidates the current connection secret and returns a new one. */\n rotateSecret: (slug: string) =>\n t.request<Schemas[\"RotatedSecret\"]>(\"POST\", `${channel(slug)}/rotate-secret`),\n\n /** The response components registered on the channel (external channels\n * only carry them) — the catalog every conversation on the channel\n * resolves at turn load. */\n listComponentLibraries: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"EnabledLibraries\"]>(\"GET\", `${channel(slug)}/component-libraries`, {\n signal,\n }),\n\n /** Replaces the channel's enabled libraries (send the complete list every\n * time; empty clears it). External channels only — 409 on any other type.\n * Running conversations pick the new catalog up on their next turn.\n *\n * Returns the slugs together with every tag they resolve to, so a runner can\n * check the catalog against what its frontend actually renders. */\n setComponentLibraries: (slug: string, libraries: string[]) =>\n t.request<Schemas[\"EnabledLibraries\"]>(\"PUT\", `${channel(slug)}/component-libraries`, {\n body: { libraries } satisfies Schemas[\"SetLibrariesInput\"],\n }),\n\n listDeadLetters: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"DeadLetter\"][]>(\"GET\", `${channel(slug)}/dead-letters`, { signal }),\n\n /** One summary per channel of what it has not sent: pending messages,\n * whether anything is trying to send them, and what it gave up on in the\n * last `days` days (default 7). */\n outboxReport: (query: { days?: number } = {}, signal?: AbortSignal) =>\n t.request<Schemas[\"ChannelOutboxReport\"]>(\"GET\", `${tenantPath(tenantSlug)}/channel-outbox`, {\n query,\n signal,\n }),\n\n /** The channel's outbox summary plus a page of its unsent messages, newest\n * first. Pass the previous page's `next_before` as `before`. */\n outbox: (\n slug: string,\n query: {\n status?: \"pending\" | \"failed\" | \"all\";\n days?: number;\n before?: string;\n limit?: number;\n } = {},\n signal?: AbortSignal,\n ) => t.request<Schemas[\"ChannelOutbox\"]>(\"GET\", `${channel(slug)}/outbox`, { query, signal }),\n\n pairWhatsapp: (slug: string, input: Schemas[\"WhatsappPairInput\"]) =>\n t.request<Schemas[\"WhatsappPairStatus\"]>(\"POST\", `${channel(slug)}/whatsapp/pair`, {\n body: input,\n }),\n };\n}\n",
10
+ "import type { Transport } from \"../http.js\";\nimport type { Schemas } from \"../schemas.js\";\nimport { enc, tenantPath } from \"./paths.js\";\n\n/** `Channel` and its Create/Update inputs are discriminated unions over `type`\n * (telegram, whatsapp, external), so no per-type methods are needed. */\nexport function channelsApi(t: Transport, tenantSlug: string) {\n const base = `${tenantPath(tenantSlug)}/channels`;\n const channel = (slug: string) => `${base}/${enc(slug)}`;\n\n return {\n list: (signal?: AbortSignal) => t.request<Schemas[\"Channel\"][]>(\"GET\", base, { signal }),\n\n get: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"Channel\"]>(\"GET\", channel(slug), { signal }),\n\n create: (input: Schemas[\"CreateChannelInput\"]) =>\n t.request<Schemas[\"CreatedChannel\"]>(\"POST\", base, { body: input }),\n\n update: (slug: string, input: Schemas[\"UpdateChannelInput\"]) =>\n t.request<Schemas[\"Channel\"]>(\"PATCH\", channel(slug), { body: input }),\n\n delete: (slug: string) => t.request<void>(\"DELETE\", channel(slug), { raw: true }),\n\n /** Invalidates the current connection secret and returns a new one. */\n rotateSecret: (slug: string) =>\n t.request<Schemas[\"RotatedSecret\"]>(\"POST\", `${channel(slug)}/rotate-secret`),\n\n /** The response components registered on the channel (external channels\n * only carry them) — the catalog every conversation on the channel\n * resolves at turn load. */\n listComponentLibraries: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"EnabledLibraries\"]>(\"GET\", `${channel(slug)}/component-libraries`, {\n signal,\n }),\n\n /** Replaces the channel's enabled libraries (send the complete list every\n * time; empty clears it). External channels only — 409 on any other type.\n * Running conversations pick the new catalog up on their next turn.\n *\n * Returns the slugs together with every tag they resolve to, so a runner can\n * check the catalog against what its frontend actually renders. */\n setComponentLibraries: (slug: string, libraries: string[]) =>\n t.request<Schemas[\"EnabledLibraries\"]>(\"PUT\", `${channel(slug)}/component-libraries`, {\n body: { libraries } satisfies Schemas[\"SetLibrariesInput\"],\n }),\n\n listDeadLetters: (slug: string, signal?: AbortSignal) =>\n t.request<Schemas[\"DeadLetter\"][]>(\"GET\", `${channel(slug)}/dead-letters`, { signal }),\n\n /** One summary per channel of what it has not sent: pending messages,\n * whether anything is trying to send them, and what it gave up on in the\n * last `days` days (default 7). */\n outboxReport: (query: { days?: number } = {}, signal?: AbortSignal) =>\n t.request<Schemas[\"ChannelOutboxReport\"]>(\"GET\", `${tenantPath(tenantSlug)}/channel-outbox`, {\n query,\n signal,\n }),\n\n /** The channel's outbox summary plus a page of its unsent messages, newest\n * first. Pass the previous page's `next_before` as `before`. */\n outbox: (\n slug: string,\n query: {\n status?: \"pending\" | \"failed\" | \"all\";\n days?: number;\n before?: string;\n limit?: number;\n } = {},\n signal?: AbortSignal,\n ) => t.request<Schemas[\"ChannelOutbox\"]>(\"GET\", `${channel(slug)}/outbox`, { query, signal }),\n\n pairWhatsapp: (slug: string, input: Schemas[\"WhatsappPairInput\"]) =>\n t.request<Schemas[\"WhatsappPairStatus\"]>(\"POST\", `${channel(slug)}/whatsapp/pair`, {\n body: input,\n }),\n };\n}\n",
11
11
  "// A `fetch`-based Server-Sent Events reader. Not `EventSource`: that can't\n// attach an Authorization header, which every stream here requires.\n//\n// Runtime-agnostic on purpose — `fetch`, `ReadableStream` and `AbortController`\n// only, no DOM. Exported as its own entry point (`@cubos/agent-sdk/sse`) so the\n// operator dashboard can reuse it without adopting the rest of the client.\n\nimport { parseRetryAfter, raiseForStatus } from \"./errors.js\";\n\n/** Just the call signature, not `typeof fetch` — that also demands runtime\n * extras (Bun's `preconnect`, undici's statics) a caller's wrapper won't have. */\nexport type FetchLike = (\n input: string,\n init?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string | FormData;\n signal?: AbortSignal;\n },\n) => Promise<Response>;\n\nexport interface SseOptions<T> {\n url: string;\n /**\n * Only frames with one of these `event:` names are delivered; the rest are\n * dropped. Several names on one connection is how a stream keeps two kinds of\n * frame in a single order — split across two connections there is none, and a\n * client cannot tell which came first.\n */\n event: string | string[];\n onEvent: (data: T, event: string) => void;\n signal: AbortSignal;\n /** Called before each (re)connect, so the caller can mint a fresh token.\n * `forceRefresh` is set on the one immediate retry that follows a 401 — a\n * caller that caches a token must bypass the cache when it sees it, or the\n * retry replays the rejected credential and the stream dies for good. */\n headers?: (opts: {\n forceRefresh: boolean;\n }) => Promise<Record<string, string>> | Record<string, string>;\n /** Called once per successful connect, before any frame is delivered. The\n * hook a caller needs to catch up on state the stream won't replay: it fires\n * on every reconnect too, so a gap the backoff swallowed is covered as\n * well. Not awaited — a slow catch-up must not stall frame delivery. */\n onOpen?: () => void;\n /** Resume cursor for the first connect. Later reconnects use the last `id:`\n * the server actually sent. */\n lastEventId?: string;\n /**\n * The cursor as a shared cell instead: read before every connect and written\n * after every frame, so something else delivering the same log — a poll that\n * runs while a connection is unproven — can advance it, and the next connect\n * asks for what neither has seen rather than replaying what the other did.\n * Takes precedence over `lastEventId`.\n */\n cursor?: { lastEventId?: string };\n /** Every time a connection ends, for whatever reason, before the wait that\n * precedes the next attempt. The counterpart of `onOpen`: between the two a\n * connection was live, and outside them nothing is being received. */\n onClose?: () => void;\n fetchImpl?: FetchLike;\n /**\n * Reconnect when this many milliseconds pass with no bytes at all — not even\n * a keep-alive comment. Defaults to `DEFAULT_IDLE_TIMEOUT_MS`; `0` disables.\n *\n * A half-open socket (a phone leaving the background, a proxy that dropped\n * the connection without telling either end) leaves `read()` waiting forever,\n * with nothing for the reconnect loop below to react to. The server sends a\n * comment every 15s, so silence past twice that is the connection being gone\n * rather than the agent being quiet.\n */\n idleTimeoutMs?: number;\n /** Every failed attempt, transient or fatal. The loop is already reconnecting\n * when this fires unless the promise also rejects. */\n onError?: (err: unknown) => void;\n}\n\nconst MAX_BACKOFF_MS = 30_000;\n\n/** Twice the server's 15s keep-alive interval: one comment may be lost to a\n * hiccup without the connection being gone, two in a row means it is. */\nexport const DEFAULT_IDLE_TIMEOUT_MS = 30_000;\n\n/** Marks an error the reconnect loop must not swallow. */\nclass Fatal extends Error {\n override readonly cause: unknown;\n constructor(cause: unknown) {\n super(\"fatal stream error\");\n this.cause = cause;\n }\n}\n\n/** Raised when the watchdog trips, so a caller logging `onError` can tell a\n * connection that went silent from one that failed outright. */\nexport class SseIdleTimeout extends Error {\n constructor(url: string, ms: number) {\n super(`Stream ${url} sent nothing for ${ms}ms — reconnecting.`);\n this.name = \"SseIdleTimeout\";\n }\n}\n\n/**\n * Reads `url` until `signal` aborts, reconnecting through any drop — clean\n * close from the server included, since intermediaries (Cloudflare et al.)\n * close idle SSE connections without warning and the caller would otherwise\n * silently stop receiving.\n *\n * `Last-Event-ID` is replayed from the last frame the server sent, so the\n * backend's catch-up query fills whatever the gap swallowed. 4xx ends the loop\n * — a deleted conversation won't fix itself by retrying — with two exceptions.\n * A 401 buys one immediate reconnect with `forceRefresh`, because a short-lived\n * token expiring under a stream that outlives it is the expected case, not a\n * misconfiguration; only after that second rejection does the promise reject.\n * And a 429 is a refusal, not a verdict: the user's budget or their cap on open\n * streams is full, and the server says when to come back — so the loop waits\n * out `Retry-After` and tries again, rather than ending a subscription over a\n * limit that clears in seconds.\n *\n * A connection that goes silent past `idleTimeoutMs` is dropped and reopened:\n * see that option for why waiting on `read()` forever is not an option.\n */\nexport async function readSse<T>(opts: SseOptions<T>): Promise<void> {\n const doFetch = opts.fetchImpl ?? globalThis.fetch;\n const idleMs = opts.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;\n const cursor = opts.cursor ?? { lastEventId: opts.lastEventId };\n let attempt = 0;\n // Set by a 401 and consumed by the connect that follows it, so the retry is\n // the only attempt that pays for a freshly minted token.\n let refreshing = false;\n\n while (!opts.signal.aborted) {\n let madeProgress = false;\n // Set by a 429 from the server's own `Retry-After`; overrides the\n // exponential backoff for the wait that follows.\n let retryAfterMs: number | null = null;\n // Aborts this connection alone — the watchdog must be able to drop a dead\n // socket without ending the subscription the caller's signal owns.\n const connection = new AbortController();\n const unlink = forward(opts.signal, connection);\n let idleTimer: ReturnType<typeof setTimeout> | undefined;\n let wentIdle = false;\n const armIdle = () => {\n if (idleMs <= 0) return;\n clearTimeout(idleTimer);\n idleTimer = setTimeout(() => {\n wentIdle = true;\n connection.abort();\n }, idleMs);\n };\n\n try {\n const headers: Record<string, string> = {\n ...(await opts.headers?.({ forceRefresh: refreshing })),\n Accept: \"text/event-stream\",\n };\n if (cursor.lastEventId !== undefined) headers[\"Last-Event-ID\"] = cursor.lastEventId;\n\n // Armed before the fetch: a connect that never answers is as dead as one\n // that stops mid-stream, and nothing else bounds it.\n armIdle();\n const res = await doFetch(opts.url, { headers, signal: connection.signal });\n if (opts.signal.aborted) return;\n if (res.ok && res.body) {\n refreshing = false;\n opts.onOpen?.();\n }\n\n if (!res.ok || !res.body) {\n // One immediate retry, no backoff: a token that expired between minting\n // and this connect is the expected case for a stream that outlives its\n // TTL, and `headers` is the only thing that can produce a new one. A\n // credential that is simply wrong takes the fatal path on the retry.\n if (res.status === 401 && opts.headers && !refreshing) {\n refreshing = true;\n continue;\n }\n if (res.status === 429) {\n // Transient by definition, and the one 4xx an app can hit by\n // doing nothing wrong: a user with one tab too many is over the\n // per-user cap on open streams, and each tab's stream would die\n // for good here while the cap clears the moment any tab closes.\n // Without a usable header the ceiling is the wait — the limiter\n // always sends one, so that is the odd proxy, not the server.\n retryAfterMs = Math.min(\n MAX_BACKOFF_MS,\n parseRetryAfter(res.headers.get(\"retry-after\")) ?? MAX_BACKOFF_MS,\n );\n await raiseForStatus(res, `Could not open ${opts.url}.`);\n }\n if (res.status >= 400 && res.status < 500) {\n // Wrapped so the catch below can tell it apart from a transient\n // failure and rethrow instead of reconnecting forever.\n await raiseForStatus(res, `Could not open ${opts.url}.`).catch((err) => {\n throw new Fatal(err);\n });\n return;\n }\n throw new Error(`stream open failed with HTTP ${res.status}`);\n }\n\n for await (const frame of frames(res.body, connection.signal, armIdle)) {\n const parsed = parseFrame<T>(frame, opts.event);\n if (parsed === null) continue;\n if (parsed.id !== null) cursor.lastEventId = parsed.id;\n opts.onEvent(parsed.data, parsed.event);\n madeProgress = true;\n }\n if (wentIdle) throw new SseIdleTimeout(opts.url, idleMs);\n } catch (err) {\n if (opts.signal.aborted) return;\n // A deleted conversation, or a credential a refresh didn't fix.\n if (err instanceof Fatal) throw err.cause;\n // Everything else is transient (network, 5xx, proxy hangup, a socket that\n // went silent) — report and back off rather than end the subscription.\n opts.onError?.(wentIdle ? new SseIdleTimeout(opts.url, idleMs) : err);\n } finally {\n clearTimeout(idleTimer);\n unlink();\n // Nothing below this point reads from the body; letting it hang open\n // would leak a connection per reconnect.\n connection.abort();\n opts.onClose?.();\n }\n\n if (opts.signal.aborted) return;\n\n // Any delivered frame resets the backoff: a long-lived stream that did real\n // work and then dropped should come back fast, not wait out the ceiling.\n if (madeProgress) attempt = 0;\n const delayMs = retryAfterMs ?? Math.min(MAX_BACKOFF_MS, 1_000 * 2 ** attempt);\n attempt += 1;\n await sleep(delayMs, opts.signal);\n }\n}\n\n/** `onRead` fires for every chunk the socket delivers, keep-alive comments\n * included — the watchdog is asking whether the connection is alive, which is\n * not the same question as whether a frame the caller wanted came through. */\nasync function* frames(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n onRead: () => void,\n): AsyncGenerator<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n try {\n while (!signal.aborted) {\n const { value, done } = await reader.read();\n if (done) return;\n onRead();\n buffer += decoder.decode(value, { stream: true });\n for (;;) {\n const sep = buffer.indexOf(\"\\n\\n\");\n if (sep === -1) break;\n yield buffer.slice(0, sep);\n buffer = buffer.slice(sep + 2);\n }\n }\n } finally {\n reader.cancel().catch(() => {});\n }\n}\n\nexport function parseFrame<T>(\n frame: string,\n expectedEvent: string | string[],\n): { data: T; id: string | null; event: string } | null {\n let dataLine: string | null = null;\n let id: string | null = null;\n let eventName = \"message\";\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\":\")) continue;\n if (line.startsWith(\"data:\")) dataLine = line.slice(5).trimStart();\n else if (line.startsWith(\"event:\")) eventName = line.slice(6).trim();\n else if (line.startsWith(\"id:\")) id = line.slice(3).trim();\n }\n const wanted =\n typeof expectedEvent === \"string\"\n ? eventName === expectedEvent\n : expectedEvent.includes(eventName);\n if (!wanted || dataLine === null) return null;\n try {\n return { data: JSON.parse(dataLine) as T, id, event: eventName };\n } catch {\n return null;\n }\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/** Aborts `child` when `outer` does, and hands back the unsubscribe — without\n * it every reconnect would leave another listener on a signal that lives as\n * long as the subscription. */\nfunction forward(outer: AbortSignal, child: AbortController): () => void {\n const onAbort = () => child.abort();\n if (outer.aborted) child.abort();\n else outer.addEventListener(\"abort\", onAbort, { once: true });\n return () => outer.removeEventListener(\"abort\", onAbort);\n}\n",
12
12
  "// The client-tool runner: give it your functions, it keeps a conversation's\n// client tools declared, executed and answered until you stop it.\n//\n// Written against `Transport` rather than the admin client so the same runner\n// serves the browser-safe conversation client when that lands — nothing here\n// knows which credential opened the connection.\n\nimport { AgentApiError } from \"./errors.js\";\nimport type { Transport } from \"./http.js\";\nimport type { Schemas } from \"./schemas.js\";\nimport { readSse } from \"./sse.js\";\n\n/** One tool: its declaration and the function that implements it. */\nexport interface ClientTool<Args = Record<string, unknown>, Result = unknown> {\n description?: string;\n /** JSON Schema for the arguments. Defaults to an open object, which leaves\n * the model to guess — worth writing. */\n inputSchema?: Record<string, unknown>;\n /** JSON Schema for what you return. The server validates against it before\n * the model sees anything, so a bug in your handler surfaces as a rejected\n * submit rather than as nonsense in the transcript. */\n outputSchema?: Record<string, unknown>;\n /** `true` promises the call mutates nothing, which exempts it from the\n * agent's guardrail. Don't claim it lightly. */\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n /** `true` promises the call is safe to run twice. Without it the server\n * assumes it isn't, and pins the lease to the call's deadline so no second\n * client can pick the call up mid-execution — safer, but a client that dies\n * holds the call until it times out instead of failing over. */\n idempotentHint?: boolean;\n /** Seconds the server waits before failing the call on your behalf.\n * Defaults to 90. Keep it tight: a pending call also holds back any user\n * message that arrives meanwhile. */\n timeoutSeconds?: number;\n handler: (args: Args, ctx: ClientToolContext) => Promise<Result> | Result;\n}\n\nexport interface ClientToolContext {\n /** The call's id, echoed on the result. Handy for logs. */\n toolCallId: string;\n conversationId: string;\n /** Aborts when the session stops, so a long handler can bail out. */\n signal: AbortSignal;\n}\n\nexport interface ServeClientToolsOptions {\n tools: Record<string, ClientTool<never, unknown>>;\n /** Stops the session. Same effect as calling `stop()`. */\n signal?: AbortSignal;\n /** Identifies this runner when leasing calls. Defaults to a random id, which\n * is what you want unless you're deliberately resuming another runner's\n * leases. */\n claimant?: string;\n /** Lease length in seconds; the runner renews at half of it. Defaults to 70.\n * Ignored for a tool that writes and isn't declared `idempotentHint: true` —\n * the server pins that lease to the call's deadline, because handing such a\n * call to a second client is worse than making the first one wait. */\n claimTtlSeconds?: number;\n /** Skip the declaration sync — for when the tools are already declared and\n * you only want to execute. */\n declare?: boolean;\n /**\n * Open the conversation's event stream to watch for calls. On by default.\n *\n * Turn it off when you already hold that stream — a chat UI does — and drive\n * the session with `poke()` instead: once for every `client_tool_call` frame,\n * and once each time the stream (re)connects. One connection instead of two,\n * and the server caps how many a user may hold open at once.\n */\n watch?: boolean;\n /** Reported failures that the runner recovered from: a stream drop, a\n * handler that threw. Losing a claim race is not one of them — that is\n * ordinary coordination, and the runner keeps watching the call instead. */\n onError?: (err: unknown) => void;\n}\n\nexport interface ClientToolsSession {\n stop(): void;\n /**\n * Look for calls to run, now. Cheap and safe to call spuriously: it reads the\n * pending list, and a call already being handled is skipped.\n *\n * Only needed with `watch: false`, where something else owns the stream.\n */\n poke(): void;\n /** Resolves when the session has stopped and no handler is still running. */\n done: Promise<void>;\n}\n\n/** Matches the server's own default. Sized against the browser: a background\n * tab's timers get throttled to about a minute, and renewing at half of 70s\n * still lands inside the window. */\nconst DEFAULT_CLAIM_TTL_SECONDS = 70;\n\n/** How many times the result POST is retried before giving up. The work is\n * already done at that point, so the answer is worth more than one attempt. */\nconst SUBMIT_ATTEMPTS = 5;\n\n/**\n * Declares `tools` on the conversation, then executes every call the agent\n * makes against them until stopped.\n *\n * `conversationPath` is a thunk rather than a string because the two clients\n * learn the tenant differently: the operator client is constructed with the\n * slug, while an end-user client discovers it from the token via `me()` and so\n * can only answer asynchronously.\n *\n * The cycle per call is claim → handler → submit. The claim is what keeps two\n * runners on the same conversation from both executing it; it is renewed while\n * the handler runs, so a slow handler doesn't lose the call, and it lapses if\n * this process dies, so the call isn't stranded either.\n *\n * A handler that throws submits the failure rather than swallowing it: the\n * agent needs to hear that the tool failed, otherwise it waits out the\n * server-side deadline for no reason.\n */\nexport function serveClientTools(\n t: Transport,\n conversationPath: () => Promise<string>,\n conversationId: string,\n options: ServeClientToolsOptions,\n): ClientToolsSession {\n const controller = new AbortController();\n const stop = () => controller.abort();\n if (options.signal) {\n if (options.signal.aborted) stop();\n else options.signal.addEventListener(\"abort\", stop, { once: true });\n }\n\n const claimant = options.claimant ?? `sdk-${randomId()}`;\n const ttl = options.claimTtlSeconds ?? DEFAULT_CLAIM_TTL_SECONDS;\n // Resolved once, on the first use, and reused: the end-user client's thunk\n // costs a `me()` round trip the first time it is called.\n let basePath: string | undefined;\n const resolveBase = async (): Promise<string> => {\n basePath ??= await conversationPath();\n return basePath;\n };\n const inFlight = new Set<string>();\n // A set that drops entries as they settle, not an array that grows: a\n // long-lived session handles thousands of calls and frames, and keeping a\n // resolved promise per event would leak for as long as the session lives.\n const running = new Set<Promise<void>>();\n const track = (p: Promise<void>) => {\n running.add(p);\n void p.finally(() => running.delete(p)).catch(() => {});\n };\n\n const done = (async () => {\n try {\n await run();\n } catch (err) {\n // Declaring failed, or the stream returned a 4xx that won't fix itself.\n // Abort so in-flight handlers unwind (and release their leases) instead\n // of running on behind a promise the caller may never await.\n stop();\n while (running.size > 0) await Promise.allSettled([...running]);\n throw err;\n }\n })();\n\n async function run(): Promise<void> {\n const base = await resolveBase();\n if (options.declare !== false) {\n await t.request<Schemas[\"ClientTool\"][]>(\"PUT\", `${base}/client-tools`, {\n body: { tools: declarations(options.tools) },\n signal: controller.signal,\n });\n }\n\n if (options.watch === false) {\n // The caller's stream is already open — it was open before the tools were\n // declared, which is the ordering the drain below relies on. From here\n // `poke()` plays the part `onOpen`/`onEvent` play in the watched case.\n track(guard(drain));\n await stopped();\n while (running.size > 0) await Promise.allSettled([...running]);\n return;\n }\n\n await readSse<{ event_type?: string }>({\n url: t.url(`${base}/events/stream`),\n event: \"conversation_event\",\n headers: ({ forceRefresh }) => t.streamHeaders(forceRefresh),\n fetchImpl: t.fetchImpl,\n signal: controller.signal,\n onError: options.onError,\n // The catch-up runs *after* the stream is open, never before. Declaring\n // the tools makes them callable immediately, so a drain that ran first\n // would leave a window — one round trip wide — in which the agent can\n // issue a call that the drain already missed and the stream isn't there\n // to see. Draining on open cannot miss it: the call either predates the\n // connection, and the drain finds it, or it doesn't, and a frame arrives.\n // Firing on every reconnect covers a gap the backoff swallowed too.\n onOpen: () => {\n track(guard(drain));\n },\n // A client tool event re-drains rather than acting on the frame's own\n // payload: one code path covers the frame, the catch-up and a reconnect,\n // and `inFlight` keeps the overlap from running anything twice.\n onEvent: (ev) => {\n if (ev.event_type !== \"client_tool_call\") return;\n track(guard(drain));\n },\n });\n\n // Loop: a handler still running can be waiting on a claim it will get,\n // and settling it may queue nothing new only once the abort has landed.\n while (running.size > 0) await Promise.allSettled([...running]);\n }\n\n async function drain(): Promise<void> {\n if (controller.signal.aborted) return;\n const base = await resolveBase();\n const calls = await t.request<Schemas[\"ClientToolCall\"][]>(\"GET\", `${base}/client-tool-calls`, {\n signal: controller.signal,\n });\n for (const call of calls) {\n if (inFlight.has(call.tool_call_id)) continue;\n const tool = options.tools[call.tool_name];\n if (!tool) continue;\n inFlight.add(call.tool_call_id);\n track(guard(() => execute(call, tool)));\n }\n }\n\n async function execute(\n call: Schemas[\"ClientToolCall\"],\n tool: ClientTool<never, unknown>,\n ): Promise<void> {\n const id = call.tool_call_id;\n const base = await resolveBase();\n try {\n if (!(await acquireClaim(call))) return;\n\n const keepAlive = setInterval(\n () => {\n void t\n .request(\"POST\", `${base}/client-tool-calls/${id}/claim`, {\n body: { claimant, ttl_seconds: ttl },\n })\n .catch(() => {});\n },\n Math.max(1_000, (ttl * 1000) / 2),\n );\n\n let body: Schemas[\"SubmitResultInput\"];\n try {\n const result = await tool.handler(call.arguments as never, {\n toolCallId: id,\n conversationId,\n signal: controller.signal,\n });\n // `null`, not omitted: a handler with only side effects returns\n // nothing, and that still has to read as an answer.\n body = { result: result === undefined ? null : result, claimant };\n } catch (err) {\n // A handler that threw because *we* stopped the session hasn't failed —\n // the work was cancelled. Submitting an error would answer the call on\n // behalf of every other client too, so hand the lease back instead and\n // let someone still running take it.\n if (controller.signal.aborted) {\n clearInterval(keepAlive);\n await t\n .request<void>(\"DELETE\", `${base}/client-tool-calls/${id}/claim`, {\n query: { claimant },\n raw: true,\n })\n .catch(() => {});\n return;\n }\n options.onError?.(err);\n body = { error: errorText(err), claimant };\n } finally {\n clearInterval(keepAlive);\n }\n\n await submitWithRetry(id, body);\n } finally {\n inFlight.delete(id);\n }\n }\n\n /**\n * Wait for the lease, rather than give up on it. Losing the race is not a\n * failure — the other holder may be a tab the user closed a second later, or\n * a phone that went offline mid-call. So this watches instead: the 409 says\n * when the current lease expires, we sleep exactly that long and ask again.\n *\n * Returns false only when there is genuinely nothing left: the call was\n * answered (410) or vanished (404). A lease that outlives the call's own\n * deadline — what a pinned lease looks like from here — is waited on rather\n * than abandoned: the holder may release it, and a release produces no event\n * for anyone to react to, so a runner that walked away would never come back\n * and the call would sit until the reaper failed it.\n */\n async function acquireClaim(call: Schemas[\"ClientToolCall\"]): Promise<boolean> {\n const base = await resolveBase();\n const deadline = Date.parse(call.deadline_at);\n while (!controller.signal.aborted) {\n try {\n await t.request<Schemas[\"ClientToolCall\"]>(\n \"POST\",\n `${base}/client-tool-calls/${call.tool_call_id}/claim`,\n { body: { claimant, ttl_seconds: ttl }, signal: controller.signal },\n );\n return true;\n } catch (err) {\n if (!(err instanceof AgentApiError)) throw err;\n if (err.status === 410 || err.status === 404) return false;\n if (err.status !== 409) throw err;\n\n const held = err.json<{ claim_expires_at?: string }>()?.claim_expires_at;\n const until = held ? Date.parse(held) : Date.now() + ttl * 1000;\n // Never wait past the deadline: at that point the reaper resolves the\n // call and the next attempt gets a 410, which is what ends the loop.\n const wakeAt = Number.isFinite(deadline) ? Math.min(until, deadline) : until;\n await sleep(Math.max(250, wakeAt - Date.now()), controller.signal);\n }\n }\n return false;\n }\n\n /**\n * The handler has already run by the time this is called — for a write, the\n * side effect has happened. Losing the answer to a dropped connection would\n * leave the agent waiting out the deadline and then told, wrongly, that\n * nothing ran. So retry the POST; the server answers a second delivery of an\n * already-recorded result with 410, which is a success from here.\n */\n async function submitWithRetry(id: string, body: Schemas[\"SubmitResultInput\"]): Promise<void> {\n const base = await resolveBase();\n for (let attempt = 0; ; attempt++) {\n try {\n await t.request<void>(\"POST\", `${base}/client-tool-calls/${id}/result`, {\n body,\n raw: true,\n });\n return;\n } catch (err) {\n const status = err instanceof AgentApiError ? err.status : 0;\n // 410 means it is already recorded; 4xx means this body will never be\n // accepted, so repeating it only delays the failure.\n if (status === 410) return;\n if (status >= 400 && status < 500) throw err;\n if (attempt >= SUBMIT_ATTEMPTS - 1 || controller.signal.aborted) throw err;\n options.onError?.(err);\n await sleep(Math.min(8_000, 250 * 2 ** attempt), controller.signal);\n }\n }\n }\n\n async function guard(fn: () => Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n if (!controller.signal.aborted) options.onError?.(err);\n }\n }\n\n function stopped(): Promise<void> {\n if (controller.signal.aborted) return Promise.resolve();\n return new Promise((resolve) => {\n controller.signal.addEventListener(\"abort\", () => resolve(), { once: true });\n });\n }\n\n return {\n stop,\n poke: () => {\n if (!controller.signal.aborted) track(guard(drain));\n },\n done,\n };\n}\n\nexport function declarations(\n tools: Record<string, ClientTool<never, unknown>>,\n): Schemas[\"NamedClientToolInput\"][] {\n return Object.entries(tools).map(([name, tool]) => ({\n name,\n description: tool.description ?? \"\",\n input_schema: tool.inputSchema ?? { type: \"object\" },\n output_schema: tool.outputSchema,\n read_only_hint: tool.readOnlyHint,\n destructive_hint: tool.destructiveHint,\n idempotent_hint: tool.idempotentHint,\n timeout_seconds: tool.timeoutSeconds,\n })) as Schemas[\"NamedClientToolInput\"][];\n}\n\nfunction errorText(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\n/** `crypto.randomUUID` isn't guaranteed outside secure contexts, and this only\n * needs to be unique among the runners on one conversation. */\nfunction randomId(): string {\n return Math.random().toString(36).slice(2, 10);\n}\n",
13
13
  "import {\n type ClientToolsSession,\n type ServeClientToolsOptions,\n serveClientTools,\n} from \"../client-tools.js\";\nimport type { Transport } from \"../http.js\";\nimport type { Schemas } from \"../schemas.js\";\nimport { enc, tenantPath } from \"./paths.js\";\n\n/**\n * Client tools: tools defined on a conversation with no server-side\n * implementation. The agent calls one, its turn suspends, and whoever drives\n * the API answers.\n *\n * This is the wire layer. For the usual case — \"here are my functions, run\n * them\" — use `serveClientTools`, which drives this on your behalf.\n */\nexport function clientToolsApi(t: Transport, tenantSlug: string) {\n const base = (convId: string) => `${tenantPath(tenantSlug)}/conversations/${enc(convId)}`;\n const tools = (convId: string) => `${base(convId)}/client-tools`;\n const calls = (convId: string) => `${base(convId)}/client-tool-calls`;\n\n return {\n /** Declares your functions on the conversation and runs them as the agent\n * calls them, until you stop the session. This is the whole feature in one\n * call; everything below is the wire it drives. */\n serve: (convId: string, options: ServeClientToolsOptions): ClientToolsSession =>\n serveClientTools(t, async () => base(convId), convId, options),\n\n list: (convId: string, signal?: AbortSignal) =>\n t.request<Schemas[\"ClientTool\"][]>(\"GET\", tools(convId), { signal }),\n\n /** Declares the whole set: entries are upserted, anything not listed is\n * removed. The shape a reconnecting client wants — it converges instead of\n * accumulating definitions from a previous session. */\n replace: (convId: string, input: Schemas[\"ReplaceClientToolsInput\"]) =>\n t.request<Schemas[\"ClientTool\"][]>(\"PUT\", tools(convId), { body: input }),\n\n /** Calls the agent is blocked on. Normally you learn about a call from the\n * `client_tool_call` event on the conversation's SSE stream; this is the\n * catch-up read for calls issued before you connected. */\n listCalls: (convId: string, signal?: AbortSignal) =>\n t.request<Schemas[\"ClientToolCall\"][]>(\"GET\", calls(convId), { signal }),\n\n /** Takes the exclusive lease, or renews it when `claimant` matches the\n * holder. Rejects with 409 while someone else holds a live one. */\n claim: (convId: string, toolCallId: string, input: Schemas[\"ClaimInput\"]) =>\n t.request<Schemas[\"ClientToolCall\"]>(\"POST\", `${calls(convId)}/${enc(toolCallId)}/claim`, {\n body: input,\n }),\n\n releaseClaim: (convId: string, toolCallId: string, claimant: string) =>\n t.request<void>(\"DELETE\", `${calls(convId)}/${enc(toolCallId)}/claim`, {\n query: { claimant },\n raw: true,\n }),\n\n /** Answers a call. Supply exactly one of `result`, `content` or `error`. */\n submitResult: (convId: string, toolCallId: string, input: Schemas[\"SubmitResultInput\"]) =>\n t.request<void>(\"POST\", `${calls(convId)}/${enc(toolCallId)}/result`, {\n body: input,\n raw: true,\n }),\n };\n}\n",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cubos/agent-sdk",
3
- "version": "0.0.1159021",
3
+ "version": "0.0.1159588",
4
4
  "type": "module",
5
5
  "description": "Client for the Cubos Agent conversation API. Runs anywhere fetch does.",
6
6
  "license": "SEE LICENSE IN LICENSE",