@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
@@ -1,778 +0,0 @@
1
- import { z } from 'zod';
2
- import { ApiResultError, apiErrorMessage, asString, errorResult, errorText, isPlainObject, requireApiSuccess, } from '../utils/api.js';
3
- import { CONNECTION_NOT_CLEARED, OAUTH_LINK_TTL_SECONDS, accountLabel, agentStatusOf, apiBaseUrlOf, buildChainedSelections, chooseConnectionMode, connectionModeRequirements, connectionRefusalText, connectionState, credentialGroup, customSkillEntries, dashboardAgentUrl, entriesTurnedOnBy, isAgentRunning, isAllowedRedirectUrl, isFilledValue, loadCredentialMeta, loadSkillRegistry, modeContext, ownAppRedirectUri, ownCandidates, ownFailedFlow, parseDiscoveredGroups, pausedSkillTitles, pickedAccountIds, readOAuthStatus, readUserAgent, savedForModesText, skillTitles, statusRedirectUri, toAccountRefs, turnOnSkillText, unusedCredential, unusedCredentialNote, writeOnlyModesNote, } from '../utils/agent-config.js';
4
- import { DEFAULT_WAIT_SECONDS, MAX_WAIT_SECONDS, pollUntil, reportProgress, } from '../utils/poll.js';
5
- import { jsonSpan } from '../utils/quoted-text.js';
6
- import { readStatusAdvice, skillOffTasksNote, startNeedsPlan, taskLabel, taskNamedByWiro, toAgentDetail, waitingTaskSentence, WIRO_PROJECT_CREDENTIAL } from '../utils/user-agent.js';
7
- import { nextActionSchema, strictInput } from './schemas.js';
8
- const accountSchema = z.object({ id: z.string(), name: z.string() });
9
- const outputSchema = {
10
- action: z.enum(['connect', 'status', 'select_accounts']),
11
- agentGuid: z.string(),
12
- credential: z.string(),
13
- title: z.string(),
14
- state: z.enum([
15
- 'authorize_in_browser',
16
- 'connected',
17
- 'pick_accounts',
18
- 'pick_child_items',
19
- 'waiting_for_user',
20
- 'token_expired',
21
- 'not_connected',
22
- 'setup_needed',
23
- 'confirm_needed',
24
- ]),
25
- mode: z.string().optional(),
26
- authorizeUrl: z.string().optional(),
27
- expiresInSeconds: z.number().optional(),
28
- redirectUrl: z.string().optional(),
29
- connectedAt: z.string().optional(),
30
- tokenExpiresAt: z.string().optional(),
31
- accounts: z.array(accountSchema).optional(),
32
- candidates: z.array(accountSchema).optional(),
33
- childStep: z.object({
34
- picker: z.string(),
35
- label: z.string(),
36
- optional: z.boolean(),
37
- configured: z.boolean().optional(),
38
- groups: z.array(z.object({
39
- parent: accountSchema,
40
- items: z.array(accountSchema),
41
- error: z.string().optional(),
42
- })),
43
- }).optional(),
44
- connectionModes: z.array(z.object({
45
- mode: z.string(),
46
- available: z.boolean(),
47
- needsBrowser: z.boolean(),
48
- fields: z.array(z.object({ field: z.string(), label: z.string(), isSet: z.boolean(), writeOnly: z.boolean().optional() })),
49
- note: z.string(),
50
- })).optional(),
51
- ownAppRedirectUri: z.string().optional(),
52
- appKeysSaved: z.boolean().optional()
53
- .describe('status: true when Wiro says the keys of the user\'s own app (mode own) are saved. They are never shown. Left out otherwise, which does not mean they are missing.'),
54
- tokenSaved: z.boolean().optional()
55
- .describe('status: whether the token, or every field the token check reads, is saved, as Wiro says.'),
56
- message: z.string(),
57
- nextAction: nextActionSchema.optional(),
58
- };
59
- const DONE_STATES = new Set(['connected', 'pick_accounts', 'pick_child_items']);
60
- // Wiro keeps the accounts a sign-in or token check found for 15 minutes, only for the person who started it, and
61
- // saves only accounts from that list. These codes say the list is gone or someone else's.
62
- const FLOW_GONE_CODES = new Set(['flow_expired', 'flow_other_person', 'flow_replaced']);
63
- // A sign-in still open in the browser has no list yet. A new connect would replace it, and that sign-in would then
64
- // save nothing, so the user finishes it instead.
65
- const FLOW_WAITING_HINT = 'The sign-in is still open: ask the user to finish it in the browser, then call select_accounts '
66
- + 'again (connect_agent_oauth status with wait_seconds waits until it is done). Do not start a new connect, which '
67
- + 'would replace the open sign-in.';
68
- // Wiro words these refusals for a sign-in or for a token check, as the list they are about, the saved mode or the
69
- // service's first way to connect says. The hints after them fit both.
70
- function oauthHint(message, meta, code) {
71
- if (code === 'not_listed')
72
- return 'Save only accounts from the list connect_agent_oauth gave after the sign-in or token check.';
73
- if (code === 'flow_waiting')
74
- return FLOW_WAITING_HINT;
75
- if (code && FLOW_GONE_CODES.has(code)) {
76
- return 'Connect again: the list is kept 15 minutes and only for the person who started the sign-in or token check.';
77
- }
78
- if (code === 'flow_failed')
79
- return 'Connect again with action connect.';
80
- if (code === 'next_expired')
81
- return 'Call select_accounts again; it lists the items afresh before saving.';
82
- if (/credentials not configured/i.test(message)) {
83
- return `Save your own ${meta.title} app keys with set_agent_credentials first (call it with credential "${meta.key}" to see the fields).`;
84
- }
85
- // A sign-in with Wiro's own app that is not open for this service: "Sign-in with the platform's app is not enabled
86
- // for <title>", as Wiro words it now, or "Wiro-managed OAuth is not enabled for <title>", as it did.
87
- if (/(sign-in with the platform's app|wiro-managed oauth) is not enabled/i.test(message)) {
88
- return 'Connect this service with mode own (your own app) or api_key where offered.';
89
- }
90
- if (/no pending .* connection/i.test(message)) {
91
- return 'The account list from the last connect expired after 15 minutes. Connect again.';
92
- }
93
- if (/account not connected/i.test(message))
94
- return 'Connect the account first with action connect.';
95
- if (/candidates expired/i.test(message))
96
- return 'Call select_accounts again; it lists the items afresh before saving.';
97
- return undefined;
98
- }
99
- /** Wiro's message, then the hint as a paragraph of its own, so the two read as separate sentences. */
100
- function withHint(error, meta) {
101
- const message = errorText(error);
102
- const code = error instanceof ApiResultError ? asString(error.body.errorcode) : undefined;
103
- const hint = meta ? oauthHint(message, meta, code) : undefined;
104
- return new Error(hint ? `${message}\n\n${hint}` : message);
105
- }
106
- function childStepOf(picker, groups, configured) {
107
- const next = picker?.next;
108
- if (!next)
109
- return undefined;
110
- return {
111
- picker: next.key,
112
- label: next.label,
113
- optional: next.optional,
114
- ...(configured !== undefined ? { configured } : {}),
115
- groups: groups.map(group => ({
116
- parent: group.parent,
117
- items: group.items,
118
- ...(group.errorCode ? { error: group.errorCode } : {}),
119
- })),
120
- };
121
- }
122
- function accountsLine(accounts) {
123
- return accounts.map(accountLabel).join(', ');
124
- }
125
- function result(action, context, state, message, extra = {}, textExtra = []) {
126
- const lines = [
127
- `## ${context.meta.title}: ${state.replace(/_/g, ' ')}`,
128
- '',
129
- message,
130
- ...textExtra,
131
- ];
132
- if (isPlainObject(extra.nextAction)) {
133
- lines.push('', `Next: call ${String(extra.nextAction.tool)} with ${jsonSpan(extra.nextAction.arguments)}.`);
134
- }
135
- return {
136
- content: [{ type: 'text', text: lines.join('\n') }],
137
- structuredContent: {
138
- action,
139
- agentGuid: context.agentGuid,
140
- credential: context.credential,
141
- title: context.meta.title,
142
- state,
143
- message,
144
- ...extra,
145
- },
146
- };
147
- }
148
- function modeLines(modes) {
149
- return [
150
- '',
151
- ...modes.filter(mode => mode.available).map(mode => `- **${mode.mode}**: ${mode.note}${mode.fields.length > 0 ? ` Fields: ${mode.fields.map(field => `${field.field}${field.isSet ? ' (set)' : field.writeOnly ? '' : ' (missing)'}`).join(', ')}.` : ''}`),
152
- ];
153
- }
154
- /** The answer to a connect that the rule on unused credentials refuses, or null when it may go ahead. */
155
- function unusedCredentialRefusal(row, context, registry) {
156
- const { credential, meta } = context;
157
- const unused = unusedCredential(row, credential, registry);
158
- if (!unused)
159
- return null;
160
- return [
161
- `${meta.title} is not used by any of this agent's active skills, custom skills or scheduled tasks, so nothing was started.`,
162
- unused.services.length > 0
163
- ? `Services its skills connect with this tool: ${unused.services.join(', ')}.`
164
- : 'None of its skills connect a service with this tool.',
165
- turnOnSkillText(meta.title, credential, unused.skills),
166
- credentialGroup(row, credential)?._connected === true ? `${meta.title} is still connected from before; disconnect_agent_oauth removes that connection.` : '',
167
- ].filter(Boolean).join(' ');
168
- }
169
- /**
170
- * What a finished sign-in does to the entries that need the service (entriesTurnedOnBy): the ones it turns on,
171
- * the ones it turns on that stay paused for skills that are off, the tasks already on that start running, and
172
- * those that still wait for skills. Each task is named as people see it, and each skill by its title. A task
173
- * that is on runs only while the agent runs, so on an agent that is not running it would run once it starts.
174
- */
175
- function turnsOnNote({ on, paused, starts, waiting }, { meta }, titles, running) {
176
- if (on.length === 0 && paused.length === 0 && starts.length === 0 && waiting.length === 0)
177
- return '';
178
- const names = (entries) => entries.map(entry => taskLabel(entry.key, taskNamedByWiro(entry))).join(', ');
179
- const startRunning = running
180
- ? `${starts.length > 1 ? 'start' : 'starts'} running once ${meta.title} is connected`
181
- : `would run once ${meta.title} is connected and the agent starts`;
182
- const sentence = (on.length > 0 ? ` ${names(on)} ${on.length > 1 ? 'turn' : 'turns'} on once ${meta.title} is connected.` : '')
183
- + paused.map(task => waitingTaskSentence(task.key, task.groups, titles, 'turns on but stays paused')).join('')
184
- + (starts.length > 0 ? ` ${names(starts)} ${startRunning}.` : '')
185
- + waiting.map(task => waitingTaskSentence(task.key, task.groups, titles, 'stays paused')).join('');
186
- return [...on, ...starts].some(entry => entry.kind === 'scheduled_task') || paused.length > 0
187
- ? `${sentence} Every run of a scheduled task uses credits; turn off any you do not want with manage_agent_custom_skill.`
188
- : sentence;
189
- }
190
- async function connect(context, input) {
191
- const { client, agentGuid, credential, meta, signal } = context;
192
- const oauth = meta.oauth;
193
- const row = await readUserAgent(client, agentGuid, signal);
194
- const refusal = unusedCredentialRefusal(row, context, await loadSkillRegistry(client, signal));
195
- if (refusal)
196
- return errorResult(new Error(refusal));
197
- const group = credentialGroup(row, credential);
198
- const apiBase = apiBaseUrlOf(client);
199
- // One status read gives the connection time before this sign-in, the redirect URI Wiro gives for the user's own
200
- // app, whether Wiro says the app keys are saved and whether the token is. A connect still goes ahead without it.
201
- const before = await readOAuthStatus(client, agentGuid, credential, oauth.picker, signal).catch(() => null);
202
- const modes = connectionModeRequirements(meta, group, modeContext(before, apiBase));
203
- const redirectUri = meta.connectionModes.includes('own') ? ownAppRedirectUri(meta, before?.redirectUri, apiBase) : undefined;
204
- const setupExtra = { connectionModes: modes, ...(redirectUri ? { ownAppRedirectUri: redirectUri } : {}) };
205
- const describeAction = {
206
- tool: 'set_agent_credentials',
207
- arguments: { agent_guid: agentGuid, credential },
208
- reason: 'See the fields and their formats before asking the user for them.',
209
- };
210
- if (input.mode && !modes.some(mode => mode.mode === input.mode)) {
211
- return errorResult(new Error(`${meta.title} cannot connect with mode ${input.mode}. Modes: ${modes.filter(mode => mode.available).map(mode => mode.mode).join(', ')}.`));
212
- }
213
- const mode = input.mode ?? chooseConnectionMode(meta, modes);
214
- const requirement = modes.find(candidate => candidate.mode === mode);
215
- if (!mode || !requirement) {
216
- const savedKeysNote = writeOnlyModesNote(modes);
217
- return result('connect', context, 'setup_needed', `Choose how to connect ${meta.title}: it needs your own app keys or a token saved first.${savedKeysNote ? ` ${savedKeysNote}` : ''}`, { ...setupExtra, nextAction: describeAction }, modeLines(modes));
218
- }
219
- if (!requirement.available) {
220
- return result('connect', context, 'setup_needed', `${requirement.note}`, { ...setupExtra, mode, nextAction: describeAction }, modeLines(modes));
221
- }
222
- if (mode === 'api_key' && !oauth.directProbe) {
223
- return result('connect', context, 'setup_needed', requirement.note, { ...setupExtra, mode, nextAction: describeAction }, modeLines(modes));
224
- }
225
- // App keys read as empty even once saved, so for those the sign-in route below decides.
226
- const missing = requirement.fields.filter(field => !field.isSet && !field.writeOnly);
227
- if (missing.length > 0) {
228
- return result('connect', context, 'setup_needed', `Mode ${mode} needs these saved first with set_agent_credentials: ${missing.map(field => `${field.label} (${field.field})`).join(', ')}. ${requirement.note}`, { ...setupExtra, mode, nextAction: describeAction });
229
- }
230
- const connectedBefore = group?._connected === true;
231
- // A sign-in removes what is saved for the modes it leaves.
232
- const removed = mode === oauth.directProbe?.mode
233
- ? []
234
- : meta.fields.filter(field => !field.oauthManaged
235
- && field.onlyInModes?.length
236
- && !field.onlyInModes.includes(mode)
237
- && isFilledValue(group?.[field.key]));
238
- const appKeys = requirement.fields.filter(field => field.writeOnly);
239
- if ((connectedBefore || removed.length > 0) && !input.confirm) {
240
- const saveKeysFirst = removed.length > 0 && appKeys.length > 0
241
- ? ' Save the app keys first if they are not saved yet, so the sign-in can start.'
242
- : '';
243
- return result('connect', context, 'confirm_needed', `${connectedBefore
244
- ? `${meta.title} is already connected. Connecting again replaces that connection and its selected accounts; if the new sign-in or check fails, the agent is left without it.`
245
- : `Connecting ${meta.title} with mode ${mode} removes the saved ${removed.map(field => field.label).join(', ')}.`}${saveKeysFirst}`, {
246
- mode,
247
- nextAction: {
248
- tool: 'connect_agent_oauth',
249
- arguments: {
250
- action: 'connect',
251
- agent_guid: agentGuid,
252
- credential,
253
- mode,
254
- ...(input.redirectUrl ? { redirect_url: input.redirectUrl } : {}),
255
- confirm: true,
256
- },
257
- reason: 'Ask the user to confirm this first.',
258
- },
259
- });
260
- }
261
- if (oauth.directProbe && mode === oauth.directProbe.mode) {
262
- // The check reads the mode from the saved credential, so it is saved first.
263
- const modeSaved = asString(group?.authmethod) !== mode;
264
- if (modeSaved) {
265
- requireApiSuccess(await client.post('/UserAgent/CredentialUpsert', {
266
- useragentguid: agentGuid,
267
- fields: [{ credentialkey: credential, fieldname: 'authmethod', fieldvalue: mode }],
268
- }, signal), 'Could not switch the connection mode.');
269
- }
270
- const body = await client.post('/UserAgentOAuth/OAuthConnect', {
271
- useragentguid: agentGuid,
272
- credentialkey: credential,
273
- authmethod: mode,
274
- }, signal);
275
- if (body.result !== true) {
276
- const code = asString(body.errorcode);
277
- const message = (body.errors ?? []).map(error => error?.message?.trim()).filter(Boolean).join(' ')
278
- || `${meta.title} could not be checked.`;
279
- if (message === CONNECTION_NOT_CLEARED)
280
- return errorResult(new Error(message));
281
- const parts = [code ? `${message} (${code})` : message];
282
- if (code === 'direct_token_missing') {
283
- parts.push(`Save ${requirement.fields.map(field => field.field).join(', ')} with set_agent_credentials first.`);
284
- }
285
- else if (connectedBefore) {
286
- parts.push('Connect again to restore the connection.');
287
- }
288
- // An error result reads as nothing done, so it says what the check still did.
289
- if (modeSaved)
290
- parts.push(`The mode is saved as ${mode}.`);
291
- // Wiro restarts a running agent after a failed check only when the check cleared a connection that read
292
- // connected before it, and says so in restart. Saving the mode restarts it only when the service read
293
- // connected. An answer without restart, from an older Wiro API, goes by the saved mode and the code.
294
- const restart = asString(body.restart);
295
- const restarts = restart === undefined
296
- ? modeSaved || Boolean(code)
297
- : restart === 'scheduled' || (modeSaved && connectedBefore);
298
- if (restarts && isAgentRunning(agentStatusOf(row))) {
299
- parts.push('The running agent restarts, which takes about a minute.');
300
- }
301
- return errorResult(new Error(parts.join(' ')));
302
- }
303
- const candidates = toAccountRefs(body.accounts, oauth.picker);
304
- if (oauth.picker && candidates.length > 0) {
305
- // Wiro keeps this list 15 minutes, only for the person who ran the check, and saves only accounts from it.
306
- return result('connect', context, 'pick_accounts', `${meta.title} accepted the ${oauth.directProbe.label ?? 'credentials'}. Choose which of these accounts the agent should use. Save the choice within 15 minutes; after that, connect again.`, {
307
- mode,
308
- candidates,
309
- nextAction: {
310
- tool: 'connect_agent_oauth',
311
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, accounts: candidates },
312
- reason: candidates.length === 1
313
- ? 'Save the only available account.'
314
- : 'Ask the user which accounts to use, then save only those.',
315
- },
316
- }, ['', ...candidates.map(account => `- ${accountLabel(account)}`)]);
317
- }
318
- return result('connect', context, 'connected', `${meta.title} is connected. A running agent restarts to use it.`, { mode });
319
- }
320
- const redirectUrl = input.redirectUrl?.trim() || dashboardAgentUrl(agentGuid, apiBase);
321
- if (!isAllowedRedirectUrl(redirectUrl, agentGuid, apiBase)) {
322
- return errorResult(new Error(`redirect_url can only be the agent's page in the Wiro dashboard (${dashboardAgentUrl(agentGuid, apiBase)}) or a local address on the user's own machine (http://localhost or http://127.0.0.1, any port). Leave it out to use the dashboard page.`));
323
- }
324
- const since = before?.connectedAt ?? '';
325
- const answer = await client.post('/UserAgentOAuth/OAuthConnect', {
326
- useragentguid: agentGuid,
327
- credentialkey: credential,
328
- authmethod: mode,
329
- redirecturl: redirectUrl,
330
- }, signal);
331
- if (answer.result !== true && appKeys.length > 0 && /credentials not configured/i.test(apiErrorMessage(answer, ''))) {
332
- // What the sign-in removes may be gone already, so this answer goes by a fresh read.
333
- const fresh = removed.length > 0 ? await readUserAgent(client, agentGuid, signal).catch(() => null) : null;
334
- const groupNow = fresh ? credentialGroup(fresh, credential) : group;
335
- const gone = removed.filter(field => !isFilledValue(groupNow?.[field.key]));
336
- const goneText = gone.length > 0
337
- ? ` The sign-in did not start, and this call removed the saved ${gone.map(field => field.label).join(', ')}${connectedBefore && groupNow?._connected !== true ? `, so ${meta.title} is no longer connected` : ''}. To go back to it, save it again with set_agent_credentials.`
338
- : '';
339
- return result('connect', context, 'setup_needed', `Mode ${mode} needs these saved first with set_agent_credentials: ${appKeys.map(field => `${field.label} (${field.field})`).join(', ')}. ${requirement.note}${goneText}`, { ...setupExtra, connectionModes: connectionModeRequirements(meta, groupNow, modeContext(before, apiBase)), mode, nextAction: describeAction });
340
- }
341
- const body = requireApiSuccess(answer, `Could not start the ${meta.title} sign-in.`);
342
- const authorizeUrl = asString(body.authorizeUrl);
343
- if (!authorizeUrl)
344
- throw new Error(`Wiro did not return a sign-in link for ${meta.title}.`);
345
- const usesDashboard = !/^http:/i.test(redirectUrl);
346
- const after = usesDashboard
347
- ? `After approving, the browser returns to the agent's page in the Wiro dashboard.${oauth.picker ? ' Then status lists the accounts the sign-in found, to choose from within 15 minutes.' : ''}`
348
- : `After approving, the browser goes to ${redirectUrl}.`;
349
- const turnsOn = entriesTurnedOnBy(row, credential);
350
- const titles = await skillTitles(client, [...turnsOn.paused, ...turnsOn.waiting].flatMap(task => task.groups.flat()), signal);
351
- return result('connect', context, 'authorize_in_browser', `The user must open this link in their own browser and approve access. It works for ${OAUTH_LINK_TTL_SECONDS / 60} minutes. ${after}${turnsOnNote(turnsOn, context, titles, isAgentRunning(agentStatusOf(row)))} Give the link to the user and check the status once they say they are done.`, {
352
- mode,
353
- authorizeUrl,
354
- expiresInSeconds: OAUTH_LINK_TTL_SECONDS,
355
- redirectUrl,
356
- nextAction: {
357
- tool: 'connect_agent_oauth',
358
- arguments: {
359
- action: 'status',
360
- agent_guid: agentGuid,
361
- credential,
362
- since_connected_at: since,
363
- wait_seconds: DEFAULT_WAIT_SECONDS,
364
- },
365
- reason: 'After the user has approved access, check that the connection finished.',
366
- },
367
- }, ['', authorizeUrl]);
368
- }
369
- /**
370
- * What to do about access that reads as expired. A start is offered only when one can
371
- * happen. Without the agent's row the offer stays: control_agent reads the agent again
372
- * and says what comes first.
373
- */
374
- function expiredAdvice(row) {
375
- const startOrConnect = 'Start the agent with control_agent, or connect again.';
376
- if (!row)
377
- return startOrConnect;
378
- const agent = toAgentDetail(row);
379
- if ((agent.status === 0 || agent.status === 5) && !startNeedsPlan(agent))
380
- return startOrConnect;
381
- return agent.status === 3 || agent.status === 4
382
- ? 'If the agent cannot use it, connect again.'
383
- : `Connect again if the agent needs it. ${readStatusAdvice(agent)}`;
384
- }
385
- function statusMessage(state, meta, snapshot, unusedNote, row) {
386
- const saved = row !== null && credentialGroup(row, meta.key)?._connected === true;
387
- const next = meta.oauth?.picker?.next;
388
- switch (state) {
389
- case 'connected': {
390
- const optionalStep = next && snapshot.childStep && !snapshot.childStep.configured
391
- ? ` Optionally, choose ${next.label} with action select_accounts and picker "${next.key}".`
392
- : '';
393
- return `${meta.title} is connected${snapshot.accounts.length > 0 ? ` for ${accountsLine(snapshot.accounts)}` : ''}.${optionalStep}`;
394
- }
395
- case 'pick_accounts':
396
- if (ownCandidates(snapshot).length > 0) {
397
- return 'The user approved access. Ask which of these accounts the agent should use, then save them with '
398
- + 'select_accounts within 15 minutes. If the agent\'s page in the Wiro dashboard is open, it offers the same list.';
399
- }
400
- // Wiro keeps the list 15 minutes, only for the person who started the sign-in, so here it is gone or someone else's.
401
- return snapshot.flow && !snapshot.flow.mine
402
- ? `The ${meta.title} sign-in finished, but another admin of this agent's team started a newer one, so the account list goes only to them. Connect again to choose the accounts yourself.`
403
- : `The ${meta.title} sign-in finished, but its account list is no longer kept: Wiro keeps it 15 minutes, only for the person who started the sign-in. Connect again to choose the accounts.`;
404
- case 'pick_child_items':
405
- return `Access is approved, but ${next?.label ?? 'the second step'} still has to be chosen for each account. Call select_accounts with picker "${next?.key ?? ''}" to list them.`;
406
- case 'waiting_for_user':
407
- return `The ${meta.title} sign-in has not finished yet. The link from connect works for ${OAUTH_LINK_TTL_SECONDS / 60} minutes; after that, connect again.`;
408
- case 'token_expired':
409
- return `The saved ${meta.title} access has expired.${saved ? ` The connection is still saved, so get_my_agent lists ${meta.title} as connected.` : ''} ${unusedNote ?? expiredAdvice(row)}`;
410
- default: {
411
- const failed = ownFailedFlow(snapshot);
412
- if (failed) {
413
- return `The latest ${meta.title} connection attempt did not finish${failed.errorCode ? ` (${failed.errorCode})` : ''}.`
414
- + `${saved ? ` The ${meta.title} connection saved before it is still there, so get_my_agent lists it as connected.` : ''}`
415
- + ` ${unusedNote ?? 'Connect again with action connect.'}`;
416
- }
417
- return saved
418
- ? `This check found no current ${meta.title} sign-in, but a ${meta.title} connection is saved on this agent, so get_my_agent lists it as connected. ${unusedNote ?? 'If the agent cannot use it, connect again: that replaces the saved connection and asks for confirm: true.'}`
419
- : `${meta.title} is not connected. ${unusedNote ?? 'Start with action connect.'}`;
420
- }
421
- }
422
- }
423
- async function status(context, input, extra) {
424
- const { client, agentGuid, credential, meta, signal } = context;
425
- const picker = meta.oauth?.picker ?? null;
426
- const stateOf = (snapshot) => connectionState(snapshot, { hasPicker: picker !== null, since: input.since });
427
- const polled = await pollUntil({
428
- read: readSignal => readOAuthStatus(client, agentGuid, credential, picker, readSignal),
429
- // A failed sign-in or token check of this person ends the wait: nothing more comes from it.
430
- isDone: snapshot => DONE_STATES.has(stateOf(snapshot)) || ownFailedFlow(snapshot) !== null,
431
- timeoutMs: input.waitSeconds * 1000,
432
- signal,
433
- interval: () => 5_000,
434
- onPoll: (snapshot, elapsedMs) => reportProgress(extra, elapsedMs, `${meta.title}: ${stateOf(snapshot)}`),
435
- });
436
- const snapshot = polled.value;
437
- if (!snapshot)
438
- throw new Error(`Could not read the ${meta.title} connection status.`);
439
- const state = stateOf(snapshot);
440
- const candidates = state === 'pick_accounts' ? ownCandidates(snapshot) : [];
441
- let nextAction;
442
- let unusedNote = null;
443
- let row = null;
444
- if (state === 'pick_accounts') {
445
- nextAction = candidates.length > 0
446
- ? {
447
- tool: 'connect_agent_oauth',
448
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, accounts: candidates },
449
- reason: candidates.length === 1
450
- ? 'Save the only available account.'
451
- : 'Ask the user which accounts to use, then save only those.',
452
- }
453
- : {
454
- tool: 'connect_agent_oauth',
455
- arguments: { action: 'connect', agent_guid: agentGuid, credential },
456
- reason: `Connect ${meta.title} again for a new account list.`,
457
- };
458
- }
459
- else if (state === 'waiting_for_user') {
460
- nextAction = {
461
- tool: 'connect_agent_oauth',
462
- arguments: {
463
- action: 'status',
464
- agent_guid: agentGuid,
465
- credential,
466
- ...(input.since !== undefined ? { since_connected_at: input.since } : {}),
467
- wait_seconds: DEFAULT_WAIT_SECONDS,
468
- },
469
- reason: 'Keep waiting for the user to finish signing in.',
470
- };
471
- }
472
- else if (state === 'pick_child_items' && picker?.next) {
473
- nextAction = {
474
- tool: 'connect_agent_oauth',
475
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, picker: picker.next.key },
476
- reason: `List the ${picker.next.label} to choose from.`,
477
- };
478
- }
479
- else if (state === 'not_connected' || state === 'token_expired') {
480
- // Only these states offer connect, so only they read the skills. A status is
481
- // still answered when that read fails: connect goes by the rule anyway.
482
- row = await readUserAgent(client, agentGuid, signal).catch(() => null);
483
- unusedNote = row ? await unusedCredentialNote(client, row, credential, meta.title, signal) : null;
484
- if (!unusedNote) {
485
- nextAction = {
486
- tool: 'connect_agent_oauth',
487
- arguments: { action: 'connect', agent_guid: agentGuid, credential },
488
- reason: `Connect ${meta.title}.`,
489
- };
490
- }
491
- }
492
- // Once connected, the scheduled tasks that need this service and still wait for a skill are named, with the
493
- // skills they wait for. A status is still answered when the agent cannot be read.
494
- let pausedNote = '';
495
- if (state === 'connected') {
496
- row = await readUserAgent(client, agentGuid, signal).catch(() => null);
497
- const paused = row
498
- ? customSkillEntries(row).filter(entry => entry.kind === 'scheduled_task' && entry.skillOff
499
- && (entry.requiresCredentials.includes(credential) || (entry.usableCredentials ?? []).includes(credential)))
500
- : [];
501
- pausedNote = skillOffTasksNote(paused, await pausedSkillTitles(client, paused, signal));
502
- }
503
- const childStep = snapshot.childStep
504
- ? { ...snapshot.childStep, label: picker?.next?.label ?? snapshot.childStep.picker }
505
- : undefined;
506
- const setup = setupFromStatus(meta, snapshot);
507
- // Where connect is offered, the message says what is saved for it and the redirect URI the user's own app allows.
508
- const setupNote = (state === 'not_connected' || state === 'token_expired') && setup.text ? ` ${setup.text}` : '';
509
- return result('status', context, state, `${statusMessage(state, meta, snapshot, unusedNote, row)}${setupNote}${pausedNote}`, {
510
- ...(snapshot.connectedAt ? { connectedAt: snapshot.connectedAt } : {}),
511
- ...(snapshot.tokenExpiresAt ? { tokenExpiresAt: snapshot.tokenExpiresAt } : {}),
512
- accounts: snapshot.accounts,
513
- ...(candidates.length > 0 ? { candidates } : {}),
514
- ...(childStep ? { childStep } : {}),
515
- ...setup.extra,
516
- ...(nextAction ? { nextAction } : {}),
517
- }, candidates.length > 0 ? ['', ...candidates.map(account => `- ${accountLabel(account)}`)] : []);
518
- }
519
- /**
520
- * What Wiro's status says about the setup the connection modes need: that the keys of the user's own app are saved
521
- * (only a yes is kept; see parseOAuthStatus), whether the token is, and the redirect URI to allow in that app. An
522
- * older Wiro API says none of it.
523
- */
524
- function setupFromStatus(meta, snapshot) {
525
- const ownMode = meta.connectionModes.includes('own');
526
- const probe = meta.oauth?.directProbe;
527
- const redirect = ownMode ? statusRedirectUri(meta, snapshot.redirectUri) : undefined;
528
- const extra = {
529
- ...(redirect ? { ownAppRedirectUri: redirect } : {}),
530
- ...(ownMode && snapshot.appKeysSaved === true ? { appKeysSaved: true } : {}),
531
- ...(probe && snapshot.tokenSaved !== undefined ? { tokenSaved: snapshot.tokenSaved } : {}),
532
- };
533
- const text = [
534
- savedForModesText(meta, snapshot),
535
- redirect ? `With mode own, the user's own app must allow ${redirect} as a redirect URI.` : '',
536
- ].filter(Boolean).join(' ');
537
- return { extra, text };
538
- }
539
- /** The child step's items as Wiro saved them, under each readable account. */
540
- function savedChildGroups(next, groups, saved) {
541
- const mappings = Array.isArray(saved[next.persistField]) ? saved[next.persistField].filter(isPlainObject) : [];
542
- const savedGroups = groups.filter(group => !group.errorCode).map(group => ({
543
- ...group,
544
- items: mappings
545
- .filter(mapping => asString(mapping[next.parentValueField]) === group.parent.id)
546
- .map(mapping => ({
547
- id: asString(mapping[next.itemValueField]) ?? '',
548
- name: asString(mapping[next.itemLabelField]) ?? '',
549
- })),
550
- }));
551
- return { mappings, savedGroups };
552
- }
553
- function childStepLines(groups) {
554
- return ['', ...groups.flatMap(group => [
555
- `- ${accountLabel(group.parent)}${group.errorCode ? `: could not be read (${group.errorCode})` : ''}`,
556
- ...group.items.map(item => ` - ${accountLabel(item)}`),
557
- ])];
558
- }
559
- function preselected(groups) {
560
- return groups.filter(group => !group.errorCode).map(group => ({ parent: group.parent.id, items: group.items.map(item => item.id) }));
561
- }
562
- /** The extra step alone, for accounts saved before: it lists the items, or saves the ones chosen. */
563
- async function childStepAlone(context, picker, next, selections) {
564
- const { client, agentGuid, credential, signal } = context;
565
- // Discovery runs before every save: the API only accepts items, with their exact labels, from a fresh list.
566
- const discovered = requireApiSuccess(await client.post('/UserAgentOAuth/DiscoverPickerItems', {
567
- useragentguid: agentGuid,
568
- credentialkey: credential,
569
- pickerkey: next.key,
570
- }, signal), `Could not list the ${next.label}.`);
571
- const groups = parseDiscoveredGroups(next, discovered.groups);
572
- if (!selections) {
573
- return result('select_accounts', context, 'pick_child_items', `Choose the ${next.label} to use under each account.${next.optional ? ' This step is optional.' : ''} Then call select_accounts again with picker "${next.key}" and selections.`, {
574
- childStep: childStepOf(picker, groups),
575
- nextAction: {
576
- tool: 'connect_agent_oauth',
577
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, picker: next.key, selections: preselected(groups) },
578
- reason: 'Ask the user which ones to keep; this preselects all of them.',
579
- },
580
- }, childStepLines(groups));
581
- }
582
- const built = buildChainedSelections(next, groups, selections);
583
- if (built.error || !built.selections)
584
- return errorResult(new Error(built.error ?? 'Nothing to save.'));
585
- const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
586
- useragentguid: agentGuid,
587
- credentialkey: credential,
588
- pickerkey: next.key,
589
- selections: built.selections,
590
- }, signal), `Could not save the ${next.label}.`);
591
- const { mappings, savedGroups } = savedChildGroups(next, groups, saved);
592
- const skipped = built.skippedParents.length > 0
593
- ? ` Nothing was chosen for ${accountsLine(built.skippedParents)}.`
594
- : '';
595
- return result('select_accounts', context, 'connected', `Saved the ${next.label} selection (${mappings.length} selected).${skipped} A running agent restarts to use it.`, { childStep: { ...childStepOf(picker, savedGroups, mappings.length > 0) } });
596
- }
597
- /**
598
- * The id of this person's latest sign-in or token check, or empty. Wiro keeps the extra step it lists for the
599
- * accounts of that flow, so the listing and the save both name it. Without it, Wiro goes by its current flow alone.
600
- */
601
- async function ownFlowId({ client, agentGuid, credential, signal }, picker) {
602
- const snapshot = await readOAuthStatus(client, agentGuid, credential, picker, signal).catch(() => null);
603
- return snapshot?.flow?.mine ? snapshot.flow.flowId : '';
604
- }
605
- /**
606
- * Accounts from the list a sign-in or token check gave, with the extra step some providers have. Wiro lists that
607
- * step for the chosen accounts before they are saved, so the accounts and the step are saved in one call and a
608
- * running agent restarts once.
609
- */
610
- async function accountsWithChildStep(context, picker, next, accounts, ids, selections) {
611
- const { client, agentGuid, credential, signal } = context;
612
- if (next.maxParents !== undefined && ids.length > next.maxParents) {
613
- const most = `${next.maxParents} account${next.maxParents === 1 ? '' : 's'}`;
614
- return errorResult(new Error(`Choose at most ${most} to go on: Wiro lists the ${next.label} for at most ${most} at once.`));
615
- }
616
- const flowId = await ownFlowId(context, picker);
617
- const flow = flowId ? { flowid: flowId } : {};
618
- const discovered = requireApiSuccess(await client.post('/UserAgentOAuth/DiscoverPickerItems', {
619
- useragentguid: agentGuid,
620
- credentialkey: credential,
621
- pickerkey: next.key,
622
- parents: ids,
623
- ...flow,
624
- }, signal), `Could not list the ${next.label}.`);
625
- const groups = parseDiscoveredGroups(next, discovered.groups);
626
- if (!selections) {
627
- return result('select_accounts', context, 'pick_child_items', `Nothing is saved yet. Choose the ${next.label} to use under each account.${next.optional ? ` This step is optional: empty selections save the accounts without any ${next.label}.` : ''} Then call select_accounts again with these accounts, picker "${next.key}" and selections within 15 minutes of the sign-in or token check: it saves both at once, so a running agent restarts only once.`, {
628
- childStep: childStepOf(picker, groups),
629
- nextAction: {
630
- tool: 'connect_agent_oauth',
631
- arguments: { action: 'select_accounts', agent_guid: agentGuid, credential, accounts, picker: next.key, selections: preselected(groups) },
632
- reason: 'Ask the user which ones to keep; this preselects all of them.',
633
- },
634
- }, childStepLines(groups));
635
- }
636
- const built = buildChainedSelections(next, groups, selections);
637
- if (built.error || !built.selections)
638
- return errorResult(new Error(built.error ?? 'Nothing to save.'));
639
- const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
640
- useragentguid: agentGuid,
641
- credentialkey: credential,
642
- ...flow,
643
- accountids: ids,
644
- pickerkey: next.key,
645
- selections: built.selections.map(selection => ({
646
- parentvalue: selection.parentvalue,
647
- itemids: selection.items.map(item => item[next.itemValueField]),
648
- })),
649
- }, signal), 'Could not save the accounts.');
650
- const savedAccounts = toAccountRefs(saved.accounts, picker);
651
- const { mappings, savedGroups } = savedChildGroups(next, groups, saved);
652
- const skipped = built.skippedParents.length > 0
653
- ? ` Nothing was chosen for ${accountsLine(built.skippedParents)}.`
654
- : '';
655
- return result('select_accounts', context, 'connected', `Saved ${savedAccounts.length} account${savedAccounts.length === 1 ? '' : 's'}: ${accountsLine(savedAccounts)}, and the ${next.label} selection (${mappings.length} selected).${skipped} A running agent restarts once to use them.`, { accounts: savedAccounts, childStep: { ...childStepOf(picker, savedGroups, mappings.length > 0) } });
656
- }
657
- async function selectAccounts(context, input) {
658
- const { client, agentGuid, credential, meta, signal } = context;
659
- const picker = meta.oauth?.picker ?? null;
660
- if (!picker) {
661
- return errorResult(new Error(`${meta.title} has no account choice to make; its connection is complete once connected.`));
662
- }
663
- const next = picker.next;
664
- if (input.picker && (!next || next.key !== input.picker)) {
665
- return errorResult(new Error(`${meta.title} has no step "${input.picker}".${next ? ` Its extra step is "${next.key}".` : ''}`));
666
- }
667
- const accounts = input.accounts ?? [];
668
- if (next && input.picker && accounts.length === 0)
669
- return childStepAlone(context, picker, next, input.selections);
670
- if (accounts.length === 0) {
671
- return errorResult(new Error('Pass accounts (each {id, name}) to save, or picker to run the extra step.'));
672
- }
673
- const picked = pickedAccountIds(picker, accounts);
674
- if (picked.error || !picked.ids)
675
- return errorResult(new Error(picked.error ?? 'Nothing to save.'));
676
- if (next)
677
- return accountsWithChildStep(context, picker, next, accounts, picked.ids, input.selections);
678
- const saved = requireApiSuccess(await client.post('/UserAgentOAuth/SetPickerAccounts', {
679
- useragentguid: agentGuid,
680
- credentialkey: credential,
681
- accountids: picked.ids,
682
- }, signal), 'Could not save the accounts.');
683
- const savedAccounts = toAccountRefs(saved.accounts, picker);
684
- return result('select_accounts', context, 'connected', `Saved ${savedAccounts.length} account${savedAccounts.length === 1 ? '' : 's'}: ${accountsLine(savedAccounts)}. A running agent restarts to use the account${savedAccounts.length === 1 ? '' : 's'}.`, { accounts: savedAccounts });
685
- }
686
- export function registerConnectAgentOauth(server, client) {
687
- server.registerTool('connect_agent_oauth', {
688
- title: 'Connect an agent integration',
689
- description: 'Connect an outside account (Google Ads, GA4, YouTube, Google Business, '
690
- + 'Merchant Center, Meta Ads, Instagram, Facebook Pages, TikTok, LinkedIn, X, HubSpot, '
691
- + 'Mailchimp, Reddit, Shopify) to a deployed agent, with a sign-in link or a saved token, as list_agent_skills '
692
- + 'shows for each service. action connect: with Wiro\'s own app '
693
- + '(mode wiro) or the user\'s own app (mode own) it returns a sign-in link that the user '
694
- + 'must open in their own browser and approve within 15 minutes; never open it for them. '
695
- + 'With mode api_key it checks a token saved earlier with set_agent_credentials and returns '
696
- + 'the accounts it can use, with no browser. Without mode the tool picks the one that '
697
- + 'works; when a provider needs the user\'s own app keys or a token first, it says which to '
698
- + 'save. action status: whether the sign-in finished (wait_seconds waits for '
699
- + 'the user) and, once it did, lists the accounts to choose from. action select_accounts: saves which accounts the agent uses ({id, name} from '
700
- + 'the list connect or status gave). Where a provider has an extra step (Meta Ads pages, Google Business locations), '
701
- + 'it first lists that step for the chosen accounts and saves nothing, then saves the accounts and the selections '
702
- + 'in one call, so a running agent restarts once; picker without accounts changes the extra step of accounts saved '
703
- + 'before. Connecting again replaces an existing connection, and a sign-in removes a token saved for another mode; both need '
704
- + 'confirm: true. A running agent restarts when a connection or selection is saved. Connecting a service '
705
- + 'turns on the scheduled tasks that need it, and the result names any that stay paused until a skill they need is on; '
706
- + 'turn off any you do not want. '
707
- + 'Remove a connection with disconnect_agent_oauth. A credential that none of the agent\'s active '
708
- + 'skills use, that no custom skill or scheduled task of the agent requires, and that its setup does not wait for, is refused before any link is made (get_my_agent '
709
- + 'lists the skills; apply_agent_skills turns one on). The person who deployed the agent or a team admin of its '
710
- + 'team can connect; the account list after a sign-in goes only to the person who started it. The agents playbook (get_playbook) has the '
711
- + 'full setup walkthrough.',
712
- inputSchema: strictInput({
713
- action: z.enum(['connect', 'status', 'select_accounts']).default('connect')
714
- .describe('connect (default) starts a connection, status checks it, select_accounts saves the accounts to use.'),
715
- agent_guid: z.string().min(1).describe('The deployed agent\'s guid, from list_my_agents.'),
716
- credential: z.string().min(1)
717
- .describe('The integration\'s credential key, for example "google-ads", "meta-ads", "instagram", "hubspot" or "shopify".'),
718
- mode: z.enum(['wiro', 'own', 'api_key']).optional()
719
- .describe('connect: wiro (Wiro\'s app), own (the user\'s own app, keys saved first) or api_key (a saved token, no browser). Omit to let the tool choose.'),
720
- redirect_url: z.string().max(2_048).optional()
721
- .describe('connect: where the browser goes after sign-in. Defaults to the agent\'s page in the Wiro dashboard, which also handles the account choice. The only other accepted address is a local one on the user\'s own machine (http://localhost or http://127.0.0.1, any port). Keep the default unless the user asks.'),
722
- since_connected_at: z.string().optional()
723
- .describe('status: the since_connected_at value from connect\'s nextAction, so an older connection is not mistaken for the new one.'),
724
- wait_seconds: z.number().int().min(0).max(MAX_WAIT_SECONDS).default(0)
725
- .describe(`status: how long to wait for the sign-in to finish, 0 to ${MAX_WAIT_SECONDS} seconds (default 0, a single check).`),
726
- accounts: z.array(z.record(z.string(), z.union([z.string(), z.number()]))).optional()
727
- .describe('select_accounts: the accounts to use, each {id, name}, from the list connect or status gave. Wiro saves only accounts from that list, for 15 minutes after the sign-in or token check.'),
728
- picker: z.string().optional()
729
- .describe('select_accounts: the extra step\'s key ("pages" for Meta Ads, "locations" for Google Business). With accounts it may be left out. Without accounts it works on the accounts saved before. Without selections it lists the choices.'),
730
- selections: z.array(z.object({
731
- parent: z.string().describe('An account id from the earlier step.'),
732
- items: z.array(z.string()).describe('The ids of the items to use under that account.'),
733
- })).optional()
734
- .describe('select_accounts: what to use under each account in the extra step. With accounts, both are saved in one call. Accounts left out get nothing.'),
735
- confirm: z.boolean().default(false)
736
- .describe('connect: true to replace an existing connection or a token saved for another mode, after the user agreed.'),
737
- }),
738
- outputSchema,
739
- annotations: {
740
- readOnlyHint: false,
741
- destructiveHint: true,
742
- idempotentHint: false,
743
- openWorldHint: true,
744
- },
745
- }, async (args, extra) => {
746
- let meta = null;
747
- try {
748
- const credential = args.credential.trim();
749
- meta = await loadCredentialMeta(client, credential, extra.signal);
750
- if (!meta)
751
- return errorResult(new Error(`Unknown credential "${credential}".`));
752
- if (!meta.oauth) {
753
- return errorResult(new Error(credential === WIRO_PROJECT_CREDENTIAL
754
- ? `${meta.title} is not a sign-in connection. Connect a Wiro project with bind_agent_project, with no key to paste.`
755
- : `${meta.title} is not a sign-in connection. Save its fields with set_agent_credentials (call it with credential "${credential}" to see them).`));
756
- }
757
- const context = { client, agentGuid: args.agent_guid, credential, meta, signal: extra.signal };
758
- if (args.action === 'status') {
759
- return await status(context, { since: args.since_connected_at, waitSeconds: args.wait_seconds }, extra);
760
- }
761
- if (args.action === 'select_accounts') {
762
- return await selectAccounts(context, {
763
- accounts: args.accounts,
764
- picker: args.picker?.trim() || undefined,
765
- selections: args.selections,
766
- });
767
- }
768
- return await connect(context, { mode: args.mode, redirectUrl: args.redirect_url, confirm: args.confirm });
769
- }
770
- catch (error) {
771
- const message = errorText(error);
772
- return errorResult(/not found or unauthorized/i.test(message)
773
- ? new Error(await connectionRefusalText(client, args.agent_guid, message, 'connected', extra.signal))
774
- : withHint(error, meta ?? undefined));
775
- }
776
- });
777
- }
778
- //# sourceMappingURL=connect-agent-oauth.js.map