@wiro-ai/wiro-mcp 1.9.1 → 2.1.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.
Files changed (216) hide show
  1. package/README.md +95 -42
  2. package/dist/index.js +7 -0
  3. package/dist/index.js.map +1 -1
  4. package/dist/instructions.js +5 -5
  5. package/dist/instructions.js.map +1 -1
  6. package/dist/playbooks.d.ts.map +1 -1
  7. package/dist/playbooks.js +111 -94
  8. package/dist/playbooks.js.map +1 -1
  9. package/dist/prompts.js +7 -7
  10. package/dist/prompts.js.map +1 -1
  11. package/dist/tools/answer-agent-approval.d.ts +4 -0
  12. package/dist/tools/answer-agent-approval.d.ts.map +1 -0
  13. package/dist/tools/answer-agent-approval.js +354 -0
  14. package/dist/tools/answer-agent-approval.js.map +1 -0
  15. package/dist/tools/apply-agent-skills.d.ts.map +1 -1
  16. package/dist/tools/apply-agent-skills.js +81 -30
  17. package/dist/tools/apply-agent-skills.js.map +1 -1
  18. package/dist/tools/bind-agent-project.d.ts.map +1 -1
  19. package/dist/tools/bind-agent-project.js +29 -28
  20. package/dist/tools/bind-agent-project.js.map +1 -1
  21. package/dist/tools/cancel-agent-message.js +1 -1
  22. package/dist/tools/cancel-agent-message.js.map +1 -1
  23. package/dist/tools/check-model-access.d.ts.map +1 -1
  24. package/dist/tools/check-model-access.js +14 -11
  25. package/dist/tools/check-model-access.js.map +1 -1
  26. package/dist/tools/connect-agent-connector.d.ts +4 -0
  27. package/dist/tools/connect-agent-connector.d.ts.map +1 -0
  28. package/dist/tools/connect-agent-connector.js +634 -0
  29. package/dist/tools/connect-agent-connector.js.map +1 -0
  30. package/dist/tools/control-agent.d.ts.map +1 -1
  31. package/dist/tools/control-agent.js +30 -31
  32. package/dist/tools/control-agent.js.map +1 -1
  33. package/dist/tools/delete-agent.d.ts.map +1 -1
  34. package/dist/tools/delete-agent.js +12 -5
  35. package/dist/tools/delete-agent.js.map +1 -1
  36. package/dist/tools/deploy-agent.d.ts.map +1 -1
  37. package/dist/tools/deploy-agent.js +96 -44
  38. package/dist/tools/deploy-agent.js.map +1 -1
  39. package/dist/tools/disconnect-agent-connector.d.ts +4 -0
  40. package/dist/tools/disconnect-agent-connector.d.ts.map +1 -0
  41. package/dist/tools/disconnect-agent-connector.js +184 -0
  42. package/dist/tools/disconnect-agent-connector.js.map +1 -0
  43. package/dist/tools/get-account.d.ts.map +1 -1
  44. package/dist/tools/get-account.js +24 -8
  45. package/dist/tools/get-account.js.map +1 -1
  46. package/dist/tools/get-agent-activity.d.ts.map +1 -1
  47. package/dist/tools/get-agent-activity.js +285 -138
  48. package/dist/tools/get-agent-activity.js.map +1 -1
  49. package/dist/tools/get-agent-connector-permissions.d.ts +145 -0
  50. package/dist/tools/get-agent-connector-permissions.d.ts.map +1 -0
  51. package/dist/tools/get-agent-connector-permissions.js +194 -0
  52. package/dist/tools/get-agent-connector-permissions.js.map +1 -0
  53. package/dist/tools/get-agent-conversation.d.ts.map +1 -1
  54. package/dist/tools/get-agent-conversation.js +39 -10
  55. package/dist/tools/get-agent-conversation.js.map +1 -1
  56. package/dist/tools/get-agent-message.d.ts.map +1 -1
  57. package/dist/tools/get-agent-message.js +13 -5
  58. package/dist/tools/get-agent-message.js.map +1 -1
  59. package/dist/tools/get-agent-template.d.ts.map +1 -1
  60. package/dist/tools/get-agent-template.js +13 -15
  61. package/dist/tools/get-agent-template.js.map +1 -1
  62. package/dist/tools/get-my-agent.d.ts.map +1 -1
  63. package/dist/tools/get-my-agent.js +38 -5
  64. package/dist/tools/get-my-agent.js.map +1 -1
  65. package/dist/tools/get-task-price.d.ts.map +1 -1
  66. package/dist/tools/get-task-price.js +4 -4
  67. package/dist/tools/get-task-price.js.map +1 -1
  68. package/dist/tools/get-task.d.ts.map +1 -1
  69. package/dist/tools/get-task.js +4 -4
  70. package/dist/tools/get-task.js.map +1 -1
  71. package/dist/tools/index.d.ts +8 -3
  72. package/dist/tools/index.d.ts.map +1 -1
  73. package/dist/tools/index.js +17 -6
  74. package/dist/tools/index.js.map +1 -1
  75. package/dist/tools/kill-task.js +1 -1
  76. package/dist/tools/kill-task.js.map +1 -1
  77. package/dist/tools/list-agent-connectors.d.ts +4 -0
  78. package/dist/tools/list-agent-connectors.d.ts.map +1 -0
  79. package/dist/tools/list-agent-connectors.js +325 -0
  80. package/dist/tools/list-agent-connectors.js.map +1 -0
  81. package/dist/tools/list-agent-skills.d.ts.map +1 -1
  82. package/dist/tools/list-agent-skills.js +59 -40
  83. package/dist/tools/list-agent-skills.js.map +1 -1
  84. package/dist/tools/list-agent-templates.d.ts.map +1 -1
  85. package/dist/tools/list-agent-templates.js +7 -5
  86. package/dist/tools/list-agent-templates.js.map +1 -1
  87. package/dist/tools/list-my-agents.d.ts.map +1 -1
  88. package/dist/tools/list-my-agents.js +7 -3
  89. package/dist/tools/list-my-agents.js.map +1 -1
  90. package/dist/tools/list-projects.d.ts.map +1 -1
  91. package/dist/tools/list-projects.js +7 -4
  92. package/dist/tools/list-projects.js.map +1 -1
  93. package/dist/tools/list-studio-results.d.ts.map +1 -1
  94. package/dist/tools/list-studio-results.js +3 -2
  95. package/dist/tools/list-studio-results.js.map +1 -1
  96. package/dist/tools/list-tasks.d.ts.map +1 -1
  97. package/dist/tools/list-tasks.js +6 -3
  98. package/dist/tools/list-tasks.js.map +1 -1
  99. package/dist/tools/manage-agent-billing.d.ts.map +1 -1
  100. package/dist/tools/manage-agent-billing.js +216 -359
  101. package/dist/tools/manage-agent-billing.js.map +1 -1
  102. package/dist/tools/manage-agent-custom-skill.d.ts.map +1 -1
  103. package/dist/tools/manage-agent-custom-skill.js +77 -30
  104. package/dist/tools/manage-agent-custom-skill.js.map +1 -1
  105. package/dist/tools/manage-model-access.js +1 -1
  106. package/dist/tools/manage-model-access.js.map +1 -1
  107. package/dist/tools/manage-spend-limit.js +1 -1
  108. package/dist/tools/manage-spend-limit.js.map +1 -1
  109. package/dist/tools/run-model.d.ts.map +1 -1
  110. package/dist/tools/run-model.js +4 -4
  111. package/dist/tools/run-model.js.map +1 -1
  112. package/dist/tools/schemas.d.ts +11 -0
  113. package/dist/tools/schemas.d.ts.map +1 -1
  114. package/dist/tools/schemas.js +19 -1
  115. package/dist/tools/schemas.js.map +1 -1
  116. package/dist/tools/send-agent-message.d.ts.map +1 -1
  117. package/dist/tools/send-agent-message.js +45 -20
  118. package/dist/tools/send-agent-message.js.map +1 -1
  119. package/dist/tools/set-agent-connector-accounts.d.ts +4 -0
  120. package/dist/tools/set-agent-connector-accounts.d.ts.map +1 -0
  121. package/dist/tools/set-agent-connector-accounts.js +263 -0
  122. package/dist/tools/set-agent-connector-accounts.js.map +1 -0
  123. package/dist/tools/set-agent-connector-permissions.d.ts +4 -0
  124. package/dist/tools/set-agent-connector-permissions.d.ts.map +1 -0
  125. package/dist/tools/set-agent-connector-permissions.js +280 -0
  126. package/dist/tools/set-agent-connector-permissions.js.map +1 -0
  127. package/dist/tools/set-agent-credentials.d.ts.map +1 -1
  128. package/dist/tools/set-agent-credentials.js +52 -169
  129. package/dist/tools/set-agent-credentials.js.map +1 -1
  130. package/dist/tools/update-agent.d.ts.map +1 -1
  131. package/dist/tools/update-agent.js +39 -18
  132. package/dist/tools/update-agent.js.map +1 -1
  133. package/dist/tools/wait-for-task.d.ts.map +1 -1
  134. package/dist/tools/wait-for-task.js +4 -4
  135. package/dist/tools/wait-for-task.js.map +1 -1
  136. package/dist/tools/wait-for-workflow-run.d.ts.map +1 -1
  137. package/dist/tools/wait-for-workflow-run.js +6 -3
  138. package/dist/tools/wait-for-workflow-run.js.map +1 -1
  139. package/dist/utils/agent-approvals.d.ts +328 -0
  140. package/dist/utils/agent-approvals.d.ts.map +1 -0
  141. package/dist/utils/agent-approvals.js +620 -0
  142. package/dist/utils/agent-approvals.js.map +1 -0
  143. package/dist/utils/agent-catalog.d.ts +15 -25
  144. package/dist/utils/agent-catalog.d.ts.map +1 -1
  145. package/dist/utils/agent-catalog.js +27 -36
  146. package/dist/utils/agent-catalog.js.map +1 -1
  147. package/dist/utils/agent-config.d.ts +87 -292
  148. package/dist/utils/agent-config.d.ts.map +1 -1
  149. package/dist/utils/agent-config.js +150 -787
  150. package/dist/utils/agent-config.js.map +1 -1
  151. package/dist/utils/agent-connectors.d.ts +197 -0
  152. package/dist/utils/agent-connectors.d.ts.map +1 -0
  153. package/dist/utils/agent-connectors.js +415 -0
  154. package/dist/utils/agent-connectors.js.map +1 -0
  155. package/dist/utils/agent-message.d.ts +106 -4
  156. package/dist/utils/agent-message.d.ts.map +1 -1
  157. package/dist/utils/agent-message.js +84 -14
  158. package/dist/utils/agent-message.js.map +1 -1
  159. package/dist/utils/agent-setup.d.ts +19 -14
  160. package/dist/utils/agent-setup.d.ts.map +1 -1
  161. package/dist/utils/agent-setup.js +171 -106
  162. package/dist/utils/agent-setup.js.map +1 -1
  163. package/dist/utils/agent-targets.d.ts.map +1 -1
  164. package/dist/utils/agent-targets.js +40 -14
  165. package/dist/utils/agent-targets.js.map +1 -1
  166. package/dist/utils/agent-turns.d.ts +256 -7
  167. package/dist/utils/agent-turns.d.ts.map +1 -1
  168. package/dist/utils/agent-turns.js +260 -71
  169. package/dist/utils/agent-turns.js.map +1 -1
  170. package/dist/utils/connector-permissions.d.ts +184 -0
  171. package/dist/utils/connector-permissions.d.ts.map +1 -0
  172. package/dist/utils/connector-permissions.js +439 -0
  173. package/dist/utils/connector-permissions.js.map +1 -0
  174. package/dist/utils/controls.d.ts +6 -2
  175. package/dist/utils/controls.d.ts.map +1 -1
  176. package/dist/utils/controls.js +20 -9
  177. package/dist/utils/controls.js.map +1 -1
  178. package/dist/utils/format.d.ts +10 -0
  179. package/dist/utils/format.d.ts.map +1 -1
  180. package/dist/utils/format.js +117 -38
  181. package/dist/utils/format.js.map +1 -1
  182. package/dist/utils/quoted-text.d.ts +2 -0
  183. package/dist/utils/quoted-text.d.ts.map +1 -1
  184. package/dist/utils/quoted-text.js +5 -0
  185. package/dist/utils/quoted-text.js.map +1 -1
  186. package/dist/utils/structured.d.ts +3 -0
  187. package/dist/utils/structured.d.ts.map +1 -1
  188. package/dist/utils/structured.js +7 -2
  189. package/dist/utils/structured.js.map +1 -1
  190. package/dist/utils/studio-runs.d.ts.map +1 -1
  191. package/dist/utils/studio-runs.js +6 -4
  192. package/dist/utils/studio-runs.js.map +1 -1
  193. package/dist/utils/user-agent.d.ts +271 -100
  194. package/dist/utils/user-agent.d.ts.map +1 -1
  195. package/dist/utils/user-agent.js +434 -159
  196. package/dist/utils/user-agent.js.map +1 -1
  197. package/dist/utils/wiro-project.d.ts +25 -0
  198. package/dist/utils/wiro-project.d.ts.map +1 -1
  199. package/dist/utils/wiro-project.js +76 -2
  200. package/dist/utils/wiro-project.js.map +1 -1
  201. package/dist/utils/workflow.d.ts.map +1 -1
  202. package/dist/utils/workflow.js +4 -2
  203. package/dist/utils/workflow.js.map +1 -1
  204. package/dist/utils/workspace.d.ts +3 -1
  205. package/dist/utils/workspace.d.ts.map +1 -1
  206. package/dist/utils/workspace.js +2 -1
  207. package/dist/utils/workspace.js.map +1 -1
  208. package/package.json +1 -1
  209. package/dist/tools/connect-agent-oauth.d.ts +0 -4
  210. package/dist/tools/connect-agent-oauth.d.ts.map +0 -1
  211. package/dist/tools/connect-agent-oauth.js +0 -778
  212. package/dist/tools/connect-agent-oauth.js.map +0 -1
  213. package/dist/tools/disconnect-agent-oauth.d.ts +0 -4
  214. package/dist/tools/disconnect-agent-oauth.d.ts.map +0 -1
  215. package/dist/tools/disconnect-agent-oauth.js +0 -138
  216. package/dist/tools/disconnect-agent-oauth.js.map +0 -1
@@ -1,37 +1,36 @@
1
- import { randomUUID } from 'node:crypto';
2
1
  import { z } from 'zod';
3
- import { ApiResultError, asString, errorResult, errorText, isPlainObject, requireApiSuccess, toNumber, unixToIso, } from '../utils/api.js';
2
+ import { ApiResultError, asString, errorResult, errorText, hasErrorCode, isPlainObject, requireApiSuccess, toNumber, unixToIso, } from '../utils/api.js';
4
3
  import { daysLeftText, readPlanChange, underOneDayLeft, workspaceHint } from '../utils/agent-config.js';
5
4
  import { DEFAULT_WAIT_SECONDS } from '../utils/poll.js';
6
5
  import { isPlainTeamMember, teamAgentBillingRefused } from '../utils/workspace.js';
7
- import { AGENT_PLANS, AMOUNT_TOLERANCE_USD, WALLET_NOT_READ_NOTE, agentDashboardUrl, agentSummarySchema, asPlan, chargeRoute, comparePlans, formatAgentSummaryLines, formatCredits, formatUsd, isTransitionalStatus, isUnsettledPlan, isWalletNotRead, outcomeUnknown, planLineText, planName, readAgentDetail, roundUsd, sameAmount, toAgentDetail, toAgentSummary, unsettledPlanText, } from '../utils/user-agent.js';
6
+ import { AGENT_PLANS, AMOUNT_TOLERANCE_USD, WALLET_NOT_READ_NOTE, agentDashboardUrl, agentSummarySchema, addFundsText, asPlan, balanceShortfall, cardPlanOnceMoreNote, centsToUsd, comparePlans, formatAgentSummaryLines, formatUsd, isTransitionalStatus, isUnsettledPlan, isWalletNotRead, outcomeUnknown, planBalanceName, planLineText, planName, readAgentDetail, renewalMoment, roundUsd, sameAmount, shortBalanceNote, toAgentDetail, toAgentSummary, toAgentUsage, toPlanPricing, unsettledPlanText, } from '../utils/user-agent.js';
8
7
  import { nextActionSchema, strictInput } from './schemas.js';
8
+ // buy_credits is retired with the extra credit packs: it is still answered, and charges nothing.
9
9
  const ACTIONS = ['subscribe', 'change_plan', 'cancel', 'renew', 'buy_credits'];
10
10
  const quoteSchema = z.object({
11
11
  chargeNowUsd: z.number().nullable(),
12
12
  estimated: z.boolean(),
13
13
  maxChargeUsd: z.number().optional(),
14
14
  recurringUsd: z.number().nullable().optional(),
15
- monthlyCredits: z.number().nullable().optional(),
16
- creditsNow: z.number().optional()
17
- .describe('change_plan to a larger plan: the credits this period gains now. monthlyCredits is what every renewal gives.'),
18
- creditsAdded: z.number().optional(),
15
+ includedUsageUsd: z.number().nullable().optional()
16
+ .describe('The AI usage the plan includes each month, in USD, from every renewal.'),
17
+ includedUsageNowUsd: z.number().optional()
18
+ .describe('change_plan to a larger plan: the included AI usage this period gains now, in USD. includedUsageUsd is what every renewal includes.'),
19
19
  paidFrom: z.enum(['personal_wallet', 'team_wallet', 'card']),
20
20
  plan: z.enum(AGENT_PLANS).optional()
21
21
  .describe('subscribe and change_plan: the plan this quote is for. renew: the plan it renews on.'),
22
22
  change: z.enum(['upgrade', 'downgrade', 'undo_downgrade']).optional()
23
23
  .describe('change_plan: upgrade (a larger plan, now), downgrade (a smaller plan, from the next renewal) or undo_downgrade (keep the plan, and undo the move set for the next renewal).'),
24
24
  startsAt: z.string().optional()
25
- .describe('change_plan to a smaller plan: when the period ends; the new plan starts with the renewal after it.'),
26
- pack: z.string().optional(),
25
+ .describe('change_plan to a smaller plan: when the period ends, as Wiro shows it (never a moment gone by); the new plan starts with the renewal after it.'),
27
26
  });
28
27
  const resultSchema = z.object({
29
28
  chargedUsd: z.number().nullable().optional(),
30
29
  monthlyPriceUsd: z.number().optional(),
31
- monthlyCredits: z.number().optional(),
32
- creditsNow: z.number().optional()
33
- .describe('change_plan to a larger plan: the credits this period gained with it. monthlyCredits is what every renewal gives.'),
34
- creditsAdded: z.number().optional(),
30
+ includedUsageUsd: z.number().optional()
31
+ .describe('The AI usage the plan includes each month, in USD, from every renewal.'),
32
+ includedUsageNowUsd: z.number().optional()
33
+ .describe('change_plan to a larger plan: the included AI usage this period gained with it, in USD.'),
35
34
  plan: z.string().optional(),
36
35
  previousPlan: z.string().optional(),
37
36
  nextPlan: z.string().nullable().optional()
@@ -42,9 +41,6 @@ const resultSchema = z.object({
42
41
  renewal: z.enum(['undo_cancel', 'renewed']).optional(),
43
42
  });
44
43
  const CHARGE_REASON = 'Ask the user to approve this charge first.';
45
- function newRequestId() {
46
- return randomUUID().replace(/-/g, '');
47
- }
48
44
  function billingCall(guid, action, extra = {}) {
49
45
  return {
50
46
  tool: 'manage_agent_billing',
@@ -60,7 +56,7 @@ function waitAction(guid, reason) {
60
56
  };
61
57
  }
62
58
  /**
63
- * The wait after a plan change, a pack or a renewal, which keep a running agent up:
59
+ * The wait after a plan change or a renewal, which keep a running agent up:
64
60
  * only an agent on its way, one that was stopping (it starts again) or one queued
65
61
  * or starting, is worth waiting for.
66
62
  */
@@ -77,8 +73,7 @@ function renewWait(agent) {
77
73
  }
78
74
  /**
79
75
  * A new plan queues a stopped or failed agent, and one waiting for setup; a
80
- * running one keeps running, and one that was stopping starts again. An agent
81
- * without a plan runs only while extra credits last.
76
+ * running one keeps running, and one that was stopping starts again.
82
77
  */
83
78
  function subscribeStarts(status) {
84
79
  return status !== 4;
@@ -100,14 +95,17 @@ function subscribeQuoteNote(status) {
100
95
  function subscribeWait(agent) {
101
96
  return subscribeStarts(agent.status) ? waitAction(agent.guid, 'Wait until the agent is running.') : undefined;
102
97
  }
103
- /** What a move to a larger plan does to this period's credits. An allowance above the new plan's is cut to it for the time left. */
104
- function upgradeCreditsText(creditsNow, renewal, done) {
105
- if (creditsNow > 0) {
106
- return `${formatCredits(creditsNow)} credits ${done ? 'came with it' : 'come now'} for the rest of this period${renewal}. `;
98
+ /**
99
+ * What a move to a larger plan does to this period's included AI usage, in USD. An amount above the new plan's is
100
+ * cut to it for the time left.
101
+ */
102
+ function upgradeUsageText(nowUsd, renewal, done) {
103
+ if (nowUsd > 0) {
104
+ return `${formatUsd(nowUsd)} of AI usage ${done ? 'came with it' : 'comes now'} for the rest of this period${renewal}. `;
107
105
  }
108
- if (creditsNow < 0)
109
- return `This period ${done ? 'lost' : 'loses'} ${formatCredits(-creditsNow)} credits for the time left${renewal}. `;
110
- return `This period ${done ? 'kept' : 'keeps'} the credits it ${done ? 'had' : 'has'}${renewal}. `;
106
+ if (nowUsd < 0)
107
+ return `This period ${done ? 'lost' : 'loses'} ${formatUsd(-nowUsd)} of included AI usage for the time left${renewal}. `;
108
+ return `This period ${done ? 'kept' : 'keeps'} the AI usage it ${done ? 'included' : 'includes'}${renewal}. `;
111
109
  }
112
110
  /** What a change to the plan does to the agent: a running one keeps running, and one that was stopping starts again. */
113
111
  function planChangeAgentNote(status, what, quote = false) {
@@ -123,13 +121,13 @@ function planChangeAgentNote(status, what, quote = false) {
123
121
  case 2:
124
122
  return 'The agent is queued to start.';
125
123
  case 6:
126
- return 'The agent still needs setup; the credits are there once it starts.';
124
+ return 'The agent still needs setup; the included AI usage is there once it starts.';
127
125
  case 0:
128
- return 'The agent is stopped; the credits are there when it starts.';
126
+ return 'The agent is stopped; the included AI usage is there when it starts.';
129
127
  case 5:
130
- return 'The agent stopped with an error; the credits are there when it starts.';
128
+ return 'The agent stopped with an error; the included AI usage is there when it starts.';
131
129
  default:
132
- return 'The credits are there when the agent starts.';
130
+ return 'The included AI usage is there when the agent starts.';
133
131
  }
134
132
  }
135
133
  /**
@@ -144,9 +142,8 @@ async function readPlanPreview(client, guid, plan, signal) {
144
142
  if (priced !== undefined && priced !== plan)
145
143
  return null;
146
144
  const priceUsd = toNumber(body.totalPriceUsd);
147
- const monthlyCredits = toNumber(body.totalMonthlyCredits);
148
145
  return {
149
- price: priceUsd !== null && monthlyCredits !== null ? { priceUsd, monthlyCredits } : null,
146
+ price: priceUsd !== null ? { priceUsd, includedUsageUsd: toPlanPricing(body)?.[plan]?.includedUsageUsd ?? priceUsd } : null,
150
147
  change: readPlanChange(body.planChange),
151
148
  };
152
149
  }
@@ -156,9 +153,9 @@ async function readPlanPreview(client, guid, plan, signal) {
156
153
  return null;
157
154
  }
158
155
  }
159
- /** A plan's price as said in a sentence: "$30.00 every 30 days with 3,000 monthly credits". */
156
+ /** A plan's price as said in a sentence: "$30.00 every 30 days, including $30.00 of AI usage a month". */
160
157
  function planTerms(price) {
161
- return `${formatUsd(price.priceUsd)} every 30 days with ${formatCredits(price.monthlyCredits)} monthly credits`;
158
+ return `${formatUsd(price.priceUsd)} every 30 days, including ${formatUsd(price.includedUsageUsd)} of AI usage a month`;
162
159
  }
163
160
  /**
164
161
  * What the next renewal charges and grants: the plan set for it, or the agent's own plan, at today's price.
@@ -215,18 +212,43 @@ function approvalProblem(action, quote, approved) {
215
212
  : sameAmount(amount, approved);
216
213
  return fits ? null : 'changed';
217
214
  }
215
+ /**
216
+ * A quoted charge the Wiro balance that pays the plan cannot pay now: the words that say so with the amount to add,
217
+ * and the confirm step's reason. Wiro checks a plan payment against what that balance can pay a plan with
218
+ * (usage.planBalanceUsd), and refuses a short one with nothing charged. null when the balance can pay it, when the
219
+ * quote charges nothing now or gives only the most a move can charge, or when the balance was not read.
220
+ */
221
+ function planBalanceShortfall(quote, row) {
222
+ const charge = quote && !quote.estimated ? quote.chargeNowUsd : null;
223
+ const planBalance = toAgentUsage(row).planBalanceUsd;
224
+ if (charge === null || charge <= 0 || planBalance === undefined)
225
+ return null;
226
+ const shortCents = Math.round(charge * 100) - Math.round(planBalance * 100);
227
+ if (shortCents <= 0)
228
+ return null;
229
+ const short = formatUsd(shortCents / 100);
230
+ const workspace = row.teamguid ? 'team' : 'personal';
231
+ const balance = planBalanceName(workspace);
232
+ return {
233
+ text: `${balance[0].toUpperCase()}${balance.slice(1)} has ${formatUsd(planBalance)} that can pay a plan, ${short} less `
234
+ + `than this charge. Add at least ${short} to it on wiro.ai before confirming; a confirm before then is refused, `
235
+ + `and nothing is charged. ${addFundsText(workspace)}`,
236
+ reason: `Ask the user to add at least ${short} on wiro.ai first, then to approve this charge.`,
237
+ };
238
+ }
218
239
  /** The first lines of a new quote when the approved amount no longer fits. */
219
- function changedLead(action, quote, amount, approved, callerRequestId) {
240
+ function changedLead(action, quote, amount, approved) {
220
241
  if (approvedAsCeiling(action, quote)) {
221
242
  return `The most this plan change can charge changed since the quote: it is now ${formatUsd(amount)}, and the user approved at most ${formatUsd(approved)}. Nothing was charged. Show the new amount to the user and ask again.`;
222
243
  }
223
- const changed = `The amount changed since the quote: it is now ${formatUsd(amount)}, and the user approved ${formatUsd(approved)}.`;
224
- if (action === 'buy_credits' && callerRequestId) {
225
- // Wiro binds a purchase request id to the price of its first attempt.
226
- return `${changed} Nothing was charged by this call. Show the new amount to the user and ask again. `
227
- + `If an earlier call with request_id "${callerRequestId}" ended without a clear result, do not approve the new amount for it: this request id works only at its original price. Check get_my_agent and the wallet balance with get_account, and if the balance changed, contact Wiro support.`;
228
- }
229
- return `${changed} Nothing was charged. Show the new amount to the user and ask again.`;
244
+ return `The amount changed since the quote: it is now ${formatUsd(amount)}, and the user approved ${formatUsd(approved)}. Nothing was charged. Show the new amount to the user and ask again.`;
245
+ }
246
+ /** The answer to buy_credits, which charges nothing: the packs are retired, and the balance pays after the plan. */
247
+ function packsRetiredText(agent) {
248
+ const balance = agent.workspace === 'team' ? 'the team\'s Wiro balance' : 'your Wiro balance';
249
+ return 'Extra credit packs are retired, and nothing was charged. The agent uses the AI usage its plan includes '
250
+ + `first, then ${balance}. To keep it running after the included usage, add funds to that balance on wiro.ai. `
251
+ + `${addFundsText(agent.workspace)} A larger plan includes more AI usage each month: action change_plan quotes a move.`;
230
252
  }
231
253
  /** The plans with their prices, for a call that did not name one, and the plan the agent is on. */
232
254
  function plansListing(agent) {
@@ -241,11 +263,18 @@ async function planFor(client, action, agent, raw, input, signal) {
241
263
  const active = raw?.status === 'active';
242
264
  const prepaid = raw?.provider === 'prepaid';
243
265
  const cancelled = raw?.pendingdowngrade === 'cancel';
244
- const route = chargeRoute(raw);
266
+ // Agent plans are paid only from the Wiro balance of the agent's workspace: every new charge and every
267
+ // renewal. A card plan from before that is paid by card through its period, then moves to the balance; one
268
+ // whose period ends within 7 days after Wiro's email announcing the move renews once more by card first.
245
269
  const paidFrom = agent.workspace === 'team' ? 'team_wallet' : 'personal_wallet';
246
- const wallet = agent.workspace === 'team' ? 'the team wallet' : 'the personal wallet';
247
- const periodEnd = agent.subscription?.periodEndsAt ?? 'the end of the current period';
248
- const cardPlan = (what) => `This plan is billed by card, and card payments are made in the Wiro dashboard. Nothing was charged here. To ${what}, open ${agent.dashboardUrl}`;
270
+ const balance = planBalanceName(agent.workspace);
271
+ // When the active plan renews or ends, as Wiro shows it: its period end, or now once a renewal is due (a wallet
272
+ // plan whose balance cannot pay it stays active while Wiro tries again), never a moment gone by.
273
+ const periodEnd = renewalMoment(agent.subscription) ?? 'the end of the current period';
274
+ // An answer with a card checkout link instead of the change, which an older Wiro gave for a card plan. No
275
+ // checkout is opened here.
276
+ const checkoutAnswer = (what) => `Wiro did not ${what}: it answered with a card checkout, which is not opened `
277
+ + `here, and nothing was charged. Agent plans are paid from ${balance}; get_my_agent shows the plan as it is now.`;
249
278
  // A plan that has not ended and is not active, such as a card plan whose last payment did not go through
250
279
  // (past_due, then unpaid). Wiro counts every status but expired, cancelled and refunded as a plan that has
251
280
  // not ended: it starts no new plan beside one, and renews, changes, cancels and tops up only an active plan.
@@ -258,7 +287,7 @@ async function planFor(client, action, agent, raw, input, signal) {
258
287
  if (active) {
259
288
  return {
260
289
  outcome: 'refused',
261
- message: 'This agent already has an active plan. Use renew to undo a cancellation, change_plan to move to another plan, or buy_credits for more credits.',
290
+ message: 'This agent already has an active plan. Use renew to undo a cancellation, or change_plan to move to another plan; a larger plan includes more AI usage each month.',
262
291
  };
263
292
  }
264
293
  // Its payment is fixed instead: a second plan would bill beside it.
@@ -276,11 +305,11 @@ async function planFor(client, action, agent, raw, input, signal) {
276
305
  chargeNowUsd: price.priceUsd,
277
306
  estimated: false,
278
307
  recurringUsd: price.priceUsd,
279
- monthlyCredits: price.monthlyCredits,
308
+ includedUsageUsd: price.includedUsageUsd,
280
309
  paidFrom,
281
310
  plan,
282
311
  },
283
- message: `Subscribe on ${planName(plan)}: ${formatUsd(price.priceUsd)} now from ${wallet}, then every 30 days until the plan is cancelled, with ${formatCredits(price.monthlyCredits)} credits per month. `
312
+ message: `Subscribe on ${planName(plan)}: ${formatUsd(price.priceUsd)} now, paid from ${balance}, then every 30 days until the plan is cancelled. It includes ${formatUsd(price.includedUsageUsd)} of AI usage a month; after it, the agent uses the same balance. `
284
313
  + subscribeQuoteNote(agent.status)
285
314
  + (missing.length > 0
286
315
  ? ` Missing credentials (${missing.map(item => item.title).join(', ')}) can be added afterwards; until then the skills that need them fail.`
@@ -293,12 +322,11 @@ async function planFor(client, action, agent, raw, input, signal) {
293
322
  }, signal), 'The plan could not be started.');
294
323
  const monthly = toNumber(body.monthlypriceusd) ?? price.priceUsd;
295
324
  const paid = walletPaid(body, monthly);
296
- const credits = toNumber(body.monthlycredits) ?? price.monthlyCredits;
297
325
  return {
298
326
  outcome: 'done',
299
- message: `Subscribed on ${planName(plan)} and charged ${paid.text} from ${wallet}. The plan renews every 30 days until it is cancelled. `
327
+ message: `Subscribed on ${planName(plan)} and charged ${paid.text} from ${balance}. The plan renews from it every 30 days until it is cancelled. `
300
328
  + (subscribeStarts(agent.status) ? 'The agent is starting.' : 'The agent keeps running: a new plan does not restart it.'),
301
- result: { chargedUsd: paid.chargedUsd, monthlyPriceUsd: monthly, monthlyCredits: credits, plan },
329
+ result: { chargedUsd: paid.chargedUsd, monthlyPriceUsd: monthly, includedUsageUsd: price.includedUsageUsd, plan },
302
330
  nextAction: subscribeWait(agent),
303
331
  };
304
332
  },
@@ -313,23 +341,19 @@ async function planFor(client, action, agent, raw, input, signal) {
313
341
  };
314
342
  }
315
343
  if (active) {
316
- if (!prepaid) {
317
- // A card plan can be set to stop at its period end.
318
- const atPeriodEnd = agent.subscription?.atPeriodEnd;
344
+ // A card plan is not renewed by card any more: at its period end it moves to the balance by itself (one
345
+ // whose period ends within 7 days after the email announcing the move renews once more by card first),
346
+ // and one that was cancelled moves there when the cancellation is undone.
347
+ const ends = cancelled || agent.subscription?.atPeriodEnd === 'ends';
348
+ if (!ends) {
319
349
  return {
320
- outcome: 'refused',
321
- message: atPeriodEnd === 'ends'
322
- ? `This plan is billed by card and is set to stop renewing after ${periodEnd}. Card plans are managed `
323
- + `from the dashboard, where it can be kept: ${agent.dashboardUrl}`
324
- : atPeriodEnd === 'renews'
325
- ? `This plan is billed by card and renews by itself. It is managed from the dashboard: ${agent.dashboardUrl}`
326
- : `This plan is billed by card and is paid through ${periodEnd}. Card plans are renewed or cancelled `
327
- + `from the dashboard: ${agent.dashboardUrl}`,
350
+ outcome: 'not_needed',
351
+ message: prepaid
352
+ ? 'The plan is active and renews by itself. Nothing to do.'
353
+ : `This plan is paid by card through ${periodEnd}. Then it moves to ${balance} and renews from it every 30 days by itself.`
354
+ + `${cardPlanOnceMoreNote(agent.subscription)} Nothing to do.`,
328
355
  };
329
356
  }
330
- if (!cancelled) {
331
- return { outcome: 'not_needed', message: 'The plan is active and renews by itself. Nothing to do.' };
332
- }
333
357
  // A renewal charges the plan set for it, or the agent's own, at today's price. A wallet cancel keeps a
334
358
  // move set for the renewal, so the plan is named: it can be another plan than the agent's.
335
359
  const next = renewalPlanPrice(agent);
@@ -341,17 +365,20 @@ async function planFor(client, action, agent, raw, input, signal) {
341
365
  chargeNowUsd: 0,
342
366
  estimated: false,
343
367
  recurringUsd: amount,
344
- monthlyCredits: next?.monthlyCredits ?? agent.credits.renewal ?? agent.credits.monthly,
368
+ includedUsageUsd: next?.includedUsageUsd ?? agent.usage.renewalUsd ?? agent.usage.includedUsd,
345
369
  paidFrom,
346
370
  ...(renewsOn ? { plan: renewsOn } : {}),
347
371
  },
348
- message: `Undo the cancellation: nothing is charged now. The plan then renews${renewsOn ? ` on ${planName(renewsOn)}` : ''} from ${wallet} for ${formatUsd(amount)} after ${periodEnd} and every 30 days after that until it is cancelled.`,
349
- confirmReason: 'Ask the user to confirm first: the plan will charge the wallet again at each renewal.',
372
+ message: `Undo the cancellation: nothing is charged now.${prepaid ? '' : ` The plan stays paid by card through ${periodEnd}.`} `
373
+ + `The plan then renews${renewsOn ? ` on ${planName(renewsOn)}` : ''} for ${formatUsd(amount)} after ${periodEnd} and every 30 days after that until it is cancelled, paid from ${balance}.`,
374
+ confirmReason: 'Ask the user to confirm first: the plan will charge the Wiro balance again at each renewal.',
350
375
  perform: async (signal) => {
351
376
  requireApiSuccess(await client.post('/UserAgent/RenewSubscription', { guid }, signal), 'The cancellation could not be undone.');
352
377
  return {
353
378
  outcome: 'done',
354
- message: 'The cancellation was undone. The plan keeps renewing every 30 days.',
379
+ message: prepaid
380
+ ? 'The cancellation was undone. The plan keeps renewing every 30 days.'
381
+ : `The cancellation was undone. The plan is paid by card through ${periodEnd}, then renews from ${balance} every 30 days.`,
355
382
  result: { chargedUsd: 0, renewal: 'undo_cancel' },
356
383
  };
357
384
  },
@@ -367,20 +394,14 @@ async function planFor(client, action, agent, raw, input, signal) {
367
394
  nextAction: billingCall(guid, 'subscribe'),
368
395
  };
369
396
  }
370
- if (!prepaid) {
371
- return {
372
- outcome: 'refused',
373
- message: 'The expired plan was billed by card. Use action subscribe to start a new plan paid from the wallet.',
374
- nextAction: billingCall(guid, 'subscribe'),
375
- };
376
- }
397
+ // A plan that ended by card starts again from the balance too.
377
398
  const own = agent.monthlyPriceUsd ?? toNumber(raw.amount);
378
399
  const planKey = asPlan(agent.nextPlan) ?? asPlan(agent.tier);
379
400
  // A renewal charges the plan set for it, or the agent's own, at its price today, which can differ
380
401
  // from the price the plan ended at.
381
402
  const today = renewalPlanPrice(agent);
382
403
  const earlier = today && own && own > 0 && !sameAmount(today.priceUsd, own)
383
- ? ` The plan ended at ${formatUsd(own)} a month; it renews at the ${planName(planKey)} price today, with ${formatCredits(today.monthlyCredits)} credits per month.`
404
+ ? ` The plan ended at ${formatUsd(own)} a month; it renews at the ${planName(planKey)} price today, including ${formatUsd(today.includedUsageUsd)} of AI usage a month.`
384
405
  : '';
385
406
  const price = today?.priceUsd ?? own;
386
407
  if (!price || price <= 0) {
@@ -396,25 +417,25 @@ async function planFor(client, action, agent, raw, input, signal) {
396
417
  chargeNowUsd: price,
397
418
  estimated: false,
398
419
  recurringUsd: price,
399
- monthlyCredits: today?.monthlyCredits ?? null,
420
+ includedUsageUsd: today?.includedUsageUsd ?? null,
400
421
  paidFrom,
401
422
  ...(planKey ? { plan: planKey } : {}),
402
423
  },
403
- message: `Renew the expired plan${planKey ? ` on ${planName(planKey)}` : ''}: ${formatUsd(price)} now from ${wallet}, then every 30 days until it is cancelled.${earlier} A stopped or failed agent is queued to start again.`,
424
+ message: `Renew the expired plan${planKey ? ` on ${planName(planKey)}` : ''}: ${formatUsd(price)} now, paid from ${balance}, then every 30 days until it is cancelled.${earlier} A stopped or failed agent is queued to start again.`,
404
425
  perform: async (signal) => {
405
426
  const body = requireApiSuccess(await client.post('/UserAgent/RenewSubscription', { guid }, signal), 'The plan could not be renewed.');
406
427
  const monthly = toNumber(body.amount) ?? price;
407
428
  const paid = walletPaid(body, monthly);
408
- const credits = toNumber(body.monthlycredits);
409
429
  // The plan it renewed on, which the wallet line names too.
410
430
  const renewedOn = asPlan(body.tier) ?? planKey;
431
+ const included = renewedOn ? agent.pricing?.[renewedOn]?.includedUsageUsd : undefined;
411
432
  return {
412
433
  outcome: 'done',
413
- message: `Renewed${renewedOn ? ` on ${planName(renewedOn)}` : ''} and charged ${paid.text} from ${wallet}. The plan renews every 30 days until it is cancelled.`,
434
+ message: `Renewed${renewedOn ? ` on ${planName(renewedOn)}` : ''} and charged ${paid.text} from ${balance}. The plan renews from it every 30 days until it is cancelled.`,
414
435
  result: {
415
436
  chargedUsd: paid.chargedUsd,
416
437
  monthlyPriceUsd: monthly,
417
- ...(credits !== null ? { monthlyCredits: credits } : {}),
438
+ ...(included !== undefined ? { includedUsageUsd: included } : {}),
418
439
  ...(renewedOn ? { plan: renewedOn } : {}),
419
440
  renewal: 'renewed',
420
441
  },
@@ -445,26 +466,17 @@ async function planFor(client, action, agent, raw, input, signal) {
445
466
  };
446
467
  };
447
468
  if (!prepaid) {
448
- // A plan moving to wallet billing has no cancel in the dashboard either: it can be cancelled once the wallet bills it.
449
- if (raw?.nextprovider === 'prepaid') {
450
- return {
451
- outcome: 'refused',
452
- message: `A switch to wallet billing is already scheduled for this plan, so it cannot be cancelled now. After ${periodEnd} it is billed from the wallet, and action cancel then stops its renewals.`,
453
- };
454
- }
455
- if (agent.workspace === 'personal') {
456
- return {
457
- outcome: 'refused',
458
- message: `This plan is billed by card. Card plans are cancelled from the dashboard: ${agent.dashboardUrl}`,
459
- };
460
- }
461
- if (agent.subscription?.cancelAtPeriodEnd) {
469
+ // A card plan, its owner's or (on a team agent) a billing admin's to cancel: it ends with its period and
470
+ // no longer moves to the balance; renew undoes that before then.
471
+ if (cancelled || agent.subscription?.cancelAtPeriodEnd) {
462
472
  return { outcome: 'not_needed', message: `The plan is already set to end after ${periodEnd}.` };
463
473
  }
464
474
  return {
465
475
  outcome: 'quote',
466
476
  quote: { chargeNowUsd: 0, estimated: false, paidFrom: 'card' },
467
- message: `Cancel the team's card plan at the end of the current period (${periodEnd}). Nothing is refunded.${dropsMove}`,
477
+ message: `Cancel the card plan at the end of its period (${periodEnd}): nothing is charged or refunded, and `
478
+ + `it does not move to ${balance}. The agent keeps working until then, then stops. Action renew undoes the `
479
+ + `cancellation before then.${dropsMove}`,
468
480
  confirmReason: 'Ask the user to confirm the cancellation first.',
469
481
  perform: performCancel,
470
482
  };
@@ -475,7 +487,8 @@ async function planFor(client, action, agent, raw, input, signal) {
475
487
  return {
476
488
  outcome: 'quote',
477
489
  quote: { chargeNowUsd: 0, estimated: false, paidFrom },
478
- message: `Cancel the plan: nothing is refunded and it stops renewing. The agent keeps its monthly credits until about a day after ${periodEnd}; then the monthly credits end and the agent stops unless it has extra credits left. Action renew undoes the cancellation before then.${keepsMove}`,
490
+ // Wiro ends a cancelled wallet plan at its period end, on its first check after it.
491
+ message: `Cancel the plan: nothing is refunded and it stops renewing. The agent keeps its plan and the AI usage it includes until ${periodEnd}; then the plan ends and the agent stops. Action renew undoes the cancellation before then.${keepsMove}`,
479
492
  confirmReason: 'Ask the user to confirm the cancellation first.',
480
493
  perform: performCancel,
481
494
  };
@@ -499,11 +512,12 @@ async function planFor(client, action, agent, raw, input, signal) {
499
512
  const open = unsettled('A plan change needs an active plan.');
500
513
  if (open)
501
514
  return { outcome: 'refused', message: open };
502
- // A wallet plan that ended comes back with renew on the plan set for its renewal, else on its own
503
- // plan, so renew answers a target that is that plan; any other target takes a new plan. When the plan
504
- // ends, Wiro writes that plan on the agent: the one set for its renewal, else the one nearest its last price.
515
+ // A plan that ended, by card or from the wallet, comes back from the balance with renew on the plan set
516
+ // for its renewal, else on its own plan, so renew answers a target that is that plan; any other target
517
+ // takes a new plan. When the plan ends, Wiro writes that plan on the agent: the one set for its renewal,
518
+ // else the one nearest its last price.
505
519
  const renewsOn = asPlan(agent.nextPlan) ?? current;
506
- if (renewsOn === target && raw?.status === 'expired' && prepaid) {
520
+ if (renewsOn === target && raw?.status === 'expired') {
507
521
  return {
508
522
  outcome: 'refused',
509
523
  message: renewsOn === current
@@ -521,10 +535,9 @@ async function planFor(client, action, agent, raw, input, signal) {
521
535
  if (!current)
522
536
  throw new Error('The agent\'s plan could not be read, so it cannot be changed right now. Try again later.');
523
537
  const next = asPlan(agent.nextPlan) ?? null;
524
- const when = agent.subscription?.periodEndsAt ? `the renewal after ${agent.subscription.periodEndsAt}` : 'the next renewal';
538
+ const renewsAt = renewalMoment(agent.subscription);
539
+ const when = renewsAt ? `the renewal after ${renewsAt}` : 'the next renewal';
525
540
  const move = comparePlans(target, current);
526
- // Wiro changes a team's card plan only in the dashboard, not with a project's key.
527
- const teamCard = route === 'card' && agent.workspace === 'team';
528
541
  if (move === 0) {
529
542
  if (!next || next === current) {
530
543
  return {
@@ -534,10 +547,7 @@ async function planFor(client, action, agent, raw, input, signal) {
534
547
  : `The agent is already on ${planName(current)}. Nothing to do.`,
535
548
  };
536
549
  }
537
- // A move to another plan is set for the next renewal: keeping this one undoes it. A team's card
538
- // plan changes only in the dashboard.
539
- if (teamCard)
540
- return { outcome: 'refused', message: cardPlan(`keep it on ${planName(current)}`) };
550
+ // A move to another plan is set for the next renewal: keeping this one undoes it.
541
551
  const keep = agent.pricing?.[current];
542
552
  return {
543
553
  outcome: 'quote',
@@ -545,8 +555,8 @@ async function planFor(client, action, agent, raw, input, signal) {
545
555
  chargeNowUsd: 0,
546
556
  estimated: false,
547
557
  recurringUsd: keep?.priceUsd ?? null,
548
- monthlyCredits: keep?.monthlyCredits ?? null,
549
- paidFrom: route === 'card' ? 'card' : paidFrom,
558
+ includedUsageUsd: keep?.includedUsageUsd ?? null,
559
+ paidFrom,
550
560
  plan: current,
551
561
  change: 'undo_downgrade',
552
562
  },
@@ -556,14 +566,13 @@ async function planFor(client, action, agent, raw, input, signal) {
556
566
  perform: async (signal) => {
557
567
  const body = requireApiSuccess(await client.post('/UserAgent/UpgradeTier', { guid, targetTier: current }, signal), 'The move set for the next renewal could not be undone.');
558
568
  if (asString(body.url))
559
- return { outcome: 'refused', message: cardPlan(`keep it on ${planName(current)}`) };
569
+ return { outcome: 'refused', message: checkoutAnswer(`keep the plan on ${planName(current)}`) };
560
570
  // An agent on a price from before the plans keeps its plan with that plan set for its renewal, so
561
571
  // the renewal bills the plan's own price.
562
572
  if (asPlan(body.nextplan) === current) {
563
- const at = unixToIso(body.startsAt ?? body.periodEnd) ?? agent.subscription?.periodEndsAt;
573
+ const at = unixToIso(body.startsAt ?? body.periodEnd) ?? renewsAt;
564
574
  const priceUsd = toNumber(body.newPriceUsd) ?? keep?.priceUsd;
565
- const monthlyCredits = toNumber(body.newMonthlyCredits) ?? keep?.monthlyCredits;
566
- const terms = priceUsd !== undefined && monthlyCredits !== undefined ? `, ${planTerms({ priceUsd, monthlyCredits })}` : '';
575
+ const terms = priceUsd !== undefined ? `, ${planTerms({ priceUsd, includedUsageUsd: keep?.includedUsageUsd ?? priceUsd })}` : '';
567
576
  return {
568
577
  outcome: 'done',
569
578
  message: `The move to ${planName(next)} is undone. The agent stays on ${planName(current)}, and nothing was charged. `
@@ -584,31 +593,32 @@ async function planFor(client, action, agent, raw, input, signal) {
584
593
  };
585
594
  }
586
595
  if (move > 0) {
587
- // No checkout pages are opened for card plans: the user pays them in the dashboard.
588
- if (route === 'card')
589
- return { outcome: 'refused', message: cardPlan(`move it to ${planName(target)}`) };
590
596
  const preview = await readPlanPreview(client, guid, target, signal);
597
+ // Wiro refuses a move to a larger plan while the plan's renewal is due, and charges nothing. Its pricing
598
+ // answer says so in the same words, in place of a charge, so nothing is quoted or sent.
599
+ if (preview?.change?.refusal)
600
+ return { outcome: 'refused', message: preview.change.refusal };
591
601
  const targetPrice = preview?.price ?? agent.pricing?.[target];
592
602
  if (!targetPrice)
593
603
  throw new Error(`The ${planName(target)} price of this agent is not available right now. Try again later.`);
594
- const ending = `The plan is cancelled, so it ends about a day after ${periodEnd} and does not renew on ${planName(target)}; this charge covers only the time left. To keep the plan, undo the cancellation first with action renew.`;
604
+ const ending = `The plan is cancelled, so it ends at ${periodEnd} and does not renew on ${planName(target)}; this charge covers only the time left. To keep the plan, undo the cancellation first with action renew.`;
595
605
  const currentPrice = agent.monthlyPriceUsd || agent.subscription?.amountUsd || 0;
596
606
  const fullDifference = roundUsd(Math.max(0, targetPrice.priceUsd - currentPrice));
597
- // A wallet plan pays the amount Wiro works out on it now. A card plan moving to wallet billing is
598
- // charged from the wallet for the time left of its card period, which Wiro works out at the change.
607
+ // A wallet plan pays the amount Wiro works out on it now. A card plan is charged from the balance for
608
+ // the time left of its card period, which Wiro works out at the change.
599
609
  const change = preview?.change?.wallet ? preview.change : null;
600
610
  const exact = change?.chargeNowUsd ?? null;
601
- const renewalCredits = change?.creditsFromRenewal ?? targetPrice.monthlyCredits;
602
- const creditsNow = change?.creditsNow ?? null;
611
+ const renewalUsd = change?.includedFromRenewalUsd ?? targetPrice.includedUsageUsd;
612
+ const nowUsd = change?.includedNowUsd ?? null;
603
613
  const days = daysLeftText(change?.secondsLeft ?? null);
604
614
  const undoes = next && next !== current ? ` This also undoes the move to ${planName(next)} set for the next renewal.` : '';
605
615
  const money = exact !== null
606
- ? `Move to ${planName(target)}: ${formatUsd(exact)} now from ${wallet} for the rest of this period`
616
+ ? `Move to ${planName(target)}: ${formatUsd(exact)} now, paid from ${balance}, for the rest of this period`
607
617
  + `${exact > 0 && underOneDayLeft(change?.secondsLeft ?? null) ? ', at the one-day minimum' : days ? ` (${days})` : ''}. `
608
- : `Move to ${planName(target)}: the difference for the rest of this period is taken from ${wallet} now. Wiro works it out from the time left when the plan changes, and it is never more than ${formatUsd(fullDifference)}, so that is the amount to approve. `;
609
- const credits = creditsNow !== null
610
- ? upgradeCreditsText(creditsNow, cancelled ? '' : `, and every renewal gives ${formatCredits(renewalCredits)}`, false)
611
- : `The added credits come for the time left in this period${cancelled ? '' : `, and every renewal gives ${formatCredits(renewalCredits)}`}. `;
618
+ : `Move to ${planName(target)}: the difference for the rest of this period is paid from ${balance} now. Wiro works it out from the time left when the plan changes, and it is never more than ${formatUsd(fullDifference)}, so that is the amount to approve. `;
619
+ const usage = nowUsd !== null
620
+ ? upgradeUsageText(nowUsd, cancelled ? '' : `, and every renewal includes ${formatUsd(renewalUsd)}`, false)
621
+ : `The added AI usage comes for the time left in this period${cancelled ? '' : `, and every renewal includes ${formatUsd(renewalUsd)}`}. `;
612
622
  return {
613
623
  outcome: 'quote',
614
624
  quote: {
@@ -616,41 +626,42 @@ async function planFor(client, action, agent, raw, input, signal) {
616
626
  estimated: exact === null,
617
627
  maxChargeUsd: exact ?? fullDifference,
618
628
  recurringUsd: cancelled ? null : targetPrice.priceUsd,
619
- monthlyCredits: renewalCredits,
620
- ...(creditsNow !== null ? { creditsNow } : {}),
629
+ includedUsageUsd: renewalUsd,
630
+ ...(nowUsd !== null ? { includedUsageNowUsd: nowUsd } : {}),
621
631
  paidFrom,
622
632
  plan: target,
623
633
  change: 'upgrade',
624
634
  },
625
- message: money + credits
635
+ message: money + usage
626
636
  + (cancelled ? `${ending} ` : `From the next renewal the plan costs ${formatUsd(targetPrice.priceUsd)} every 30 days. `)
627
637
  + `${planChangeAgentNote(agent.status, 'the plan change', true)}${undoes} A move to a smaller plan later starts at the renewal after it is asked for, with nothing refunded.`,
628
638
  perform: async (signal) => {
629
639
  const body = requireApiSuccess(await client.post('/UserAgent/UpgradeTier', { guid, targetTier: target }, signal), 'The plan could not be changed.');
630
- if (asString(body.url)) {
631
- // A checkout link means the plan is paid by card, and card payments are made in the dashboard.
632
- return { outcome: 'refused', message: cardPlan(`move it to ${planName(target)}`) };
633
- }
640
+ if (asString(body.url))
641
+ return { outcome: 'refused', message: checkoutAnswer(`move the plan to ${planName(target)}`) };
634
642
  const charged = toNumber(body.proratedCharge) ?? toNumber(body.chargedUsd);
635
643
  const newPrice = toNumber(body.newPriceUsd) ?? targetPrice.priceUsd;
636
- const fromRenewal = toNumber(body.creditsFromRenewal) ?? toNumber(body.newMonthlyCredits) ?? renewalCredits;
637
- const came = toNumber(body.creditsNow);
644
+ // Wiro answers the included usage in hundredths of a dollar.
645
+ const fromRenewalCents = toNumber(body.creditsFromRenewal) ?? toNumber(body.newMonthlyCredits);
646
+ const fromRenewal = fromRenewalCents !== null ? centsToUsd(fromRenewalCents) : renewalUsd;
647
+ const cameCents = toNumber(body.creditsNow);
648
+ const came = cameCents !== null ? centsToUsd(cameCents) : null;
638
649
  const previous = asString(body.previousTier);
639
650
  return {
640
651
  outcome: 'done',
641
- message: `Moved to ${planName(target)} and charged ${formatUsd(charged ?? 0)} from ${wallet}. `
652
+ message: `Moved to ${planName(target)} and charged ${formatUsd(charged ?? 0)} from ${balance}. `
642
653
  + (came !== null
643
- ? upgradeCreditsText(came, cancelled ? '' : `, and every renewal gives ${formatCredits(fromRenewal)}`, true)
654
+ ? upgradeUsageText(came, cancelled ? '' : `, and every renewal includes ${formatUsd(fromRenewal)}`, true)
644
655
  : '')
645
656
  + (cancelled
646
- ? `The plan is still cancelled and ends about a day after ${periodEnd}; action renew undoes the cancellation. `
657
+ ? `The plan is still cancelled and ends at ${periodEnd}; action renew undoes the cancellation. `
647
658
  : `The plan now costs ${formatUsd(newPrice)} every 30 days. `)
648
659
  + planChangeAgentNote(agent.status, 'the plan change'),
649
660
  result: {
650
661
  chargedUsd: charged,
651
662
  monthlyPriceUsd: newPrice,
652
- monthlyCredits: fromRenewal,
653
- ...(came !== null ? { creditsNow: came } : {}),
663
+ includedUsageUsd: fromRenewal,
664
+ ...(came !== null ? { includedUsageNowUsd: came } : {}),
654
665
  plan: target,
655
666
  ...(previous ? { previousPlan: previous } : {}),
656
667
  change: 'upgrade',
@@ -665,146 +676,72 @@ async function planFor(client, action, agent, raw, input, signal) {
665
676
  if (cancelled || agent.subscription?.atPeriodEnd === 'ends') {
666
677
  return {
667
678
  outcome: 'refused',
668
- message: `The plan is set to end after ${periodEnd}, so it does not renew on another plan. To keep the agent on ${planName(target)}, `
669
- + (route === 'card' && !cancelled
670
- ? `keep the plan in the dashboard first (${agent.dashboardUrl}), then change the plan.`
671
- : 'undo the cancellation first with action renew, then change the plan.'),
672
- ...(cancelled ? { nextAction: billingCall(guid, 'renew') } : {}),
679
+ message: `The plan is set to end after ${periodEnd}, so it does not renew on another plan. To keep the agent on `
680
+ + `${planName(target)}, undo the cancellation first with action renew, then change the plan.`,
681
+ nextAction: billingCall(guid, 'renew'),
673
682
  };
674
683
  }
675
684
  if (next === target) {
676
685
  return {
677
686
  outcome: 'not_needed',
678
- message: `The move to ${planName(target)} is already set: it starts with ${when}. Until then the agent keeps ${planName(current)} and its credits.`,
687
+ message: `The move to ${planName(target)} is already set: it starts with ${when}. Until then the agent keeps ${planName(current)} and the AI usage it includes.`,
679
688
  };
680
689
  }
681
- if (teamCard)
682
- return { outcome: 'refused', message: cardPlan(`move it to ${planName(target)}`) };
683
690
  const smaller = agent.pricing?.[target];
684
- const card = route === 'card';
685
- const startsAt = agent.subscription?.periodEndsAt;
691
+ const startsAt = renewsAt;
686
692
  return {
687
693
  outcome: 'quote',
688
694
  quote: {
689
695
  chargeNowUsd: 0,
690
696
  estimated: false,
691
697
  recurringUsd: smaller?.priceUsd ?? null,
692
- monthlyCredits: smaller?.monthlyCredits ?? null,
693
- paidFrom: card ? 'card' : paidFrom,
698
+ includedUsageUsd: smaller?.includedUsageUsd ?? null,
699
+ paidFrom,
694
700
  plan: target,
695
701
  change: 'downgrade',
696
702
  ...(startsAt ? { startsAt } : {}),
697
703
  },
698
- message: `Move to ${planName(target)} at the next renewal: nothing is charged or refunded now. The agent keeps ${planName(current)} and its credits until ${periodEnd}. `
699
- + `From ${when} the plan is ${planName(target)}${smaller ? `, ${planTerms(smaller)}` : ''}, ${card ? 'paid by card' : `paid from ${wallet}`}. `
704
+ message: `Move to ${planName(target)} at the next renewal: nothing is charged or refunded now. The agent keeps ${planName(current)} and the AI usage it includes until ${periodEnd}. `
705
+ + `From ${when} the plan is ${planName(target)}${smaller ? `, ${planTerms(smaller)}` : ''}, paid from ${balance}. `
700
706
  + `Asking for ${planName(current)} again before then undoes the move.`,
701
- confirmReason: 'Ask the user to confirm first: from the next renewal the agent has the smaller plan\'s credits.',
707
+ confirmReason: 'Ask the user to confirm first: from the next renewal the agent has the smaller plan\'s included AI usage.',
702
708
  perform: async (signal) => {
703
709
  // Wiro moves an agent to a smaller plan only when the request says so: a bare smaller plan is
704
710
  // refused, so an older client that asks for one as an upgrade changes nothing.
705
711
  const body = requireApiSuccess(await client.post('/UserAgent/UpgradeTier', { guid, targetTier: target, allowDowngrade: true }, signal), 'The move to the smaller plan could not be set.');
706
712
  if (asString(body.url))
707
- return { outcome: 'refused', message: cardPlan(`move it to ${planName(target)}`) };
713
+ return { outcome: 'refused', message: checkoutAnswer(`move the plan to ${planName(target)}`) };
708
714
  const at = unixToIso(body.startsAt ?? body.effectiveAt ?? body.periodEnd) ?? startsAt;
709
715
  return {
710
716
  outcome: 'done',
711
- message: `The move to ${planName(target)} is set: it starts with the renewal after ${at ?? 'this period'}. Until then the agent keeps ${planName(current)} and its credits. Nothing was charged or refunded.`,
717
+ message: `The move to ${planName(target)} is set: it starts with the renewal after ${at ?? 'this period'}. Until then the agent keeps ${planName(current)} and the AI usage it includes. Nothing was charged or refunded.`,
712
718
  result: { chargedUsd: 0, plan: current, nextPlan: target, change: 'downgrade', ...(at ? { startsAt: at } : {}) },
713
719
  };
714
720
  },
715
721
  verify: after => (after.nextPlan !== target ? `get_my_agent does not show the move to ${planName(target)} yet; check it again in a minute.` : null),
716
722
  };
717
723
  }
718
- case 'buy_credits': {
719
- if (!active) {
720
- const open = unsettled('Extra credits need an active plan.');
721
- return { outcome: 'refused', message: open ?? 'Extra credits need an active plan. Use action subscribe or renew first.' };
722
- }
723
- if (route === 'card')
724
- return { outcome: 'refused', message: cardPlan('buy the pack') };
725
- const packs = agent.extraCreditPacks;
726
- const packList = packs.map(item => `${item.pack} (${formatCredits(item.credits)} credits for ${formatUsd(item.priceUsd)})`).join(', ');
727
- if (!input.pack) {
728
- return {
729
- outcome: 'refused',
730
- ...(packs.length > 0 ? { heading: 'Available packs' } : {}),
731
- message: packs.length > 0 ? `Choose a pack: ${packList}.` : 'No extra credit packs are available for this agent yet.',
732
- ...(packs[0] ? { nextAction: billingCall(guid, 'buy_credits', { pack: packs[0].pack }) } : {}),
733
- };
734
- }
735
- const chosen = packs.find(item => item.pack === input.pack);
736
- if (!chosen) {
737
- return {
738
- outcome: 'refused',
739
- message: `The ${input.pack} pack is not available for this agent.${packList ? ` Available: ${packList}.` : ''}`,
740
- };
741
- }
742
- return {
743
- outcome: 'quote',
744
- quote: { chargeNowUsd: chosen.priceUsd, estimated: false, creditsAdded: chosen.credits, paidFrom, pack: chosen.pack },
745
- message: `Buy the ${chosen.pack} pack: ${formatUsd(chosen.priceUsd)} now from ${wallet} for ${formatCredits(chosen.credits)} extra credits, added at once. Extra credits are used after the monthly credits, do not reset each month and end 6 months (180 days) after purchase. ${planChangeAgentNote(agent.status, 'a credit pack', true)} This is a one-time charge.`,
746
- perform: async (signal) => {
747
- const body = requireApiSuccess(await client.post('/UserAgent/CreateExtraCreditCheckout', {
748
- useragentguid: guid,
749
- pack: chosen.pack,
750
- requestid: input.requestId,
751
- }, signal), 'The credit pack could not be bought.');
752
- if (asString(body.url))
753
- return { outcome: 'refused', message: cardPlan('buy the pack') };
754
- return {
755
- outcome: 'done',
756
- message: `Bought the ${chosen.pack} pack: ${formatCredits(chosen.credits)} credits for ${formatUsd(chosen.priceUsd)} from ${wallet}. The credits are added. ${planChangeAgentNote(agent.status, 'a credit pack')}`,
757
- result: { chargedUsd: chosen.priceUsd, creditsAdded: chosen.credits },
758
- nextAction: waitIfStarting(agent),
759
- };
760
- },
761
- };
762
- }
724
+ case 'buy_credits':
725
+ // Retired: nothing is quoted, sent or charged.
726
+ return { outcome: 'refused', heading: 'Retired', message: packsRetiredText(agent) };
763
727
  }
764
728
  }
765
729
  /** The arguments that repeat a quoted action with the user's approval. */
766
- function confirmArguments(guid, action, quote, requestId) {
730
+ function confirmArguments(guid, action, quote) {
767
731
  const amount = approvalAmountOf(action, quote);
768
732
  return {
769
733
  agent_guid: guid,
770
734
  action,
771
735
  ...((action === 'subscribe' || action === 'change_plan') && quote?.plan ? { plan: quote.plan } : {}),
772
- ...(quote?.pack ? { pack: quote.pack } : {}),
773
- ...(requestId ? { request_id: requestId } : {}),
774
736
  ...(amount !== null ? { confirm_charge_usd: amount } : {}),
775
737
  confirm: true,
776
738
  };
777
739
  }
778
- function retryPurchaseText(guid, quote, requestId) {
779
- const amount = chargeOf(quote);
780
- return `To retry, call manage_agent_billing again with agent_guid "${guid}", action buy_credits, pack "${quote?.pack ?? ''}", request_id "${requestId}"${amount !== null ? `, confirm_charge_usd ${amount}` : ''} and confirm: true. That request id never charges twice, and repeating it completes this same purchase. Do not get a new quote for this purchase: a new request id is a new purchase.`
781
- + (amount !== null ? ` This request id works only while the pack costs ${formatUsd(amount)}. If the price changes, do not buy again: check get_my_agent and the wallet balance with get_account, and if the balance changed, contact Wiro support.` : '');
782
- }
783
- /**
784
- * Whether the agent's packs show an active one of this size bought since
785
- * the request was sent, or null when they cannot be read. A lot is dated
786
- * when the purchase starts, before the wallet is charged; the margin covers
787
- * a local clock that differs from Wiro's.
788
- */
789
- async function freshPackShows(client, guid, credits, sentAtMs, signal) {
790
- try {
791
- const ledger = requireApiSuccess(await client.post('/UserAgent/TransactionList', { useragentguid: guid, limit: 1, start: 0 }, signal), 'The credit history could not be read.');
792
- const summary = isPlainObject(ledger.summary) ? ledger.summary : {};
793
- const lots = Array.isArray(summary.extrapacks) ? summary.extrapacks.filter(isPlainObject) : [];
794
- const since = sentAtMs / 1000 - 900;
795
- return lots.some(lot => lot.status === 'active'
796
- && toNumber(lot.credits) === credits
797
- && (toNumber(lot.purchasedat) ?? 0) >= since);
798
- }
799
- catch {
800
- return null;
801
- }
802
- }
803
740
  /**
804
741
  * After a paid request whose answer did not confirm it, reads the agent again
805
742
  * and says what it shows.
806
743
  */
807
- async function observeOpenOutcome(client, action, before, quote, requestId, sentAtMs, signal) {
744
+ async function observeOpenOutcome(client, action, before, quote, signal) {
808
745
  let row;
809
746
  try {
810
747
  row = await readAgentDetail(client, before.guid, signal);
@@ -859,37 +796,6 @@ async function observeOpenOutcome(client, action, before, quote, requestId, sent
859
796
  : `The agent still shows ${planName(after.tier) || 'its earlier plan'}. Check get_my_agent and the wallet balance with get_account before trying again; if the balance changed, contact Wiro support.`,
860
797
  };
861
798
  }
862
- case 'buy_credits': {
863
- const credits = quote?.creditsAdded ?? 0;
864
- const rose = after.credits.extra - before.credits.extra;
865
- const bought = { chargedUsd: charged, creditsAdded: credits };
866
- if (credits > 0 && rose >= credits / 2) {
867
- return {
868
- happened: true,
869
- row,
870
- text: `The agent's extra credits rose by ${formatCredits(rose)}, so the purchase went through. Do not buy it again.`,
871
- result: bought,
872
- nextAction: waitIfStarting(before),
873
- };
874
- }
875
- const fresh = await freshPackShows(client, before.guid, credits, sentAtMs, signal);
876
- if (fresh) {
877
- // The pack shows on the agent. If its credits do not show yet, the same
878
- // request id completes the purchase without a second charge.
879
- return {
880
- happened: true,
881
- row,
882
- text: 'A new pack of that size shows on the agent, so the purchase went through. Do not buy it again. '
883
- + `If get_my_agent does not show its credits in a few minutes, repeat this purchase with the same request_id "${requestId ?? ''}" and confirm_charge_usd ${charged ?? ''}; that request id never charges twice.`,
884
- result: bought,
885
- nextAction: waitAction(before.guid, 'Check that the pack\'s credits show on the agent.'),
886
- };
887
- }
888
- return {
889
- happened: false,
890
- text: fresh === false ? 'No new pack shows on the agent yet.' : 'The agent\'s packs could not be read to check it.',
891
- };
892
- }
893
799
  default:
894
800
  return { happened: false, text: '' };
895
801
  }
@@ -902,22 +808,22 @@ const RENEWAL_REPRICED = /^(This plan now renews on the .+? plan at \$[\d.,]+ a
902
808
  const SMALLER_PLAN_REFUSAL = /^The \w+ plan is smaller than this agent's \w+ plan, so this is not an upgrade\. Nothing was changed\./i;
903
809
  // Code 104: another payment from the same wallet, or another change to the agent's plan, was going through.
904
810
  const BUSY_NOTE = 'Nothing was charged or changed, and it is not a low balance. Offer to try again in a minute.';
905
- function annotateKnownRefusal(error, requestId) {
811
+ /** workspace: the agent's, whose Wiro balance pays for its plan. */
812
+ function annotateKnownRefusal(error, workspace) {
906
813
  const text = error.message;
907
- if (error.codes.some(code => Number(code) === 104)) {
908
- return new Error(`${text}\n\n${BUSY_NOTE}${requestId ? ` To try again, repeat the call with request_id "${requestId}"; that request id never charges twice.` : ''}`);
909
- }
814
+ if (hasErrorCode(error, 104))
815
+ return new Error(`${text}\n\n${BUSY_NOTE}`);
910
816
  if (isWalletNotRead(error))
911
817
  return new Error(`${text}\n\n${WALLET_NOT_READ_NOTE}`);
912
818
  if (SMALLER_PLAN_REFUSAL.test(text)) {
913
819
  // A move this server sent as one to a larger plan: the agent's plan moved up after it was read.
914
820
  return new Error(`${text}\n\nNothing was charged: the agent's plan changed after it was read. get_my_agent shows the plan it is on now, and change_plan quotes a move from it.`);
915
821
  }
916
- if (/insufficient wallet balance/i.test(text)) {
917
- return new Error(`${text}\n\nNothing was charged. Funds are added at https://wiro.ai/panel/wallet/deposit/credit-card (for a team project, select that team in the dashboard first); once the user has added them and says yes, try again. get_account shows the balance.`);
918
- }
919
- if (/purchase request id was already used/i.test(text)) {
920
- return new Error(`${text}\n\nNothing was charged now. This request id belongs to an earlier purchase of another pack or at another price. For a new purchase, get a new quote without request_id. If the earlier purchase with this id ended without a clear result, do not buy again: check get_my_agent and the wallet balance with get_account, and if the balance changed, contact Wiro support.`);
822
+ const short = balanceShortfall(error);
823
+ if (short) {
824
+ const team = workspace === 'team' ? 'select the agent\'s team in the dashboard first' : workspace ? '' : 'for a team agent, select its team in the dashboard first';
825
+ return new Error(`${text}\n\n${shortBalanceNote(short.neededUsd, team)} Once the user has added them and says yes, `
826
+ + 'confirm the same quote again. get_account shows the balance.');
921
827
  }
922
828
  const hint = workspaceHint(text);
923
829
  if (hint)
@@ -926,10 +832,11 @@ function annotateKnownRefusal(error, requestId) {
926
832
  }
927
833
  export function registerManageAgentBilling(server, client) {
928
834
  server.registerTool('manage_agent_billing', {
929
- title: 'Manage a Wiro agent\'s plan and credits',
930
- description: 'Pay for, renew, change or cancel a deployed agent\'s plan, or buy extra credits. An agent has '
931
- + 'one of three plans, smallest first: Starter, Pro or Max. Each has a fixed monthly price and monthly credits, '
932
- + 'and every plan includes every skill. Charges come from the Wiro wallet of the agent\'s workspace (the team '
835
+ title: 'Manage a Wiro agent\'s plan',
836
+ description: 'Pay for, renew, change or cancel a deployed agent\'s plan. An agent has '
837
+ + 'one of three plans, smallest first: Starter, Pro or Max. Each has a fixed monthly price that it also '
838
+ + 'includes as AI usage each month, and every plan includes every '
839
+ + 'skill. After the included usage, the agent uses the Wiro balance of its workspace. Charges come from the Wiro balance of the agent\'s workspace (the team '
933
840
  + 'wallet for a team agent); the connected project must belong to that same workspace. Every call without '
934
841
  + 'confirm: true only returns what will happen and the amount (for a move to a larger plan, the prorated '
935
842
  + 'amount Wiro works out, or the most it can charge when that is worked out only at the change). Show it to '
@@ -938,34 +845,36 @@ export function registerManageAgentBilling(server, client) {
938
845
  + 'between, nothing is charged and a new quote comes back. Never repeat a confirmed charge that failed or '
939
846
  + 'timed out without checking get_my_agent first. '
940
847
  + 'subscribe starts a plan for an agent without one; renew undoes a cancellation or renews an expired '
941
- + 'wallet plan; change_plan moves to another plan: a larger plan starts now and charges the prorated '
848
+ + 'plan; change_plan moves to another plan: a larger plan starts now and charges the prorated '
942
849
  + 'difference for the rest of the period, a smaller plan starts with the next renewal and charges or refunds '
943
- + 'nothing, and asking for the plan the agent is on undoes a move set for the next renewal; buy_credits adds '
944
- + 'a credit pack, on any plan; cancel stops renewals with no refund. Plans renew every 30 days until '
945
- + 'cancelled. Renewals, plan changes and packs leave a running agent running. An agent whose plan is billed '
946
- + 'by card moves to a larger plan and is topped up in the Wiro dashboard, and a personal card plan is '
947
- + 'cancelled there; the tool returns the link and charges nothing. A personal card plan can move to a smaller '
948
- + 'plan here: the card pays the smaller plan from the next renewal; a team\'s card plan changes plans in the '
949
- + 'dashboard. A card plan that is moving to wallet billing '
950
- + 'pays change_plan and buy_credits from the wallet, and cancel works once the wallet bills it. A card plan '
951
- + 'whose last payment did not go through has not ended and takes no new plan: the payment is fixed from '
952
- + 'Billing in the dashboard, in the personal workspace of the person whose card pays for the plan, and the '
953
- + 'plan then renews by itself. On a team '
850
+ + 'nothing, and asking for the plan the agent is on undoes a move set for the next renewal; cancel stops '
851
+ + 'renewals with no refund. Extra credit packs are retired: buy_credits only says so and charges nothing, and '
852
+ + 'funds are added to the balance on wiro.ai. Plans renew every 30 days until '
853
+ + 'cancelled. Renewals and plan changes leave a running agent running. Agent plans are paid only from the '
854
+ + 'Wiro balance: no card payment is taken, and a quote refused because the balance is short says how much '
855
+ + 'to add on wiro.ai, with nothing charged. Every plan payment, the automatic renewal included, counts the '
856
+ + 'balance\'s deposits, store revenue and coupon credit that is not limited to certain models; coupon credit '
857
+ + 'limited to models pays no plan. A card plan from before plans were paid from the balance is paid by card '
858
+ + 'through its period, then moves to the balance and renews from it (one whose period ends within 7 days '
859
+ + 'after Wiro\'s email announcing the move renews once more by card first); its plan changes are paid from '
860
+ + 'the balance, cancel ends it with its period instead, and renew undoes that, or brings back a card plan '
861
+ + 'that ended, from the balance. A card plan whose last payment did not go through has not ended and takes no '
862
+ + 'new plan until it ends. On a team '
954
863
  + 'agent only a team admin, the organization\'s owner or the person who deployed the agent can pay for it or '
955
864
  + 'change its plan; other members are refused and nothing is charged.',
956
865
  inputSchema: strictInput({
957
866
  agent_guid: z.string().min(1).max(100)
958
867
  .describe('The deployed agent\'s guid, from list_my_agents or deploy_agent.'),
959
868
  action: z.enum(ACTIONS)
960
- .describe('subscribe, change_plan, cancel, renew or buy_credits.'),
869
+ .describe('subscribe, change_plan, cancel or renew. buy_credits is retired: it says so and charges nothing.'),
961
870
  plan: z.enum(AGENT_PLANS).optional()
962
871
  .describe('subscribe: the plan to pay for (default: the agent\'s current plan, else starter). change_plan: the plan to move to; leave it out to get the plans with their prices.'),
963
872
  pack: z.enum(['small', 'medium', 'large']).optional()
964
- .describe('buy_credits only: the credit pack to buy. Leave it out to get the packs with their credits and prices.'),
873
+ .describe('Retired with buy_credits: extra credit packs are no longer sold. Ignored.'),
965
874
  request_id: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).optional()
966
- .describe('buy_credits only: the id returned by the quote. Repeating a purchase with the same id never charges twice. Every new purchase needs a new quote; an id whose purchase already completed buys nothing.'),
875
+ .describe('Retired with buy_credits. Ignored.'),
967
876
  confirm_charge_usd: z.number().min(0).max(100_000).optional()
968
- .describe('With confirm: true, the amount the user approved, from the quote\'s nextAction (quote.chargeNowUsd, or quote.maxChargeUsd for a move to a larger plan). Required for every action that charges: subscribe, change_plan to a larger plan, buy_credits and renewing an expired plan. If a fresh quote no longer matches it, nothing is charged and the new quote is returned. For a move to a larger plan it is the most the user agreed to pay now.'),
877
+ .describe('With confirm: true, the amount the user approved, from the quote\'s nextAction (quote.chargeNowUsd, or quote.maxChargeUsd for a move to a larger plan). Required for every action that charges: subscribe, change_plan to a larger plan and renewing an expired plan. If a fresh quote no longer matches it, nothing is charged and the new quote is returned. For a move to a larger plan it is the most the user agreed to pay now.'),
969
878
  confirm: z.boolean().default(false)
970
879
  .describe('false returns only the quote. true performs the action. Set it only after the user approved it.'),
971
880
  }, 'The plan to pay for or move to is the argument plan: starter, pro or max.'),
@@ -976,7 +885,6 @@ export function registerManageAgentBilling(server, client) {
976
885
  quote: quoteSchema.optional(),
977
886
  priceChanged: z.boolean().optional(),
978
887
  result: resultSchema.optional(),
979
- requestId: z.string().optional(),
980
888
  dashboardUrl: z.string(),
981
889
  agent: agentSummarySchema,
982
890
  message: z.string(),
@@ -988,9 +896,8 @@ export function registerManageAgentBilling(server, client) {
988
896
  idempotentHint: false,
989
897
  openWorldHint: true,
990
898
  },
991
- }, async ({ agent_guid, action, plan: planInput, pack, request_id, confirm_charge_usd, confirm }, extra) => {
899
+ }, async ({ agent_guid, action, plan: planInput, confirm_charge_usd, confirm }, extra) => {
992
900
  const guid = agent_guid.trim();
993
- const requestId = action === 'buy_credits' ? request_id ?? newRequestId() : undefined;
994
901
  let sentAtMs = 0;
995
902
  let before;
996
903
  let plan;
@@ -1024,7 +931,6 @@ export function registerManageAgentBilling(server, client) {
1024
931
  ...(payload.quote ? { quote: payload.quote } : {}),
1025
932
  ...(payload.priceChanged ? { priceChanged: true } : {}),
1026
933
  ...(payload.result ? { result: payload.result } : {}),
1027
- ...(requestId && payload.withRequestId ? { requestId } : {}),
1028
934
  dashboardUrl,
1029
935
  agent: summary,
1030
936
  message: payload.message,
@@ -1036,22 +942,22 @@ export function registerManageAgentBilling(server, client) {
1036
942
  const quoteResponse = (quoted, lead, row, priceChanged) => {
1037
943
  const amount = approvalAmountOf(action, quoted.quote);
1038
944
  const additions = [
1039
- ...(requestId ? [`request_id "${requestId}"`] : []),
1040
945
  ...(amount !== null ? [`confirm_charge_usd ${amount}`] : []),
1041
946
  'confirm: true',
1042
947
  ];
948
+ // A charge the balance cannot pay now is refused on confirm, so the amount to add comes first.
949
+ const short = planBalanceShortfall(quoted.quote, row);
1043
950
  return respond({
1044
951
  outcome: 'quote',
1045
- message: `${lead}${quoted.message}\n\nNothing has been done yet. To go ahead, call manage_agent_billing again with the same arguments plus ${additions.join(', ')}.`,
952
+ message: `${lead}${quoted.message}${short ? ` ${short.text}` : ''}\n\nNothing has been done yet. To go ahead, call manage_agent_billing again with the same arguments plus ${additions.join(', ')}.`,
1046
953
  quote: quoted.quote,
1047
954
  ...(priceChanged ? { priceChanged: true } : {}),
1048
955
  nextAction: {
1049
956
  tool: 'manage_agent_billing',
1050
- arguments: confirmArguments(guid, action, quoted.quote, requestId),
1051
- reason: quoted.confirmReason ?? CHARGE_REASON,
957
+ arguments: confirmArguments(guid, action, quoted.quote),
958
+ reason: short?.reason ?? quoted.confirmReason ?? CHARGE_REASON,
1052
959
  },
1053
960
  agentRow: row,
1054
- withRequestId: true,
1055
961
  });
1056
962
  };
1057
963
  /**
@@ -1064,7 +970,7 @@ export function registerManageAgentBilling(server, client) {
1064
970
  const row = await readAgentDetail(client, guid, extra.signal);
1065
971
  const agent = toAgentDetail(row);
1066
972
  const raw = isPlainObject(row.subscription) ? row.subscription : null;
1067
- const again = await planFor(client, action, agent, raw, { plan: planInput, pack, requestId: requestId ?? '' }, extra.signal);
973
+ const again = await planFor(client, action, agent, raw, { plan: planInput }, extra.signal);
1068
974
  if (again.outcome !== 'quote' || !again.perform) {
1069
975
  return respond({
1070
976
  outcome: again.outcome,
@@ -1090,7 +996,7 @@ export function registerManageAgentBilling(server, client) {
1090
996
  before = agent;
1091
997
  plainMember = await isPlainTeamMember(client, row, extra.signal);
1092
998
  const raw = isPlainObject(row.subscription) ? row.subscription : null;
1093
- plan = await planFor(client, action, agent, raw, { plan: planInput, pack, requestId: requestId ?? '' }, extra.signal);
999
+ plan = await planFor(client, action, agent, raw, { plan: planInput }, extra.signal);
1094
1000
  if (plan.outcome !== 'quote' || !plan.perform) {
1095
1001
  return respond({ outcome: plan.outcome, heading: plan.heading, message: plan.message, nextAction: plan.nextAction, agentRow: row });
1096
1002
  }
@@ -1109,7 +1015,7 @@ export function registerManageAgentBilling(server, client) {
1109
1015
  if (!confirm || problem) {
1110
1016
  const amount = approvalAmountOf(action, plan.quote);
1111
1017
  const lead = problem === 'changed'
1112
- ? `${changedLead(action, plan.quote, amount, confirm_charge_usd, request_id)}\n\n`
1018
+ ? `${changedLead(action, plan.quote, amount, confirm_charge_usd)}\n\n`
1113
1019
  : problem === 'missing'
1114
1020
  ? 'Nothing was charged: confirm_charge_usd is missing. It is the amount the user approved, and it must be sent with confirm: true.\n\n'
1115
1021
  : '';
@@ -1126,49 +1032,6 @@ export function registerManageAgentBilling(server, client) {
1126
1032
  catch {
1127
1033
  // The action went through; the earlier snapshot still identifies the agent.
1128
1034
  }
1129
- // A request id that already completed a purchase is answered with
1130
- // success again, without a new charge or new credits. An older pack can
1131
- // end at the same moment, so the extra credits can grow by less than
1132
- // the pack, and the agent's packs decide.
1133
- const credits = plan.quote?.creditsAdded ?? 0;
1134
- const extraBefore = toNumber(row.extracredits);
1135
- const extraAfter = afterRead ? toNumber(after.extracredits) : null;
1136
- if (action === 'buy_credits' && performed.outcome === 'done' && credits > 0
1137
- && extraBefore !== null && extraAfter !== null && extraAfter - extraBefore < credits / 2) {
1138
- const fresh = await freshPackShows(client, guid, credits, sentAtMs, extra.signal);
1139
- if (fresh === false) {
1140
- return respond({
1141
- outcome: 'not_needed',
1142
- message: `Wiro answered request id "${requestId}" with a purchase that had already completed: the agent's extra credits did not grow and no new pack shows, so nothing new was bought or charged now. For another pack, get a new quote without request_id.`,
1143
- nextAction: billingCall(guid, 'buy_credits', { pack: plan.quote?.pack }),
1144
- agentRow: after,
1145
- });
1146
- }
1147
- // A repeat adds no credits. A new pack can add none only when an older
1148
- // pack ends at the same moment with at least as many left, so an answer
1149
- // with no growth says only what holds in both cases.
1150
- if (fresh && extraAfter <= extraBefore) {
1151
- return respond({
1152
- outcome: 'done',
1153
- heading: 'Pack in place',
1154
- message: `The ${plan.quote?.pack} pack is in place: ${formatCredits(credits)} credits for ${formatUsd(plan.quote?.chargeNowUsd)} from ${agent.workspace === 'team' ? 'the team wallet' : 'the personal wallet'}. This request id is charged only once. The agent's extra credits did not grow in this call, so if the id had already completed in an earlier call, nothing new was bought or charged now. ${planChangeAgentNote(agent.status, 'a credit pack')} For another pack, get a new quote without request_id.`,
1155
- quote: plan.quote,
1156
- result: { chargedUsd: null },
1157
- nextAction: performed.nextAction,
1158
- agentRow: after,
1159
- });
1160
- }
1161
- return respond({
1162
- outcome: 'done',
1163
- message: fresh
1164
- ? `${performed.message} The agent's extra credits grew by less than the pack, which happens when an older pack expires at the same moment. If this request id had already completed in an earlier call, it was charged only that once.`
1165
- : `Wiro accepted request id "${requestId}", but the agent's extra credits did not grow by the pack size and its packs could not be read, so it is not confirmed whether this bought a new pack or repeated a purchase that had already completed. Check get_my_agent and the wallet balance with get_account before buying again.`,
1166
- quote: plan.quote,
1167
- result: fresh ? performed.result : { chargedUsd: null },
1168
- nextAction: performed.nextAction,
1169
- agentRow: after,
1170
- });
1171
- }
1172
1035
  // Without the read-back, the row shows the agent as it was before the change.
1173
1036
  const stale = !afterRead && performed.outcome === 'done';
1174
1037
  // A change the agent read again does not show yet is said, so the result never claims more than it shows.
@@ -1176,7 +1039,7 @@ export function registerManageAgentBilling(server, client) {
1176
1039
  return respond({
1177
1040
  outcome: performed.outcome,
1178
1041
  message: stale
1179
- ? `${performed.message} The agent could not be read afterwards; get_my_agent shows its new status, plan and credits.`
1042
+ ? `${performed.message} The agent could not be read afterwards; get_my_agent shows its new status, plan and AI usage.`
1180
1043
  : notShown ? `${performed.message} ${notShown}` : performed.message,
1181
1044
  quote: plan.quote,
1182
1045
  result: performed.result,
@@ -1186,9 +1049,6 @@ export function registerManageAgentBilling(server, client) {
1186
1049
  });
1187
1050
  }
1188
1051
  catch (error) {
1189
- if (error instanceof ApiResultError && requestId && /still pending\. Retry with the same request id/i.test(error.message)) {
1190
- return errorResult(new Error(`${error.message}\n\n${retryPurchaseText(guid, plan?.quote, requestId)}`));
1191
- }
1192
1052
  const repriced = action === 'renew' && sentAtMs > 0 && error instanceof ApiResultError
1193
1053
  ? RENEWAL_REPRICED.exec(error.message.trim())
1194
1054
  : null;
@@ -1200,7 +1060,7 @@ export function registerManageAgentBilling(server, client) {
1200
1060
  if (chargeOf(quote) === null || !before) {
1201
1061
  return errorResult(new Error(`${text}\n\nThe request was sent, so it may have taken effect. Check get_my_agent before trying again.`));
1202
1062
  }
1203
- const observed = await observeOpenOutcome(client, action, before, quote, requestId, sentAtMs, extra.signal);
1063
+ const observed = await observeOpenOutcome(client, action, before, quote, extra.signal);
1204
1064
  if (observed.happened && observed.row) {
1205
1065
  return respond({
1206
1066
  outcome: 'done',
@@ -1211,13 +1071,10 @@ export function registerManageAgentBilling(server, client) {
1211
1071
  agentRow: observed.row,
1212
1072
  });
1213
1073
  }
1214
- const retry = action === 'buy_credits' && requestId
1215
- ? retryPurchaseText(guid, quote, requestId)
1216
- : 'Do not repeat the call until this is checked.';
1217
- return errorResult(new Error(`${text}\n\nThe request was sent and the answer does not show whether it went through. ${observed.text} ${retry}`));
1074
+ return errorResult(new Error(`${text}\n\nThe request was sent and the answer does not show whether it went through. ${observed.text} Do not repeat the call until this is checked.`));
1218
1075
  }
1219
1076
  if (error instanceof ApiResultError)
1220
- return errorResult(annotateKnownRefusal(error, sentAtMs > 0 ? requestId : undefined));
1077
+ return errorResult(annotateKnownRefusal(error, before?.workspace));
1221
1078
  return errorResult(error);
1222
1079
  }
1223
1080
  });