@wiro-ai/wiro-mcp 1.9.0 → 2.0.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 (223) hide show
  1. package/README.md +101 -41
  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 +125 -98
  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 +22 -15
  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 +41 -11
  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-controls.d.ts.map +1 -1
  63. package/dist/tools/get-controls.js +7 -4
  64. package/dist/tools/get-controls.js.map +1 -1
  65. package/dist/tools/get-my-agent.d.ts.map +1 -1
  66. package/dist/tools/get-my-agent.js +38 -5
  67. package/dist/tools/get-my-agent.js.map +1 -1
  68. package/dist/tools/get-task-price.d.ts.map +1 -1
  69. package/dist/tools/get-task-price.js +4 -4
  70. package/dist/tools/get-task-price.js.map +1 -1
  71. package/dist/tools/get-task.d.ts.map +1 -1
  72. package/dist/tools/get-task.js +4 -4
  73. package/dist/tools/get-task.js.map +1 -1
  74. package/dist/tools/index.d.ts +8 -3
  75. package/dist/tools/index.d.ts.map +1 -1
  76. package/dist/tools/index.js +17 -6
  77. package/dist/tools/index.js.map +1 -1
  78. package/dist/tools/kill-task.js +1 -1
  79. package/dist/tools/kill-task.js.map +1 -1
  80. package/dist/tools/list-agent-connectors.d.ts +4 -0
  81. package/dist/tools/list-agent-connectors.d.ts.map +1 -0
  82. package/dist/tools/list-agent-connectors.js +325 -0
  83. package/dist/tools/list-agent-connectors.js.map +1 -0
  84. package/dist/tools/list-agent-skills.d.ts.map +1 -1
  85. package/dist/tools/list-agent-skills.js +59 -40
  86. package/dist/tools/list-agent-skills.js.map +1 -1
  87. package/dist/tools/list-agent-templates.d.ts.map +1 -1
  88. package/dist/tools/list-agent-templates.js +7 -5
  89. package/dist/tools/list-agent-templates.js.map +1 -1
  90. package/dist/tools/list-my-agents.d.ts.map +1 -1
  91. package/dist/tools/list-my-agents.js +7 -3
  92. package/dist/tools/list-my-agents.js.map +1 -1
  93. package/dist/tools/list-projects.d.ts.map +1 -1
  94. package/dist/tools/list-projects.js +7 -4
  95. package/dist/tools/list-projects.js.map +1 -1
  96. package/dist/tools/list-studio-results.d.ts.map +1 -1
  97. package/dist/tools/list-studio-results.js +3 -2
  98. package/dist/tools/list-studio-results.js.map +1 -1
  99. package/dist/tools/list-tasks.d.ts.map +1 -1
  100. package/dist/tools/list-tasks.js +6 -3
  101. package/dist/tools/list-tasks.js.map +1 -1
  102. package/dist/tools/manage-agent-billing.d.ts.map +1 -1
  103. package/dist/tools/manage-agent-billing.js +216 -359
  104. package/dist/tools/manage-agent-billing.js.map +1 -1
  105. package/dist/tools/manage-agent-custom-skill.d.ts.map +1 -1
  106. package/dist/tools/manage-agent-custom-skill.js +77 -30
  107. package/dist/tools/manage-agent-custom-skill.js.map +1 -1
  108. package/dist/tools/manage-model-access.d.ts.map +1 -1
  109. package/dist/tools/manage-model-access.js +51 -20
  110. package/dist/tools/manage-model-access.js.map +1 -1
  111. package/dist/tools/manage-spend-limit.d.ts.map +1 -1
  112. package/dist/tools/manage-spend-limit.js +25 -19
  113. package/dist/tools/manage-spend-limit.js.map +1 -1
  114. package/dist/tools/run-model.d.ts.map +1 -1
  115. package/dist/tools/run-model.js +9 -8
  116. package/dist/tools/run-model.js.map +1 -1
  117. package/dist/tools/schemas.d.ts +11 -0
  118. package/dist/tools/schemas.d.ts.map +1 -1
  119. package/dist/tools/schemas.js +19 -1
  120. package/dist/tools/schemas.js.map +1 -1
  121. package/dist/tools/send-agent-message.d.ts.map +1 -1
  122. package/dist/tools/send-agent-message.js +53 -23
  123. package/dist/tools/send-agent-message.js.map +1 -1
  124. package/dist/tools/set-agent-connector-accounts.d.ts +4 -0
  125. package/dist/tools/set-agent-connector-accounts.d.ts.map +1 -0
  126. package/dist/tools/set-agent-connector-accounts.js +263 -0
  127. package/dist/tools/set-agent-connector-accounts.js.map +1 -0
  128. package/dist/tools/set-agent-connector-permissions.d.ts +4 -0
  129. package/dist/tools/set-agent-connector-permissions.d.ts.map +1 -0
  130. package/dist/tools/set-agent-connector-permissions.js +280 -0
  131. package/dist/tools/set-agent-connector-permissions.js.map +1 -0
  132. package/dist/tools/set-agent-credentials.d.ts.map +1 -1
  133. package/dist/tools/set-agent-credentials.js +52 -169
  134. package/dist/tools/set-agent-credentials.js.map +1 -1
  135. package/dist/tools/update-agent.d.ts.map +1 -1
  136. package/dist/tools/update-agent.js +39 -18
  137. package/dist/tools/update-agent.js.map +1 -1
  138. package/dist/tools/wait-for-task.d.ts.map +1 -1
  139. package/dist/tools/wait-for-task.js +4 -4
  140. package/dist/tools/wait-for-task.js.map +1 -1
  141. package/dist/tools/wait-for-workflow-run.d.ts.map +1 -1
  142. package/dist/tools/wait-for-workflow-run.js +6 -3
  143. package/dist/tools/wait-for-workflow-run.js.map +1 -1
  144. package/dist/utils/agent-approvals.d.ts +328 -0
  145. package/dist/utils/agent-approvals.d.ts.map +1 -0
  146. package/dist/utils/agent-approvals.js +620 -0
  147. package/dist/utils/agent-approvals.js.map +1 -0
  148. package/dist/utils/agent-catalog.d.ts +15 -25
  149. package/dist/utils/agent-catalog.d.ts.map +1 -1
  150. package/dist/utils/agent-catalog.js +27 -36
  151. package/dist/utils/agent-catalog.js.map +1 -1
  152. package/dist/utils/agent-config.d.ts +87 -292
  153. package/dist/utils/agent-config.d.ts.map +1 -1
  154. package/dist/utils/agent-config.js +150 -787
  155. package/dist/utils/agent-config.js.map +1 -1
  156. package/dist/utils/agent-connectors.d.ts +197 -0
  157. package/dist/utils/agent-connectors.d.ts.map +1 -0
  158. package/dist/utils/agent-connectors.js +415 -0
  159. package/dist/utils/agent-connectors.js.map +1 -0
  160. package/dist/utils/agent-message.d.ts +112 -4
  161. package/dist/utils/agent-message.d.ts.map +1 -1
  162. package/dist/utils/agent-message.js +105 -15
  163. package/dist/utils/agent-message.js.map +1 -1
  164. package/dist/utils/agent-setup.d.ts +19 -14
  165. package/dist/utils/agent-setup.d.ts.map +1 -1
  166. package/dist/utils/agent-setup.js +171 -106
  167. package/dist/utils/agent-setup.js.map +1 -1
  168. package/dist/utils/agent-targets.d.ts +7 -1
  169. package/dist/utils/agent-targets.d.ts.map +1 -1
  170. package/dist/utils/agent-targets.js +78 -23
  171. package/dist/utils/agent-targets.js.map +1 -1
  172. package/dist/utils/agent-turns.d.ts +260 -7
  173. package/dist/utils/agent-turns.d.ts.map +1 -1
  174. package/dist/utils/agent-turns.js +265 -74
  175. package/dist/utils/agent-turns.js.map +1 -1
  176. package/dist/utils/api.d.ts +26 -0
  177. package/dist/utils/api.d.ts.map +1 -1
  178. package/dist/utils/api.js +29 -0
  179. package/dist/utils/api.js.map +1 -1
  180. package/dist/utils/connector-permissions.d.ts +184 -0
  181. package/dist/utils/connector-permissions.d.ts.map +1 -0
  182. package/dist/utils/connector-permissions.js +439 -0
  183. package/dist/utils/connector-permissions.js.map +1 -0
  184. package/dist/utils/controls.d.ts +71 -11
  185. package/dist/utils/controls.d.ts.map +1 -1
  186. package/dist/utils/controls.js +124 -30
  187. package/dist/utils/controls.js.map +1 -1
  188. package/dist/utils/format.d.ts +10 -0
  189. package/dist/utils/format.d.ts.map +1 -1
  190. package/dist/utils/format.js +42 -3
  191. package/dist/utils/format.js.map +1 -1
  192. package/dist/utils/quoted-text.d.ts +2 -0
  193. package/dist/utils/quoted-text.d.ts.map +1 -1
  194. package/dist/utils/quoted-text.js +5 -0
  195. package/dist/utils/quoted-text.js.map +1 -1
  196. package/dist/utils/structured.d.ts +3 -0
  197. package/dist/utils/structured.d.ts.map +1 -1
  198. package/dist/utils/structured.js +7 -2
  199. package/dist/utils/structured.js.map +1 -1
  200. package/dist/utils/studio-runs.d.ts.map +1 -1
  201. package/dist/utils/studio-runs.js +6 -4
  202. package/dist/utils/studio-runs.js.map +1 -1
  203. package/dist/utils/user-agent.d.ts +271 -100
  204. package/dist/utils/user-agent.d.ts.map +1 -1
  205. package/dist/utils/user-agent.js +434 -159
  206. package/dist/utils/user-agent.js.map +1 -1
  207. package/dist/utils/wiro-project.d.ts +25 -0
  208. package/dist/utils/wiro-project.d.ts.map +1 -1
  209. package/dist/utils/wiro-project.js +76 -2
  210. package/dist/utils/wiro-project.js.map +1 -1
  211. package/dist/utils/workspace.d.ts +3 -1
  212. package/dist/utils/workspace.d.ts.map +1 -1
  213. package/dist/utils/workspace.js +2 -1
  214. package/dist/utils/workspace.js.map +1 -1
  215. package/package.json +1 -1
  216. package/dist/tools/connect-agent-oauth.d.ts +0 -4
  217. package/dist/tools/connect-agent-oauth.d.ts.map +0 -1
  218. package/dist/tools/connect-agent-oauth.js +0 -778
  219. package/dist/tools/connect-agent-oauth.js.map +0 -1
  220. package/dist/tools/disconnect-agent-oauth.d.ts +0 -4
  221. package/dist/tools/disconnect-agent-oauth.d.ts.map +0 -1
  222. package/dist/tools/disconnect-agent-oauth.js +0 -138
  223. package/dist/tools/disconnect-agent-oauth.js.map +0 -1
@@ -65,7 +65,7 @@ export function describeAgentStatus(status) {
65
65
  // can read it and message it, so their hints say who can act instead of naming
66
66
  // a call they cannot make.
67
67
  const TEAM_AGENT_MANAGERS = 'a team admin or the person who deployed it';
68
- export const MEMBER_SETUP_HELP = `On this team agent, ${TEAM_AGENT_MANAGERS} saves credentials, connects accounts such `
68
+ export const MEMBER_SETUP_HELP = `On this team agent, ${TEAM_AGENT_MANAGERS} saves credentials, connects connectors such `
69
69
  + 'as Instagram or Google Ads, and pays for the plan.';
70
70
  const MEMBER_STATUS_HINT = {
71
71
  stopped: `It is not running. On this team agent, ${TEAM_AGENT_MANAGERS} can start it.`,
@@ -82,12 +82,12 @@ export function isTransitionalStatus(status) {
82
82
  return status === 1 || status === 2 || status === 3;
83
83
  }
84
84
  // ---------------------------------------------------------------------------
85
- // Prices, plans and credits
85
+ // Prices, plans and AI usage
86
86
  // ---------------------------------------------------------------------------
87
87
  /**
88
- * The plans an agent can have, smallest first. Every plan includes every skill,
89
- * and each has a fixed monthly price and monthly credits, the same for every
90
- * template and custom build. The numbers come from Wiro, never from here.
88
+ * The plans an agent can have, smallest first. Every plan includes every skill, and each has a fixed monthly
89
+ * price that it also includes as AI usage each month, the same for every template and custom build. After the
90
+ * included usage, the agent uses the Wiro balance of its workspace. The numbers come from Wiro, never from here.
91
91
  */
92
92
  export const AGENT_PLANS = ['starter', 'pro', 'max'];
93
93
  const PLAN_NAMES = { starter: 'Starter', pro: 'Pro', max: 'Max' };
@@ -104,60 +104,75 @@ export function comparePlans(a, b) {
104
104
  return AGENT_PLANS.indexOf(a) - AGENT_PLANS.indexOf(b);
105
105
  }
106
106
  export const planPriceSchema = z.object({
107
- priceUsd: z.number(),
108
- monthlyCredits: z.number(),
107
+ priceUsd: z.number()
108
+ .describe('What the plan costs every 30 days.'),
109
+ includedUsageUsd: z.number()
110
+ .describe('The AI usage the plan includes each month, in USD.'),
109
111
  });
110
112
  export const planPricingSchema = z.object({
111
113
  starter: planPriceSchema.optional(),
112
114
  pro: planPriceSchema.optional(),
113
115
  max: planPriceSchema.optional(),
114
116
  });
117
+ /** One plan's price; the AI usage it includes is its own price when Wiro does not name it. */
115
118
  function toPlanPrice(value) {
116
119
  if (!isPlainObject(value))
117
120
  return null;
118
121
  const priceUsd = toNumber(value.priceUsd);
119
- const credits = toNumber(value.credits);
120
- if (priceUsd === null || credits === null)
122
+ if (priceUsd === null)
121
123
  return null;
122
- return { priceUsd, monthlyCredits: credits };
124
+ return { priceUsd, includedUsageUsd: toNumber(value.includedUsageUsd) ?? priceUsd };
123
125
  }
124
- /** Each plan's price and monthly credits as Wiro lists them (its tiers), or null when it lists none. */
125
- export function toPlanPricing(value) {
126
- if (!isPlainObject(value))
126
+ /**
127
+ * Each plan's price and the AI usage it includes, as an answer lists them, or null when it lists none. source
128
+ * holds the plans as plans ([{ key, priceUsd, includedUsageUsd }]) or, in their older form, as tiers
129
+ * ({ starter: { priceUsd }, ... }).
130
+ */
131
+ export function toPlanPricing(source) {
132
+ if (!isPlainObject(source))
127
133
  return null;
128
134
  const pricing = {};
129
- for (const plan of AGENT_PLANS) {
130
- const price = toPlanPrice(value[plan]);
131
- if (price)
135
+ for (const entry of Array.isArray(source.plans) ? source.plans.filter(isPlainObject) : []) {
136
+ const plan = asPlan(entry.key);
137
+ const price = toPlanPrice(entry);
138
+ if (plan && price && !pricing[plan])
132
139
  pricing[plan] = price;
133
140
  }
141
+ if (Object.keys(pricing).length === 0 && isPlainObject(source.tiers)) {
142
+ const tiers = source.tiers;
143
+ for (const plan of AGENT_PLANS) {
144
+ const price = toPlanPrice(tiers[plan]);
145
+ if (price)
146
+ pricing[plan] = price;
147
+ }
148
+ }
134
149
  return Object.keys(pricing).length > 0 ? pricing : null;
135
150
  }
136
151
  /** A plan's monthly price in a list: whole dollars without cents, such as $5, and other amounts with them. */
137
152
  export function formatPlanUsd(value) {
138
153
  return Number.isInteger(value) ? `$${value}` : `$${value.toFixed(2)}`;
139
154
  }
140
- /** One plan with its price and credits: "Pro $30 (3,000 credits)". */
155
+ /** One plan with its price and the AI usage it includes: "Pro $30 a month, includes $30 of AI usage". */
141
156
  export function planPriceText(plan, price) {
142
- return `${PLAN_NAMES[plan]} ${formatPlanUsd(price.priceUsd)} (${formatCredits(price.monthlyCredits)} credits)`;
157
+ return `${PLAN_NAMES[plan]} ${formatPlanUsd(price.priceUsd)} a month, includes ${formatPlanUsd(price.includedUsageUsd)} of AI usage`;
143
158
  }
144
159
  /**
145
- * The plans Wiro lists, smallest first, as one line: "Starter $5 (500 credits), Pro $30 (3,000 credits),
146
- * Max $100 (10,000 credits) per month". except leaves one plan out, such as the one a quote is for.
160
+ * The plans Wiro lists, smallest first, as one line: "Starter $5 a month, includes $5 of AI usage; Pro $30 a
161
+ * month, includes $30 of AI usage; ...". except leaves one plan out, such as the one a quote is for.
147
162
  */
148
163
  export function planLineText(pricing, except) {
149
- const listed = AGENT_PLANS.flatMap(plan => {
164
+ return AGENT_PLANS.flatMap(plan => {
150
165
  const price = pricing[plan];
151
166
  return price && plan !== except ? [planPriceText(plan, price)] : [];
152
- });
153
- return listed.length > 0 ? `${listed.join(', ')} per month` : '';
167
+ }).join('; ');
154
168
  }
155
169
  export function formatUsd(value) {
156
170
  if (value === null || value === undefined || !Number.isFinite(value))
157
171
  return 'unknown';
158
172
  return `$${value.toFixed(2)}`;
159
173
  }
160
- export function formatCredits(value) {
174
+ /** A whole count, such as tokens or turns: 50,147. */
175
+ export function formatCount(value) {
161
176
  if (value === null || value === undefined || !Number.isFinite(value))
162
177
  return 'unknown';
163
178
  return Math.round(value).toLocaleString('en-US');
@@ -165,6 +180,49 @@ export function formatCredits(value) {
165
180
  export function roundUsd(value) {
166
181
  return Math.round(value * 100) / 100;
167
182
  }
183
+ /** Without included AI usage left, an agent's new turn needs this much in the Wiro balance. */
184
+ export const MIN_RUN_BALANCE_USD = 0.5;
185
+ /** What pays for an agent's chat and scheduled tasks, for a sentence such as "every run uses ...". */
186
+ export const AGENT_AI_USAGE = 'the agent\'s AI usage (its plan first, then the workspace balance)';
187
+ /** The Wiro dashboard page where funds are added to a balance. No tool adds funds. */
188
+ export const ADD_FUNDS_URL = 'https://wiro.ai/panel/wallet/deposit/credit-card';
189
+ /**
190
+ * What pays an agent plan: one rule for every plan payment, a new plan, a renewal, a move to a larger plan and the
191
+ * automatic renewal alike. The balance's deposits, its store revenue and its coupon credit count, except coupon credit
192
+ * limited to certain models, which pays no plan.
193
+ */
194
+ export const PLAN_FUNDS_TEXT = 'A plan payment, the automatic renewal included, counts the balance\'s deposits, store '
195
+ + 'revenue and coupon credit that is not limited to certain models; coupon credit limited to models pays no plan.';
196
+ /** Where funds are added, as a sentence. A team agent's balance is its team's wallet. */
197
+ export function addFundsText(workspace) {
198
+ return `Funds are added at ${ADD_FUNDS_URL}${workspace === 'team' ? ' (select the agent\'s team in the dashboard first)' : ''}.`;
199
+ }
200
+ /**
201
+ * What Wiro says is missing from the balance for a plan payment it refused: its neededusd, the amount to add in USD
202
+ * (rounded up to the cent, at least the deposit minimum), or the older "Insufficient wallet balance" answer. A
203
+ * refusal for a paused agent carries agentusage instead, and any other refusal, a 97 that refuses a team member
204
+ * included, is null.
205
+ */
206
+ export function balanceShortfall(error) {
207
+ if (!(error instanceof ApiResultError))
208
+ return null;
209
+ const needed = toNumber(error.body.neededusd);
210
+ if (needed !== null)
211
+ return { neededUsd: needed > 0 ? needed : null };
212
+ return /insufficient wallet balance/i.test(error.message) ? { neededUsd: null } : null;
213
+ }
214
+ /** The agent's AI usage a refusal carries (agentusage), when Wiro refused it because the agent is paused. */
215
+ export function pausedUsage(body) {
216
+ return isPlainObject(body.agentusage) ? toAgentUsage({ usage: body.agentusage }) : null;
217
+ }
218
+ /**
219
+ * The words after a plan payment refused for a short balance: what was not done, how much to add, and where.
220
+ * teamHint says which team to select in the dashboard, when one is to be selected.
221
+ */
222
+ export function shortBalanceNote(neededUsd, teamHint, nothingDone = 'Nothing was charged.') {
223
+ return `${nothingDone} ${PLAN_FUNDS_TEXT} ${neededUsd !== null ? `Add at least ${formatUsd(neededUsd)} to the Wiro balance on wiro.ai. ` : ''}`
224
+ + `Funds are added at ${ADD_FUNDS_URL}${teamHint ? ` (${teamHint})` : ''}.`;
225
+ }
168
226
  // A confirmed charge goes ahead only when a fresh quote still matches the
169
227
  // amount the user approved; anything else is quoted again.
170
228
  export const AMOUNT_TOLERANCE_USD = 0.005;
@@ -178,15 +236,36 @@ export const subscriptionSchema = z.object({
178
236
  amountUsd: z.number().nullable()
179
237
  .describe('What the plan costs every 30 days. For a plan that has ended, what a new period costs: the price of its plan today.'),
180
238
  periodEndsAt: z.string().optional(),
239
+ renewsOrEndsAt: z.string().optional()
240
+ .describe('For an active plan, when it renews, or ends when atPeriodEnd is ends, as Wiro shows it: periodEndsAt, or the time of the answer once that has passed and the renewal is due (while the balance cannot pay a wallet plan\'s renewal, Wiro tries again for up to a day), never a moment gone by. Absent when Wiro does not send it.'),
181
241
  daysRemaining: z.number().nullable(),
182
242
  cancelAtPeriodEnd: z.boolean(),
183
243
  atPeriodEnd: z.enum(['renews', 'ends', 'unknown']).optional()
184
- .describe('For an active plan, what happens at periodEndsAt: it renews, it ends, or unknown for a card plan whose renewal is managed in the Wiro dashboard.'),
244
+ .describe('For an active plan, what happens at periodEndsAt: it renews, it ends, or unknown for a card plan from before agent plans were paid from the Wiro balance only.'),
185
245
  });
246
+ /** A moment Wiro answers as an ISO date, such as a plan's renewaldate, written as unixToIso writes one. */
247
+ function isoMoment(value) {
248
+ const ms = typeof value === 'string' ? Date.parse(value) : Number.NaN;
249
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : undefined;
250
+ }
251
+ /**
252
+ * When an active plan renews, or ends when it is set to end, for a sentence: the moment Wiro shows
253
+ * (renewsOrEndsAt), which is never gone by, else, in an answer without it, the period end. The period end itself
254
+ * can be gone by while the plan is active: a wallet plan whose renewal the balance cannot pay stays active while
255
+ * Wiro tries again for up to a day after it.
256
+ */
257
+ export function renewalMoment(plan) {
258
+ return plan?.renewsOrEndsAt ?? plan?.periodEndsAt;
259
+ }
260
+ /**
261
+ * A renewal Wiro says is due (usage.renewalDue), in its own words: the period has ended, so the moment it shows is
262
+ * the time of the answer, which is not said as a renewal date.
263
+ */
264
+ const RENEWAL_DUE_NOW = 'renewal due now (once the balance can pay it, it renews within 15 minutes)';
186
265
  /**
187
266
  * Whether a plan ends with its current period: true when it ends, false when
188
267
  * it renews, null when that is not known. A wallet plan says so itself, and a
189
- * card plan moving to wallet billing renews from the wallet, even though its
268
+ * card plan moving to the wallet renews from the Wiro balance, even though its
190
269
  * card subscription is set to end with the period. Any other card plan is
191
270
  * known only when the row carries its card state (cardEnds).
192
271
  */
@@ -206,25 +285,32 @@ export function toSubscription(value, cardEnds) {
206
285
  const periodEndsAt = unixToIso(value.currentperiodend);
207
286
  const status = asString(value.status) ?? 'expired';
208
287
  const ends = planEndsWithPeriod(value, cardEnds);
288
+ // Wiro's renewal date of an active plan: its renewal, or its end, never a moment gone by.
289
+ const renewsOrEndsAt = status === 'active' ? isoMoment(value.renewaldate) : undefined;
209
290
  return {
210
291
  status,
211
292
  billing: provider === 'prepaid' ? 'wallet' : 'card',
212
293
  switchingToWallet: provider !== 'prepaid' && value.nextprovider === 'prepaid',
213
294
  amountUsd: toNumber(value.amount),
214
295
  ...(periodEndsAt ? { periodEndsAt } : {}),
296
+ ...(renewsOrEndsAt ? { renewsOrEndsAt } : {}),
215
297
  daysRemaining: toNumber(value.daysremaining),
216
298
  // True only when the plan is known to end; atPeriodEnd also tells a plan that renews from an unknown one.
217
299
  cancelAtPeriodEnd: ends === true,
218
300
  ...(status === 'active' ? { atPeriodEnd: ends === true ? 'ends' : ends === false ? 'renews' : 'unknown' } : {}),
219
301
  };
220
302
  }
221
- /** How a new charge for this plan is paid right now. */
222
- export function chargeRoute(subscription) {
223
- if (!isPlainObject(subscription))
224
- return null;
225
- if (subscription.nextprovider === 'prepaid' || subscription.provider === 'prepaid')
226
- return 'wallet';
227
- return 'card';
303
+ /**
304
+ * A card plan from before agent plans were paid from the Wiro balance moves to the balance at its period end, except
305
+ * one whose period ends within 7 days after Wiro's email announcing the move: that one renews once more by card
306
+ * first. A plan already set to move (switchingToWallet) moves at this period end; for any other card plan the answer
307
+ * cannot tell, so what is said of it names the exception.
308
+ */
309
+ const CARD_PLAN_ONCE_MORE = 'If this period ends within 7 days after Wiro\'s email announcing the move, it '
310
+ + 'renews once more by card first.';
311
+ /** The exception a card plan's text adds, with a leading space; none for a plan already set to move. */
312
+ export function cardPlanOnceMoreNote(plan) {
313
+ return plan?.switchingToWallet ? '' : ` ${CARD_PLAN_ONCE_MORE}`;
228
314
  }
229
315
  // The plan statuses Wiro counts as ended. Every other status is a plan that has not ended, a card plan
230
316
  // whose renewal payment did not go through included, and Wiro starts no second plan beside it.
@@ -239,15 +325,15 @@ function isLivePlanStatus(status) {
239
325
  export function isUnsettledPlan(plan) {
240
326
  return Boolean(plan) && plan?.status !== 'active' && isLivePlanStatus(plan?.status);
241
327
  }
242
- // Billing in the dashboard's personal workspace. Its Open Billing Portal button is where a card plan whose last
243
- // payment did not go through is paid or cancelled: the agent's page offers the billing portal only for an active
244
- // plan, and a team workspace has no billing portal, since a team's card plans are billed to the member who pays.
245
- const BILLING_PAGE_URL = 'https://wiro.ai/panel/billing';
328
+ /** The Wiro balance that pays for an agent's plan: the personal wallet, or the team wallet for a team agent. */
329
+ export function planBalanceName(workspace) {
330
+ return workspace === 'team' ? 'the team\'s Wiro balance' : 'your Wiro balance';
331
+ }
246
332
  /**
247
- * What to do about a plan that has not ended and is not active. Wiro starts no new plan beside it, and renews,
248
- * changes, cancels and adds packs only to an active plan, so the dashboard settles it: a card plan whose last
249
- * payment did not go through renews by itself once its open invoice is paid in the billing portal, which Billing
250
- * opens in the personal workspace of whoever pays for the plan. lead says what the call could not do, after the
333
+ * What to do about a plan that has not ended and is not active, such as a card plan from before agent plans were
334
+ * paid from the Wiro balance only, whose last payment did not go through. Wiro starts no new plan beside it, and
335
+ * renews, changes and cancels only an active plan, and no card payment is taken here, so nothing here settles it:
336
+ * once a card plan has ended, a new plan is paid from the balance. lead says what the call could not do, after the
251
337
  * plan's state.
252
338
  */
253
339
  export function unsettledPlanText(plan, agent, lead = '') {
@@ -255,41 +341,228 @@ export function unsettledPlanText(plan, agent, lead = '') {
255
341
  const state = failed
256
342
  ? `The last payment for this card plan did not go through (${plan.status}), so the plan has not ended.`
257
343
  : `This ${plan.billing === 'card' ? 'card ' : ''}plan is ${plan.status}, so it has not ended.`;
258
- const fix = failed
259
- ? 'To fix the payment, open Billing in the personal workspace of the Wiro dashboard and choose Open Billing Portal. '
260
- + 'Pay the open invoice there, with another card if needed, and the plan renews by itself. The plan can also be cancelled there. '
261
- + (agent.workspace === 'team' ? 'On a team agent, the member whose card pays for the plan does this, from their own personal workspace. ' : '')
262
- + BILLING_PAGE_URL
344
+ const fix = plan.billing === 'card'
345
+ ? 'Agent plans are paid from the Wiro balance now, and no card payment is taken here: once this card plan has ended, '
346
+ + `a new plan is paid from ${planBalanceName(agent.workspace)}. The agent's page: ${agentDashboardUrl(agent.guid)}`
263
347
  : `It is managed in the Wiro dashboard: ${agentDashboardUrl(agent.guid)}`;
264
348
  return [state, lead, fix].filter(Boolean).join(' ');
265
349
  }
266
- export const creditsSchema = z.object({
267
- monthly: z.number()
268
- .describe('The monthly credits this period grants. A plan change inside a period moves it for the time left, so it can differ from renewal.'),
269
- renewal: z.number().optional()
270
- .describe('The monthly credits each renewal grants.'),
271
- extra: z.number(),
272
- used: z.number(),
273
- remaining: z.number(),
274
- period: z.string().optional(),
350
+ // ---------------------------------------------------------------------------
351
+ // AI usage and spending
352
+ // ---------------------------------------------------------------------------
353
+ /** Wiro keeps some amounts in hundredths of a dollar; this is the same amount in USD. */
354
+ export function centsToUsd(value) {
355
+ return Math.round(value * 10_000) / 1_000_000;
356
+ }
357
+ export const agentUsageSchema = z.object({
358
+ period: z.string().optional()
359
+ .describe('A month tag (YYYY-MM, UTC), such as 2026-11: the month the current plan period started in, when its renewal ran. Not the period itself, which runs from one renewal to the next (resetsAt), so the amounts are not a calendar month\'s.'),
360
+ resetsAt: z.string().optional()
361
+ .describe('When the included AI usage starts again: the plan\'s next renewal.'),
362
+ renewalDue: z.boolean().optional()
363
+ .describe('true while the plan\'s renewal is due: a wallet plan whose period has ended and that Wiro has not renewed yet, so resetsAt reads the time of the answer. Once the balance can pay the renewal, it renews within 15 minutes; Wiro tries again for up to a day after the period end, and after that day the plan ends. Absent when Wiro does not send it.'),
364
+ includedUsd: z.number()
365
+ .describe('The AI usage the plan includes this period, in USD. A plan change inside a period moves it for the time left, so it can differ from renewalUsd.'),
366
+ usedUsd: z.number()
367
+ .describe('The included AI usage used this period.'),
368
+ leftUsd: z.number()
369
+ .describe('The included AI usage left this period.'),
370
+ renewalUsd: z.number().optional()
371
+ .describe('The AI usage each renewal includes.'),
372
+ fromBalanceUsd: z.number().optional()
373
+ .describe('The AI usage paid from the workspace balance this period, after the included usage ran out.'),
374
+ balanceUsd: z.number().optional()
375
+ .describe('What the agent\'s AI usage can draw on now in the Wiro balance that pays after the included usage (the '
376
+ + 'personal wallet, or the team wallet for a team agent): its deposits, store revenue and coupon credit that is '
377
+ + 'not limited to certain models. A coupon limited to certain models never pays an agent\'s AI usage, so this '
378
+ + 'can read less than get_account shows.'),
379
+ wallet: z.enum(['personal', 'team']).optional()
380
+ .describe('Which Wiro balance pays after the included usage.'),
381
+ planBalanceUsd: z.number().optional()
382
+ .describe('What the wallet that pays for the agent can pay a plan with: deposits, store revenue and coupons that can pay a plan; a coupon limited to models does not count. Set where the agent\'s full detail is read, such as get_my_agent; list_my_agents leaves it out.'),
383
+ minBalanceUsd: z.number().optional()
384
+ .describe('Without included usage left, a new turn needs balanceUsd to be at least this much.'),
385
+ paused: z.boolean()
386
+ .describe('Whether the agent takes no new turns now: it has no active plan, its included usage is used up and the balance is under minBalanceUsd, or a spend limit is reached. A turn that is running finishes.'),
387
+ pausedReason: z.enum(['plan', 'balance', 'spendlimit']).optional()
388
+ .describe('Why it is paused: plan (it has no active plan; an agent runs only with one, whatever the balance holds), balance (the included usage is used up and the balance is short) or spendlimit (a spend limit is reached).'),
389
+ extraUsd: z.number().optional()
390
+ .describe('Only in an answer from an older Wiro release: usage bought earlier for this agent that is left.'),
391
+ legacy: z.boolean().optional()
392
+ .describe('true when Wiro answered without these amounts, so they were worked out from its older fields.'),
275
393
  });
276
- export function toCredits(row) {
277
- const period = asString(row.creditperiod);
394
+ export const agentSpendSchema = z.object({
395
+ month: z.string().optional()
396
+ .describe('The calendar month (UTC), such as 2026-11.'),
397
+ totalUsd: z.number()
398
+ .describe('What the agent cost this month: its plan, its AI usage paid from the balance and the model runs it started.'),
399
+ planUsd: z.number(),
400
+ aiUsageBalanceUsd: z.number()
401
+ .describe('AI usage paid from the balance.'),
402
+ aiUsagePlanUsd: z.number()
403
+ .describe('AI usage the plan included, already paid with the plan and not in totalUsd.'),
404
+ modelRunsUsd: z.number(),
405
+ fundsAddedUsd: z.number()
406
+ .describe('Funds added to the balance from this agent\'s page. Not spending, so not in totalUsd.'),
407
+ });
408
+ /**
409
+ * The agent's AI usage in USD from its row: Wiro's usage object, or, in an answer from an older Wiro release, its
410
+ * credit fields, which count hundredths of a dollar.
411
+ */
412
+ export function toAgentUsage(row) {
413
+ const usage = isPlainObject(row.usage) ? row.usage : null;
414
+ const included = usage ? toNumber(usage.includedusd) : null;
415
+ if (usage && included !== null) {
416
+ const used = toNumber(usage.usedusd) ?? 0;
417
+ const left = toNumber(usage.leftusd) ?? Math.max(0, roundUsd(included - used));
418
+ const period = asString(usage.period);
419
+ const resetsAt = unixToIso(usage.resetsat);
420
+ const renewal = toNumber(usage.renewalusd);
421
+ const fromBalance = toNumber(usage.frombalanceusd);
422
+ const balance = toNumber(usage.balanceusd);
423
+ const wallet = usage.wallet === 'personal' || usage.wallet === 'team' ? usage.wallet : undefined;
424
+ // Only the agent's detail carries it, and null when Wiro could not read it.
425
+ const planBalance = typeof usage.planbalanceusd === 'number' && Number.isFinite(usage.planbalanceusd)
426
+ ? usage.planbalanceusd
427
+ : null;
428
+ const minBalance = toNumber(usage.minbalanceusd);
429
+ const reason = usage.pausedreason === 'plan' || usage.pausedreason === 'balance' || usage.pausedreason === 'spendlimit'
430
+ ? usage.pausedreason
431
+ : undefined;
432
+ return {
433
+ ...(period ? { period } : {}),
434
+ ...(resetsAt ? { resetsAt } : {}),
435
+ ...(typeof usage.renewaldue === 'boolean' ? { renewalDue: usage.renewaldue } : {}),
436
+ includedUsd: included,
437
+ usedUsd: used,
438
+ leftUsd: left,
439
+ ...(renewal !== null ? { renewalUsd: renewal } : {}),
440
+ ...(fromBalance !== null ? { fromBalanceUsd: fromBalance } : {}),
441
+ ...(balance !== null ? { balanceUsd: balance } : {}),
442
+ ...(wallet ? { wallet } : {}),
443
+ ...(planBalance !== null ? { planBalanceUsd: planBalance } : {}),
444
+ ...(minBalance !== null ? { minBalanceUsd: minBalance } : {}),
445
+ paused: usage.paused === true || reason !== undefined,
446
+ ...(reason ? { pausedReason: reason } : {}),
447
+ };
448
+ }
449
+ // An older answer: the plan's part comes first, and what is left beyond it was bought apart from the plan.
450
+ const monthly = Math.max(0, toNumber(row.monthlycredits) ?? 0);
451
+ const used = Math.max(0, toNumber(row.usedcredits) ?? 0);
452
+ const remaining = toNumber(row.remainingcredits);
278
453
  const renewal = toNumber(row.renewalcredits);
454
+ const period = asString(row.creditperiod);
455
+ const includedLeft = Math.max(0, monthly - used);
456
+ const extraLeft = remaining !== null ? Math.max(0, remaining - includedLeft) : Math.max(0, toNumber(row.extracredits) ?? 0);
457
+ const active = isPlainObject(row.subscription) && row.subscription.status === 'active';
279
458
  return {
280
- monthly: toNumber(row.monthlycredits) ?? 0,
281
- ...(renewal !== null ? { renewal } : {}),
282
- extra: toNumber(row.extracredits) ?? 0,
283
- used: toNumber(row.usedcredits) ?? 0,
284
- remaining: toNumber(row.remainingcredits) ?? 0,
285
459
  ...(period ? { period } : {}),
460
+ includedUsd: centsToUsd(monthly),
461
+ usedUsd: centsToUsd(Math.min(used, monthly)),
462
+ leftUsd: centsToUsd(includedLeft),
463
+ ...(renewal !== null ? { renewalUsd: centsToUsd(renewal) } : {}),
464
+ paused: active && includedLeft + extraLeft <= 0,
465
+ ...(extraLeft > 0 ? { extraUsd: centsToUsd(extraLeft) } : {}),
466
+ legacy: true,
286
467
  };
287
468
  }
288
- /** The monthly credits as said in a line: those of this period, and those of each renewal when they differ. */
289
- export function monthlyCreditsText(credits) {
290
- return credits.renewal !== undefined && credits.renewal !== credits.monthly
291
- ? `${formatCredits(credits.monthly)} credits this period, ${formatCredits(credits.renewal)} from each renewal`
292
- : `monthly ${formatCredits(credits.monthly)}`;
469
+ /** What the agent cost this calendar month, or undefined when Wiro does not say. */
470
+ export function toAgentSpend(row) {
471
+ if (!isPlainObject(row.spend))
472
+ return undefined;
473
+ const spend = row.spend;
474
+ const planUsd = toNumber(spend.planusd) ?? 0;
475
+ const aiUsageBalanceUsd = toNumber(spend.aiusagebalanceusd) ?? 0;
476
+ const modelRunsUsd = toNumber(spend.modelrunsusd) ?? 0;
477
+ const month = asString(spend.month);
478
+ return {
479
+ ...(month ? { month } : {}),
480
+ totalUsd: toNumber(spend.totalusd) ?? roundUsd(planUsd + aiUsageBalanceUsd + modelRunsUsd),
481
+ planUsd,
482
+ aiUsageBalanceUsd,
483
+ aiUsagePlanUsd: toNumber(spend.aiusageplanusd) ?? 0,
484
+ modelRunsUsd,
485
+ fundsAddedUsd: toNumber(spend.fundsaddedusd) ?? 0,
486
+ };
487
+ }
488
+ /** Why a paused agent takes no new turns, as a clause. */
489
+ function pausedText(usage) {
490
+ if (usage.pausedReason === 'plan') {
491
+ return 'it has no active plan, so it takes no new turns until a plan is paid for: manage_agent_billing with action '
492
+ + 'renew brings back an expired plan, and subscribe starts a new one. Funds alone do not run it';
493
+ }
494
+ if (usage.pausedReason === 'spendlimit') {
495
+ return 'a spend limit is reached, so it takes no new turns until the limit resets or is raised (get_controls shows it)';
496
+ }
497
+ if (usage.pausedReason === 'balance') {
498
+ return `its included usage is used up and the balance is under ${formatUsd(usage.minBalanceUsd ?? MIN_RUN_BALANCE_USD)}, `
499
+ + 'so it takes no new turns until funds are added on wiro.ai or the plan renews';
500
+ }
501
+ return 'it has no AI usage left, so it takes no new turns until its plan renews';
502
+ }
503
+ /**
504
+ * The name of the agent's AI usage line, as the agent's page titles it: Included AI usage while the plan period
505
+ * includes some, and AI usage when it includes none (no live plan, so the balance paid all of it).
506
+ */
507
+ export function aiUsageLabel(usage) {
508
+ return usage.includedUsd > 0 ? 'Included AI usage' : 'AI usage';
509
+ }
510
+ /** Whether the period includes nothing because the agent has no active plan, as Wiro says it (pausedReason plan). */
511
+ function nothingIncludedWithoutPlan(usage) {
512
+ return usage.pausedReason === 'plan' && usage.includedUsd <= 0;
513
+ }
514
+ /**
515
+ * The agent's AI usage this period as said in a line: "$12.40 of $30.00 included; then the workspace balance
516
+ * ($42.10)", or "nothing included (no active plan)" for an agent without one, with what the balance paid so far and
517
+ * why the agent is paused when it is.
518
+ */
519
+ export function aiUsageText(usage) {
520
+ const renewal = usage.renewalUsd !== undefined && !sameAmount(usage.renewalUsd, usage.includedUsd)
521
+ ? ` (${formatUsd(usage.renewalUsd)} from each renewal)`
522
+ : '';
523
+ const parts = [nothingIncludedWithoutPlan(usage)
524
+ ? 'nothing included (no active plan)'
525
+ : `${formatUsd(usage.usedUsd)} of ${formatUsd(usage.includedUsd)} included${renewal}`];
526
+ if (usage.extraUsd)
527
+ parts.push(`${formatUsd(usage.extraUsd)} bought earlier left`);
528
+ if (!usage.legacy) {
529
+ const amounts = [
530
+ ...(usage.balanceUsd !== undefined ? [formatUsd(usage.balanceUsd)] : []),
531
+ ...(usage.planBalanceUsd !== undefined ? [`${formatUsd(usage.planBalanceUsd)} of it can pay a plan`] : []),
532
+ ];
533
+ parts.push(`then the workspace balance${amounts.length > 0 ? ` (${amounts.join('; ')})` : ''}`);
534
+ }
535
+ if (usage.fromBalanceUsd)
536
+ parts.push(`${formatUsd(usage.fromBalanceUsd)} paid from the balance so far`);
537
+ return `${parts.join('; ')}${usage.paused ? `. Paused: ${pausedText(usage)}` : ''}`;
538
+ }
539
+ /**
540
+ * The agent's AI usage in a list row: "AI usage $12.40 of $30.00 included, balance $42.10, paused (balance short)",
541
+ * or "no AI usage included, balance $42.10, paused (no active plan)" for an agent without a plan.
542
+ */
543
+ export function aiUsageShortText(usage) {
544
+ const reason = usage.pausedReason === 'plan'
545
+ ? 'no active plan'
546
+ : usage.pausedReason === 'spendlimit' ? 'spend limit reached' : usage.pausedReason === 'balance' ? 'balance short' : 'no usage left';
547
+ return (nothingIncludedWithoutPlan(usage)
548
+ ? 'no AI usage included'
549
+ : `AI usage ${formatUsd(usage.usedUsd)} of ${formatUsd(usage.includedUsd)} included`)
550
+ + `${usage.extraUsd ? `, ${formatUsd(usage.extraUsd)} bought earlier left` : ''}`
551
+ + `${usage.balanceUsd !== undefined ? `, balance ${formatUsd(usage.balanceUsd)}` : ''}`
552
+ + `${usage.paused ? `, paused (${reason})` : ''}`;
553
+ }
554
+ /** What the agent cost this month as said in a line: "$33.20 (plan $30.00, model runs $3.20); ...". */
555
+ export function spendText(spend) {
556
+ const parts = [
557
+ ...(spend.planUsd > 0 ? [`plan ${formatUsd(spend.planUsd)}`] : []),
558
+ ...(spend.aiUsageBalanceUsd > 0 ? [`AI usage from the balance ${formatUsd(spend.aiUsageBalanceUsd)}`] : []),
559
+ ...(spend.modelRunsUsd > 0 ? [`model runs ${formatUsd(spend.modelRunsUsd)}`] : []),
560
+ ];
561
+ return [
562
+ `${formatUsd(spend.totalUsd)}${parts.length > 0 ? ` (${parts.join(', ')})` : ''}`,
563
+ ...(spend.aiUsagePlanUsd > 0 ? [`its plan covered ${formatUsd(spend.aiUsagePlanUsd)} of AI usage`] : []),
564
+ ...(spend.fundsAddedUsd > 0 ? [`funds added from its page ${formatUsd(spend.fundsAddedUsd)}`] : []),
565
+ ].join('; ');
293
566
  }
294
567
  // ---------------------------------------------------------------------------
295
568
  // Text helpers
@@ -348,7 +621,6 @@ export const credentialStatusSchema = z.object({
348
621
  key: z.string(),
349
622
  title: z.string(),
350
623
  optional: z.boolean(),
351
- oauth: z.boolean(),
352
624
  connected: z.boolean(),
353
625
  filled: z.boolean(),
354
626
  requiredMissing: z.boolean(),
@@ -366,7 +638,6 @@ export function summarizeCredentials(credentials, skipKeys = new Set()) {
366
638
  key,
367
639
  title: asString(schema.title) ?? key,
368
640
  optional: group.optional === true,
369
- oauth: isPlainObject(schema.oauth_provider),
370
641
  connected: group._connected === true,
371
642
  filled: group._filled === true,
372
643
  requiredMissing: group._required_missing === true,
@@ -422,6 +693,8 @@ export const agentTaskSchema = z.object({
422
693
  enabled: z.boolean(),
423
694
  notWritten: z.boolean().optional()
424
695
  .describe('The starter task whose text was never written. It does not run, even when it shows on, until its text is saved with manage_agent_custom_skill.'),
696
+ editable: z.boolean().optional()
697
+ .describe('false: a scheduled task that comes with the agent\'s template. The agent runs the template\'s text, which cannot be changed; its schedule and on/off state can.'),
425
698
  ownerSkills: z.array(z.string()).optional()
426
699
  .describe('The skills that bring this task.'),
427
700
  skillOff: z.boolean().optional()
@@ -439,7 +712,7 @@ const TASK_SOURCES = {
439
712
  'user-created': 'user',
440
713
  };
441
714
  /** Custom instructions and scheduled tasks, with the instruction text cut short. */
442
- export function summarizeTasks(value, maxInstructionLength = 300) {
715
+ export function summarizeTasks(value, maxInstructionLength = 300, options = {}) {
443
716
  if (!Array.isArray(value))
444
717
  return [];
445
718
  return value.filter(isPlainObject).map(task => {
@@ -455,6 +728,9 @@ export function summarizeTasks(value, maxInstructionLength = 300) {
455
728
  ...(description ? { description } : {}),
456
729
  enabled: task.enabled !== false,
457
730
  ...(asString(task.key) === STARTER_TASK_KEY && task._edited === false ? { notWritten: true } : {}),
731
+ // On a deployed agent, Wiro marks a scheduled task whose text its template owns as not editable. A template's
732
+ // own list means something else by the flag, so it is read only there.
733
+ ...(options.deployed && asString(task.key)?.startsWith('cs-cron-') && task._editable === false ? { editable: false } : {}),
458
734
  ...(ownerSkills.length > 0 ? { ownerSkills } : {}),
459
735
  ...(task._skill_off === true ? { skillOff: true } : {}),
460
736
  ...(offSkills.length > 0 ? { offSkills } : {}),
@@ -483,13 +759,10 @@ const modelSettingsSchema = z.object({
483
759
  const selectableModelSchema = z.object({
484
760
  slug: z.string(),
485
761
  label: z.string().optional(),
486
- inputCreditsPer1M: z.number().optional(),
487
- outputCreditsPer1M: z.number().optional(),
488
- });
489
- export const extraCreditPackSchema = z.object({
490
- pack: z.string(),
491
- credits: z.number(),
492
- priceUsd: z.number(),
762
+ inputUsdPer1M: z.number().optional()
763
+ .describe('What 1M input tokens cost, in USD.'),
764
+ outputUsdPer1M: z.number().optional()
765
+ .describe('What 1M output tokens cost, in USD.'),
493
766
  });
494
767
  export const agentSummarySchema = z.object({
495
768
  guid: z.string(),
@@ -505,7 +778,10 @@ export const agentSummarySchema = z.object({
505
778
  nextPlan: z.string().nullable().optional()
506
779
  .describe('The plan the agent moves to at its next renewal, when a move is set: another plan, or its own plan at today\'s price. null when none is set; left out when Wiro does not say.'),
507
780
  monthlyPriceUsd: z.number().nullable(),
508
- credits: creditsSchema,
781
+ usage: agentUsageSchema
782
+ .describe('The agent\'s AI usage this period in USD: what its plan includes, used and left, then the Wiro balance that pays after it.'),
783
+ spend: agentSpendSchema.optional()
784
+ .describe('What the agent cost this calendar month. Left out when Wiro does not say.'),
509
785
  subscription: subscriptionSchema.nullable(),
510
786
  timezone: z.string().nullable().optional(),
511
787
  teamSessionMode: z.string().optional(),
@@ -520,9 +796,7 @@ export const agentDetailSchema = agentSummarySchema.extend({
520
796
  cover: z.string().optional(),
521
797
  categories: z.array(z.string()),
522
798
  pricing: planPricingSchema.nullable()
523
- .describe('Each plan\'s price and monthly credits, the same for every agent. null when Wiro could not list them.'),
524
- extraCreditPacks: z.array(extraCreditPackSchema)
525
- .describe('The extra credit packs this agent can buy, the same on every plan. Only an agent with an active plan can buy them, so any other agent lists none.'),
799
+ .describe('Each plan\'s price and the AI usage it includes, the same for every agent. null when Wiro could not list them.'),
526
800
  models: modelSettingsSchema.optional(),
527
801
  selectableModels: z.array(selectableModelSchema).optional(),
528
802
  enabledCommands: z.array(z.string()).nullable(),
@@ -530,7 +804,7 @@ export const agentDetailSchema = agentSummarySchema.extend({
530
804
  .describe('Setup from chat: where the agent may propose setup changes that a person then approves. off, webchat '
531
805
  + '(the Wiro web chat only) or all (also messages sent with an API key). Left out when Wiro does not report it.'),
532
806
  credentials: z.array(credentialStatusSchema),
533
- missingCredentials: z.array(z.object({ key: z.string(), title: z.string(), oauth: z.boolean() })),
807
+ missingCredentials: z.array(z.object({ key: z.string(), title: z.string() })),
534
808
  channels: z.array(channelStatusSchema),
535
809
  scheduledTasks: z.array(agentTaskSchema),
536
810
  customInstructions: z.array(agentTaskSchema),
@@ -585,9 +859,9 @@ export function readNextPlan(row) {
585
859
  return null;
586
860
  return asPlan(value);
587
861
  }
588
- /** The plans' prices on an agent row (its agent's tiers), or null when it lists none. */
862
+ /** The plans' prices on an agent row (its agent's plans), or null when it lists none. */
589
863
  export function rowPlanPricing(row) {
590
- return toPlanPricing(isPlainObject(row.agent) ? row.agent.tiers : undefined);
864
+ return toPlanPricing(row.agent);
591
865
  }
592
866
  /**
593
867
  * The plan as it is shown. A plan that has ended costs a whole new period at the price its plan has today,
@@ -612,6 +886,7 @@ export function toAgentSummary(row) {
612
886
  const nextPlan = readNextPlan(row);
613
887
  const timezone = row.timezone === null ? null : asString(row.timezone);
614
888
  const sessionMode = asString(row.teamsessionmode);
889
+ const spend = toAgentSpend(row);
615
890
  return {
616
891
  guid: asString(row.guid) ?? '',
617
892
  title: asString(row.title) ?? '',
@@ -623,7 +898,8 @@ export function toAgentSummary(row) {
623
898
  ...(tier ? { tier } : {}),
624
899
  ...(nextPlan !== undefined ? { nextPlan } : {}),
625
900
  monthlyPriceUsd: toNumber(row.monthlypriceusd),
626
- credits: toCredits(row),
901
+ usage: toAgentUsage(row),
902
+ ...(spend ? { spend } : {}),
627
903
  subscription: planOf(row),
628
904
  ...(timezone !== undefined ? { timezone } : {}),
629
905
  ...(sessionMode ? { teamSessionMode: sessionMode } : {}),
@@ -631,7 +907,10 @@ export function toAgentSummary(row) {
631
907
  ...timestamps(row, { createdAt: 'createdat', updatedAt: 'updatedat', lastActivityAt: 'lastactivityat' }),
632
908
  };
633
909
  }
634
- /** The models an agent can switch to, with their credits per 1M input and output tokens when Wiro lists them. */
910
+ /**
911
+ * The models an agent can switch to, with what 1M input and output tokens cost in USD when Wiro lists it. Wiro
912
+ * lists the rates in hundredths of a dollar.
913
+ */
635
914
  function selectableModels(tokenRates) {
636
915
  if (!isPlainObject(tokenRates) || !isPlainObject(tokenRates.models))
637
916
  return [];
@@ -645,8 +924,8 @@ function selectableModels(tokenRates) {
645
924
  return {
646
925
  slug,
647
926
  ...(label ? { label } : {}),
648
- ...(input !== null ? { inputCreditsPer1M: input } : {}),
649
- ...(output !== null ? { outputCreditsPer1M: output } : {}),
927
+ ...(input !== null ? { inputUsdPer1M: centsToUsd(input) } : {}),
928
+ ...(output !== null ? { outputUsdPer1M: centsToUsd(output) } : {}),
650
929
  };
651
930
  });
652
931
  }
@@ -656,8 +935,7 @@ export function selectableModelSlugs(row) {
656
935
  }
657
936
  /**
658
937
  * The keys of the credentials an agent's setup waits for: a credential with a
659
- * required field empty, a required credential that holds no value yet, or a
660
- * required sign-in that is not connected. A custom build's setup waits only for
938
+ * required field empty, or a required credential that holds no value yet. A custom build's setup waits only for
661
939
  * the main credential of each active skill, which skillsmeta lists. Its chat
662
940
  * channels are never among them.
663
941
  */
@@ -673,7 +951,7 @@ export function credentialKeysSetupWaitsFor(row) {
673
951
  // A required credential whose fields are all optional has no empty required
674
952
  // field to show, and the setup still waits until it holds a value.
675
953
  .filter(credential => credential.requiredMissing
676
- || (!credential.optional && !credential.connected && (credential.oauth || (row.setuprequired === true && !credential.filled))))
954
+ || (!credential.optional && !credential.connected && row.setuprequired === true && !credential.filled))
677
955
  .filter(credential => !activeKeys || activeKeys.has(credential.key))
678
956
  // A group with no optional flag has no template row and no skill behind it, only saved values left over.
679
957
  .filter((credential) => {
@@ -684,7 +962,7 @@ export function credentialKeysSetupWaitsFor(row) {
684
962
  }
685
963
  /**
686
964
  * The full view of one deployed agent (Detail, Deploy and Update rows): its
687
- * status, plan, prices, credits and settings, and the state of each
965
+ * status, plan, prices, AI usage and settings, and the state of each
688
966
  * credential and channel.
689
967
  */
690
968
  export function toAgentDetail(row) {
@@ -701,23 +979,12 @@ export function toAgentDetail(row) {
701
979
  const agentModel = isPlainObject(row.agentModel) ? row.agentModel : undefined;
702
980
  const models = selectableModels(row.tokenRates);
703
981
  const chatSetup = readChatSetupMode(row.chatSetup);
704
- // Every plan can buy packs, but only while it is active, so only an active plan lists them.
705
- const canBuyPacks = summary.subscription?.status === 'active';
706
- const packs = canBuyPacks && Array.isArray(agent.extracreditpacks)
707
- ? agent.extracreditpacks.filter(isPlainObject).filter(pack => pack.enabled !== false)
708
- : [];
709
982
  return {
710
983
  ...summary,
711
984
  ...(description ? { description: truncate(description, 2_000) } : {}),
712
985
  ...(cover ? { cover } : {}),
713
986
  categories: toStringArray(row.categories),
714
- pricing: toPlanPricing(agent.tiers),
715
- extraCreditPacks: packs.flatMap(pack => {
716
- const name = asString(pack.packkey);
717
- const credits = toNumber(pack.credits);
718
- const priceUsd = toNumber(pack.priceusd);
719
- return name && credits !== null && priceUsd !== null ? [{ pack: name, credits, priceUsd }] : [];
720
- }),
987
+ pricing: toPlanPricing(agent),
721
988
  ...(agentModel
722
989
  ? {
723
990
  models: {
@@ -734,10 +1001,10 @@ export function toAgentDetail(row) {
734
1001
  credentials,
735
1002
  missingCredentials: credentials
736
1003
  .filter(credential => credential.requiredMissing)
737
- .map(({ key, title, oauth }) => ({ key, title, oauth })),
1004
+ .map(({ key, title }) => ({ key, title })),
738
1005
  channels,
739
- scheduledTasks: summarizeTasks(row.scheduledskills),
740
- customInstructions: summarizeTasks(row.customskills),
1006
+ scheduledTasks: summarizeTasks(row.scheduledskills, undefined, { deployed: true }),
1007
+ customInstructions: summarizeTasks(row.customskills, undefined, { deployed: true }),
741
1008
  ...timestamps(row, {
742
1009
  queuedAt: 'queuedat',
743
1010
  startedAt: 'startedat',
@@ -748,7 +1015,7 @@ export function toAgentDetail(row) {
748
1015
  dashboardUrl: agentDashboardUrl(summary.guid),
749
1016
  };
750
1017
  }
751
- export function formatSubscriptionLine(subscription, plainMember = false) {
1018
+ export function formatSubscriptionLine(subscription, plainMember = false, renewalDue = false) {
752
1019
  if (!subscription) {
753
1020
  return plainMember
754
1021
  ? 'No plan. On this team agent, a team admin, the organization\'s owner or the person who deployed it can start one.'
@@ -756,7 +1023,7 @@ export function formatSubscriptionLine(subscription, plainMember = false) {
756
1023
  }
757
1024
  const parts = [`${subscription.status}, billed ${subscription.billing === 'wallet' ? 'from the wallet' : 'by card'}`];
758
1025
  if (subscription.amountUsd !== null) {
759
- parts.push(subscription.status === 'expired' && subscription.billing === 'wallet'
1026
+ parts.push(subscription.status === 'expired'
760
1027
  ? `a new period costs ${formatUsd(subscription.amountUsd)} per 30 days`
761
1028
  : `${formatUsd(subscription.amountUsd)} per 30 days`);
762
1029
  }
@@ -768,45 +1035,51 @@ export function formatSubscriptionLine(subscription, plainMember = false) {
768
1035
  }
769
1036
  else if (subscription.periodEndsAt) {
770
1037
  const atPeriodEnd = subscription.atPeriodEnd ?? (subscription.cancelAtPeriodEnd ? 'ends' : 'renews');
1038
+ // An active plan's renewal or end as Wiro shows it, which its period end is not once a renewal is due.
1039
+ const at = renewalMoment(subscription);
771
1040
  if (subscription.status !== 'active') {
772
1041
  parts.push(`period ended ${subscription.periodEndsAt}`);
773
1042
  }
774
1043
  else if (atPeriodEnd === 'ends') {
775
- parts.push(`cancelled, ends after ${subscription.periodEndsAt}`);
1044
+ parts.push(`cancelled, ends after ${at}`);
776
1045
  }
777
1046
  else if (atPeriodEnd === 'renews') {
778
- parts.push(`renews after ${subscription.periodEndsAt}`);
1047
+ parts.push(renewalDue ? RENEWAL_DUE_NOW : `renews after ${at}`);
779
1048
  }
780
1049
  else {
781
1050
  // Whether this card plan renews is not known here.
782
- parts.push(`paid through ${subscription.periodEndsAt}`);
1051
+ parts.push(`paid through ${at}`);
783
1052
  }
784
1053
  }
785
1054
  if (subscription.switchingToWallet)
786
- parts.push('switching to wallet billing at period end');
1055
+ parts.push('moves to the Wiro balance at period end');
787
1056
  return parts.join(', ');
788
1057
  }
789
- /** Without an active plan, an agent starts only on the extra credits it has left. */
1058
+ /**
1059
+ * An agent starts only with an active plan. An answer from an older Wiro release can still show usage bought
1060
+ * earlier, on which an agent without a plan starts too.
1061
+ */
790
1062
  export function startNeedsPlan(agent) {
791
- return agent.subscription?.status !== 'active' && agent.credits.extra <= 0;
1063
+ return agent.subscription?.status !== 'active' && (agent.usage.extraUsd ?? 0) <= 0;
792
1064
  }
793
1065
  /**
794
- * renew brings back an expired wallet plan; any other agent without an active plan takes a new one. A plan that
795
- * has not ended, such as a card plan whose last payment did not go through, takes neither: null.
1066
+ * renew brings back an expired plan, a card plan's included, from the Wiro balance; any other agent without an
1067
+ * active plan takes a new one. A plan that has not ended, such as a card plan whose last payment did not go
1068
+ * through, takes neither: null.
796
1069
  */
797
1070
  function planActionForStart(agent) {
798
1071
  if (isUnsettledPlan(agent.subscription))
799
1072
  return null;
800
- return agent.subscription?.status === 'expired' && agent.subscription.billing === 'wallet' ? 'renew' : 'subscribe';
1073
+ return agent.subscription?.status === 'expired' ? 'renew' : 'subscribe';
801
1074
  }
802
- const NO_PLAN_TO_START = 'It has no active plan and no extra credits left, so it cannot start.';
1075
+ const NO_PLAN_TO_START = 'It has no active plan, so it cannot start.';
803
1076
  function noPlanStartHint(agent) {
804
1077
  if (agent.subscription && isUnsettledPlan(agent.subscription)) {
805
- return unsettledPlanText(agent.subscription, agent, 'The agent cannot start until the plan is active again, since it has no extra credits left.');
1078
+ return unsettledPlanText(agent.subscription, agent, 'The agent cannot start until the plan is active again.');
806
1079
  }
807
1080
  return `${NO_PLAN_TO_START} `
808
1081
  + (planActionForStart(agent) === 'renew'
809
- ? 'Its wallet plan has expired; manage_agent_billing with action renew restarts it.'
1082
+ ? 'Its plan has expired; manage_agent_billing with action renew restarts it, paid from the Wiro balance.'
810
1083
  : 'manage_agent_billing with action subscribe pays for a plan and starts the agent.');
811
1084
  }
812
1085
  /** An agent's title inside a line of this server's own text: on one line, in a code span it cannot close. */
@@ -816,14 +1089,16 @@ export function agentTitleSpan(title) {
816
1089
  /**
817
1090
  * The move set for the next renewal, as a clause after the plan: "moves to Starter from the renewal after
818
1091
  * <date>", or for the agent's own plan "from the renewal after <date> it is billed at today's Starter
819
- * price". Empty when none is set, or when the plan ends with its period instead of renewing.
1092
+ * price". Empty when none is set, or when the plan ends with its period instead of renewing. While the renewal is
1093
+ * due, it starts from the renewal due now.
820
1094
  */
821
1095
  export function nextPlanText(agent) {
822
1096
  const next = agent.nextPlan;
823
1097
  const subscription = agent.subscription;
824
1098
  if (!next || subscription?.status !== 'active' || subscription.atPeriodEnd === 'ends')
825
1099
  return '';
826
- const when = subscription.periodEndsAt ? `the renewal after ${subscription.periodEndsAt}` : 'the next renewal';
1100
+ const at = renewalMoment(subscription);
1101
+ const when = agent.usage.renewalDue ? 'the renewal due now' : at ? `the renewal after ${at}` : 'the next renewal';
827
1102
  return next === agent.tier
828
1103
  ? `from ${when} it is billed at today's ${planName(next)} price`
829
1104
  : `moves to ${planName(next)} from ${when}`;
@@ -839,13 +1114,16 @@ export function formatAgentSummaryLines(agent, plainMember = false) {
839
1114
  : `template ${agent.template.title ?? agent.template.slug ?? agent.template.guid}`;
840
1115
  const hint = !plainMember && (agent.status === 0 || agent.status === 5) && startNeedsPlan(agent)
841
1116
  ? `${agent.status === 5 ? 'The start failed or the agent stopped unexpectedly.' : 'It is not running.'} ${noPlanStartHint(agent)}`
842
- : agentStatusHint(agent.status, plainMember);
1117
+ : agent.status === 4 && agent.usage.paused
1118
+ ? `It is running, but paused: it takes no new turns now (see ${aiUsageLabel(agent.usage)}).`
1119
+ : agentStatusHint(agent.status, plainMember);
843
1120
  const next = nextPlanText(agent);
844
1121
  return [
845
1122
  `**Agent:** ${agentTitleSpan(agent.title)} (\`${agent.guid}\`), ${template}, ${agent.workspace} workspace`,
846
1123
  `**Status:** ${describeAgentStatus(agent.status)}. ${hint}`,
847
- `**Plan:** ${agent.tier ? planName(agent.tier) : 'no plan'}; ${formatSubscriptionLine(agent.subscription, plainMember)}${next ? `; ${next}` : ''}`,
848
- `**Credits:** ${formatCredits(agent.credits.remaining)} left (${monthlyCreditsText(agent.credits)}, extra ${formatCredits(agent.credits.extra)}, used ${formatCredits(agent.credits.used)})`,
1124
+ `**Plan:** ${agent.tier ? planName(agent.tier) : 'no plan'}; ${formatSubscriptionLine(agent.subscription, plainMember, agent.usage.renewalDue)}${next ? `; ${next}` : ''}`,
1125
+ `**${aiUsageLabel(agent.usage)}:** ${aiUsageText(agent.usage)}`,
1126
+ ...(agent.spend ? [`**Spent this month:** ${spendText(agent.spend)}`] : []),
849
1127
  ];
850
1128
  }
851
1129
  /** Where an entry the list shortens is read in full. */
@@ -898,12 +1176,12 @@ const KEY_WORDS = {
898
1176
  // letters is an abbreviation and is written in capitals.
899
1177
  const TITLE_CASE_2L = new Set(['my', 'us', 'we', 'me', 'he', 'an', 'at', 'in', 'on', 'of', 'to', 'by', 'do', 'go', 'if', 'is', 'it', 'no', 'or', 'so', 'up', 'am', 'as', 'be', 'oh', 'ok']);
900
1178
  /**
901
- * A name made from a key, as the dashboard makes it, for when there is no title: int-brevo-email reads
902
- * Brevo Email and ga4-attribution-auditor GA4 Attribution Auditor. known: false leaves the list of brands
1179
+ * A name made from a key, as the dashboard makes it, for when there is no title: util-video-creator reads
1180
+ * Video Creator and ga4-attribution-auditor GA4 Attribution Auditor. known: false leaves the list of brands
903
1181
  * and acronyms out, for a name the customer typed.
904
1182
  */
905
1183
  export function wordsFromKey(key, { known = true } = {}) {
906
- return key.replace(/^(int|util)-/, '').replace(/-/g, ' ').replace(/\b\w+\b/g, word => {
1184
+ return key.replace(/^util-/, '').replace(/-/g, ' ').replace(/\b\w+\b/g, word => {
907
1185
  const lower = word.toLowerCase();
908
1186
  if (known && Object.prototype.hasOwnProperty.call(KEY_WORDS, lower))
909
1187
  return KEY_WORDS[lower];
@@ -926,8 +1204,8 @@ export function taskNamedByWiro(task) {
926
1204
  return !(task.source === 'user' || task.source === 'user-created' || task.userCreated === true) || (task.ownerSkills?.length ?? 0) > 0;
927
1205
  }
928
1206
  /**
929
- * A skill as people see it, by its catalog title, with the name apply_agent_skills takes: Gmail Check
930
- * (`int-gmail-check`). Without the title, words made from the name stand in for it.
1207
+ * A skill as people see it, by its catalog title, with the name apply_agent_skills takes: Video Creator
1208
+ * (`util-video-creator`). Without the title, words made from the name stand in for it.
931
1209
  */
932
1210
  export function skillLabel(name, titles) {
933
1211
  return `${titles?.get(name) ?? wordsFromKey(name)} (\`${name}\`)`;
@@ -973,21 +1251,22 @@ export function skillOffTasksNote(tasks, titles, verb = 'stays paused') {
973
1251
  * was cut. titles names the skills a paused task waits for as people see them.
974
1252
  */
975
1253
  export function formatScheduledTaskLine(task, shortenedNote = '', titles) {
976
- return `- ${taskLabel(task.key, taskNamedByWiro(task))} ${task.enabled ? 'on' : 'off'}${task.notWritten ? ' (its text is not written yet, so it does not run)' : ''}${task.skillOff ? ` (${skillOffText(task, titles)})` : ''}${task.interval ? `, ${task.interval}` : ''}${task.description ? `: ${quotedSpan(task.description)}` : ''}${task.instructionsTruncated ? shortenedNote : ''}`;
1254
+ return `- ${taskLabel(task.key, taskNamedByWiro(task))} ${task.enabled ? 'on' : 'off'}${task.notWritten ? ' (its text is not written yet, so it does not run)' : ''}${task.editable === false ? ' (the template\'s text, which cannot be changed)' : ''}${task.skillOff ? ` (${skillOffText(task, titles)})` : ''}${task.interval ? `, ${task.interval}` : ''}${task.description ? `: ${quotedSpan(task.description)}` : ''}${task.instructionsTruncated ? shortenedNote : ''}`;
977
1255
  }
978
1256
  /** A custom instruction as a list line: name and key, on or off and description, then shortenedNote if its text was cut. */
979
1257
  export function formatCustomInstructionLine(task, shortenedNote = '') {
980
1258
  return `- ${taskLabel(task.key, taskNamedByWiro(task))} ${task.enabled ? 'on' : 'off'}${task.description ? `: ${quotedSpan(task.description)}` : ''}${task.instructionsTruncated ? shortenedNote : ''}`;
981
1259
  }
982
- function formatRate(credits) {
983
- return credits.toLocaleString('en-US', { maximumFractionDigits: 3 });
1260
+ /** A rate in USD per 1M tokens, with cents and up to four decimals: $6.25, $0.125. */
1261
+ export function formatRateUsd(value) {
1262
+ return `$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`;
984
1263
  }
985
- /** Each model with its credits per 1M input and output tokens, separated by semicolons. */
1264
+ /** Each model with what 1M input and output tokens cost in USD, separated by semicolons. */
986
1265
  export function formatModelRates(models) {
987
1266
  return models.map(model => {
988
1267
  const name = model.label ? `${model.label} (${model.slug})` : model.slug;
989
- return model.inputCreditsPer1M !== undefined && model.outputCreditsPer1M !== undefined
990
- ? `${name} ${formatRate(model.inputCreditsPer1M)} and ${formatRate(model.outputCreditsPer1M)}`
1268
+ return model.inputUsdPer1M !== undefined && model.outputUsdPer1M !== undefined
1269
+ ? `${name} ${formatRateUsd(model.inputUsdPer1M)} and ${formatRateUsd(model.outputUsdPer1M)}`
991
1270
  : `${name} rate unknown`;
992
1271
  }).join('; ');
993
1272
  }
@@ -999,12 +1278,13 @@ function formatModelsLine(agent) {
999
1278
  if (agent.models)
1000
1279
  parts.push(`chat ${nameOf(agent.models.chat)}, scheduled tasks ${nameOf(agent.models.cron)}.`);
1001
1280
  if (choices.length > 0) {
1002
- parts.push(`Models you can switch to, in credits per 1M input and output tokens: ${formatModelRates(choices)}.`);
1281
+ parts.push(`Models you can switch to, in USD per 1M input and output tokens: ${formatModelRates(choices)}.`);
1003
1282
  }
1004
1283
  return parts.length > 0 ? `**Models:** ${parts.join(' ')}` : null;
1005
1284
  }
1006
1285
  /** titles names skills as people see them: the agent's own (activeSkillTitles) and those a paused task waits for (pausedSkillTitles). */
1007
- export function formatAgentDetail(agent, plainMember = false, titles) {
1286
+ /** extraLines: sections that go before the dashboard link, such as the agent's connectors. */
1287
+ export function formatAgentDetail(agent, plainMember = false, titles, extraLines = []) {
1008
1288
  const lines = formatAgentSummaryLines(agent, plainMember);
1009
1289
  if (agent.lastActivityAt)
1010
1290
  lines.push(`**Last activity:** ${agent.lastActivityAt}`);
@@ -1012,7 +1292,7 @@ export function formatAgentDetail(agent, plainMember = false, titles) {
1012
1292
  if (plans) {
1013
1293
  // The plans' prices today, the same for every agent. A plan that started at
1014
1294
  // another price keeps it until a change or a renewal moves it.
1015
- lines.push(`**Plans:** ${plans}. Every plan includes every skill. A move to a larger plan starts now, and a move to a smaller one at the next renewal.`);
1295
+ lines.push(`**Plans:** ${plans}. Every plan includes every skill. After the included AI usage, the agent uses the workspace's Wiro balance. A move to a larger plan starts now, and a move to a smaller one at the next renewal.`);
1016
1296
  }
1017
1297
  const models = formatModelsLine(agent);
1018
1298
  if (models)
@@ -1038,7 +1318,7 @@ export function formatAgentDetail(agent, plainMember = false, titles) {
1038
1318
  const state = credential.connected
1039
1319
  ? 'connected'
1040
1320
  : credential.requiredMissing
1041
- ? (credential.oauth ? 'not connected (required)' : 'missing (required)')
1321
+ ? 'missing (required)'
1042
1322
  : credential.filled
1043
1323
  ? 'filled'
1044
1324
  : 'not set';
@@ -1055,7 +1335,7 @@ export function formatAgentDetail(agent, plainMember = false, titles) {
1055
1335
  for (const task of agent.customInstructions)
1056
1336
  lines.push(formatCustomInstructionLine(task, shortenedNote(task.key)));
1057
1337
  }
1058
- lines.push('', `Dashboard: ${agent.dashboardUrl}`);
1338
+ lines.push(...extraLines, '', `Dashboard: ${agent.dashboardUrl}`);
1059
1339
  return lines.join('\n');
1060
1340
  }
1061
1341
  // Custom skill keys get the same canonical shape the server gives them, so a
@@ -1140,17 +1420,11 @@ export function missingCredentialStep(agent) {
1140
1420
  if (missing.key === WIRO_PROJECT_CREDENTIAL) {
1141
1421
  return bindProjectStep(agent.guid, `Provide the missing credentials (${keys}), starting with ${missing.title}.`);
1142
1422
  }
1143
- return missing.oauth
1144
- ? {
1145
- tool: 'connect_agent_oauth',
1146
- arguments: { action: 'connect', agent_guid: agent.guid, credential: missing.key },
1147
- reason: `Provide the missing credentials (${keys}). This starts with ${missing.title}, which the user connects by signing in.`,
1148
- }
1149
- : {
1150
- tool: 'set_agent_credentials',
1151
- arguments: { agent_guid: agent.guid, credential: missing.key },
1152
- reason: `Provide the missing credentials (${keys}). This lists the ${missing.title} fields to ask the user for.`,
1153
- };
1423
+ return {
1424
+ tool: 'set_agent_credentials',
1425
+ arguments: { agent_guid: agent.guid, credential: missing.key },
1426
+ reason: `Provide the missing credentials (${keys}). This lists the ${missing.title} fields to ask the user for.`,
1427
+ };
1154
1428
  }
1155
1429
  /**
1156
1430
  * The most useful next call for an agent in this state, if any. For a team
@@ -1186,7 +1460,7 @@ export function nextStepForAgent(agent, waitSeconds, plainMember = false) {
1186
1460
  ? {
1187
1461
  tool: 'manage_agent_billing',
1188
1462
  arguments: { agent_guid: agent.guid, action },
1189
- reason: 'The agent has no active plan and no extra credits left, so it cannot start. This returns the price; nothing is charged without confirm: true.',
1463
+ reason: 'The agent has no active plan, so it cannot start. This returns the price; nothing is charged without confirm: true.',
1190
1464
  }
1191
1465
  : undefined;
1192
1466
  }
@@ -1199,7 +1473,8 @@ export function nextStepForAgent(agent, waitSeconds, plainMember = false) {
1199
1473
  }
1200
1474
  return undefined;
1201
1475
  }
1202
- // Refusals known to leave the wallet untouched (93: a spend limit refused the purchase).
1476
+ // Refusals known to leave the wallet untouched (93: a spend limit refused the purchase; 97: among others, a
1477
+ // balance too short for a plan payment).
1203
1478
  const PRE_CHARGE_CODES = new Set([93, 95, 96, 97, 99, 101, 102, 103, 104, 105, 106, 107, 108, 109]);
1204
1479
  const WALLET_NOT_READ = /could not retrieve wallet balance/i;
1205
1480
  /** Whether a refusal says the wallet could not be read, which says nothing about what it holds. */
@@ -1216,8 +1491,6 @@ const PRE_CHARGE_REFUSALS = [
1216
1491
  /already on (the )?(starter|pro|max) (tier|plan)/i,
1217
1492
  /no active subscription|active subscription required|no expired subscription found/i,
1218
1493
  /stripe subscriptions must be/i,
1219
- /extra credit pack|pack key required|purchase request id/i,
1220
- /could not (initialize|resume) prepaid credit purchase|prepaid credit purchase cannot be resumed/i,
1221
1494
  /downgrading to starter is not supported|targettier must be|tier must be 'starter'|change the plan with upgradetier/i,
1222
1495
  /failed to compute (target-tier )?pricing|must be greater than \$0|failed to apply pricing snapshot/i,
1223
1496
  /failed to create subscription record|subscription record returned invalid id/i,
@@ -1238,6 +1511,8 @@ const PRE_CHARGE_REFUSALS = [
1238
1511
  /^the (starter|pro|max) plan is smaller than this agent's (starter|pro|max) plan, so this is not an upgrade\. nothing was changed\./i,
1239
1512
  /^this agent is on the (starter|pro|max) plan now, so (starter|pro|max) is an upgrade\. nothing was changed\./i,
1240
1513
  /^the move to the (starter|pro|max) plan started with this billing period, and its payment moves the agent there, so it can no longer be undone\. nothing was changed\./i,
1514
+ // A move to a larger plan while the plan's renewal is due.
1515
+ /^this plan's renewal is due, so it can't be upgraded until it renews\. .*nothing was charged\./i,
1241
1516
  /^the (scheduled )?plan change could not be (scheduled|cancelled)\./i,
1242
1517
  /^we couldn't (schedule|undo) the cancellation\./i,
1243
1518
  /enabledchannels is not accepted|credentials must be an object|credential field|is missing required fields/i,
@@ -1288,7 +1563,7 @@ export function outcomeUnknown(error) {
1288
1563
  }
1289
1564
  return true;
1290
1565
  }
1291
- /** Advice for a status reached after a start, renew or deploy. With the agent, a failed agent without a plan or extra credits is sent to billing. */
1566
+ /** Advice for a status reached after a start, renew or deploy. With the agent, a failed agent without a plan is sent to billing. */
1292
1567
  export function settledStatusAdvice(status, plainMember = false, agent) {
1293
1568
  if (!plainMember && agent && status === 5 && startNeedsPlan(agent)) {
1294
1569
  return `The agent failed to start. ${noPlanStartHint(agent)}`;
@@ -1305,7 +1580,7 @@ export function settledStatusAdvice(status, plainMember = false, agent) {
1305
1580
  case 5:
1306
1581
  return 'The agent failed to start. get_agent_activity with kind logs may show why, and control_agent with action start retries.';
1307
1582
  case 0:
1308
- return 'The agent is stopped. Right after a start this means it has no active plan and no credits left, or someone stopped it.';
1583
+ return 'The agent is stopped. Right after a start this means it has no active plan, or someone stopped it.';
1309
1584
  case 6:
1310
1585
  return 'The agent needs setup: it has no paid plan, or required credentials are missing.';
1311
1586
  default: