@dench.com/cli 3.12.26 → 3.12.27

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 (3) hide show
  1. package/dench.ts +33 -37
  2. package/package.json +1 -1
  3. package/tools.ts +457 -75
package/dench.ts CHANGED
@@ -58,7 +58,6 @@ import {
58
58
  import {
59
59
  connectionSource,
60
60
  fetchConnectedAppsSummary,
61
- fetchUnipileConnections,
62
61
  runToolCommand,
63
62
  toolHelp,
64
63
  } from "./tools";
@@ -3039,28 +3038,22 @@ function nextContextCommands() {
3039
3038
  }
3040
3039
 
3041
3040
  async function connectedAppsContext(runtime: Runtime) {
3042
- try {
3043
- const gatewayAuth = await resolveGatewayCommandAuth(
3044
- runtime,
3045
- "dench context",
3046
- );
3047
- return fetchConnectedAppsSummary({
3048
- bearerToken: gatewayAuth.bearerToken,
3049
- gatewayBaseUrl: gatewayAuth.gatewayBaseUrl,
3050
- gatewayHeaders: gatewayAuth.gatewayHeaders,
3051
- ...unipileQueryAuth(runtime),
3052
- });
3053
- } catch (error) {
3054
- const unipile = await fetchUnipileConnections(unipileQueryAuth(runtime));
3055
- return {
3056
- available: false,
3057
- reason: errorMessage(error),
3058
- count: unipile.connections.length,
3059
- connections: unipile.connections,
3060
- nativeAvailable: unipile.available,
3061
- ...(unipile.error ? { nativeError: unipile.error } : {}),
3062
- };
3063
- }
3041
+ return fetchConnectedAppsSummary({
3042
+ resolveGatewayAuth: async () => {
3043
+ try {
3044
+ return await resolveGatewayCommandAuth(runtime, "dench context");
3045
+ } catch (error) {
3046
+ return { gatewayAuthError: gatewayAuthFailureReason(error) };
3047
+ }
3048
+ },
3049
+ ...unipileQueryAuth(runtime),
3050
+ ...(runtime.mode !== "dev"
3051
+ ? {
3052
+ appOrigin: runtime.host,
3053
+ workspaceSlug: runtime.organization?.slug,
3054
+ }
3055
+ : {}),
3056
+ });
3064
3057
  }
3065
3058
 
3066
3059
  async function buildContext(runtime: Runtime) {
@@ -5069,26 +5062,29 @@ async function main() {
5069
5062
  return;
5070
5063
  }
5071
5064
 
5072
- // `dench integrations` — every app connected to this workspace, from BOTH
5073
- // brokers: Composio (via the gateway) and Dench's own Unipile connections
5074
- // for Gmail, Outlook, Calendar and LinkedIn (via Convex). Composio tool
5075
- // search/run/connect stay under `dench tool`.
5065
+ // `dench integrations` — every app connected to this workspace across
5066
+ // Dench's unified `/api/v1/tools/status` surface (falling back to the legacy
5067
+ // gateway + Convex merge on older hosts). Tool search/run/connect stay under
5068
+ // `dench tool`.
5076
5069
  if (command === "integrations") {
5077
5070
  const runtime = await getRuntime();
5078
- let gatewayAuthError: string | undefined;
5079
- const gatewayAuth = await resolveGatewayCommandAuth(
5080
- runtime,
5081
- "dench integrations",
5082
- ).catch((error) => {
5083
- gatewayAuthError = gatewayAuthFailureReason(error);
5084
- return null;
5085
- });
5086
5071
  await runToolCommand({
5087
5072
  args: ["status"],
5088
5073
  jsonOutput: json,
5089
- ...(gatewayAuth ?? {}),
5090
- gatewayAuthError,
5074
+ resolveGatewayAuth: async () => {
5075
+ try {
5076
+ return await resolveGatewayCommandAuth(runtime, "dench integrations");
5077
+ } catch (error) {
5078
+ return { gatewayAuthError: gatewayAuthFailureReason(error) };
5079
+ }
5080
+ },
5091
5081
  ...unipileQueryAuth(runtime),
5082
+ ...(runtime.mode !== "dev"
5083
+ ? {
5084
+ appOrigin: runtime.host,
5085
+ workspaceSlug: runtime.organization?.slug,
5086
+ }
5087
+ : {}),
5092
5088
  });
5093
5089
  return;
5094
5090
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dench.com/cli",
3
- "version": "3.12.26",
3
+ "version": "3.12.27",
4
4
  "description": "Dench agent workspace CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/tools.ts CHANGED
@@ -252,19 +252,7 @@ export async function fetchCustomMcpConnections(
252
252
  }
253
253
  }
254
254
 
255
- /**
256
- * Summarise the user's connected apps for `dench context` and friends.
257
- * Speaks straight to the gateway with either DENCH_API_KEY or a gateway
258
- * key resolved from the active agent session, and merges in the Unipile
259
- * connections Composio never reports.
260
- * Returns the same legacy shape the previous Convex-routed path did so
261
- * existing parsers don't need to change.
262
- */
263
- export async function fetchConnectedAppsSummary(
264
- ctx: GatewayAuthContext &
265
- UnipileAuthContext &
266
- Pick<ToolCliContext, "workspaceSlug"> = {},
267
- ): Promise<{
255
+ export type ConnectedAppsSummary = {
268
256
  available: boolean;
269
257
  count: number;
270
258
  connections: CompactConnection[];
@@ -272,7 +260,82 @@ export async function fetchConnectedAppsSummary(
272
260
  nativeError?: string;
273
261
  error?: string;
274
262
  reason?: string;
275
- }> {
263
+ };
264
+
265
+ /**
266
+ * Summarise the user's connected apps for `dench context` and friends.
267
+ * Prefers Dench's unified `/api/v1/tools/status` endpoint when an authenticated
268
+ * app host is known, and falls back cleanly to the legacy gateway + Convex
269
+ * merge on older deployments or gateway-only callers.
270
+ */
271
+ export async function fetchConnectedAppsSummary(
272
+ ctx: GatewayAuthContext &
273
+ UnipileAuthContext &
274
+ Pick<ToolCliContext, "appOrigin" | "workspaceSlug"> = {},
275
+ ): Promise<ConnectedAppsSummary> {
276
+ const { summary } = await fetchConnectedAppsSummaryInternal(ctx);
277
+ return summary;
278
+ }
279
+
280
+ async function fetchConnectedAppsSummaryInternal(
281
+ ctx: GatewayAuthContext &
282
+ UnipileAuthContext &
283
+ Pick<ToolCliContext, "appOrigin" | "workspaceSlug"> = {},
284
+ ): Promise<{ summary: ConnectedAppsSummary; viaAppApi: boolean }> {
285
+ if (canUseAppApi(ctx)) {
286
+ try {
287
+ const apiRes = await tryCallAppApi(ctx, "GET", "/tools/status");
288
+ if (apiRes.supported) {
289
+ const record = asRecord(apiRes.payload) ?? {};
290
+ const connections = extractConnections(record).map(
291
+ compactAppApiConnection,
292
+ );
293
+ const available = booleanField(record, "available") ?? true;
294
+ const nativeAvailable = booleanField(record, "nativeAvailable") ?? true;
295
+ const nativeError = stringField(record, "nativeError");
296
+ const error = stringField(record, "error");
297
+ const reason = stringField(record, "reason");
298
+ return {
299
+ viaAppApi: true,
300
+ summary: {
301
+ available,
302
+ count: connections.length,
303
+ connections,
304
+ nativeAvailable,
305
+ ...(nativeError ? { nativeError } : {}),
306
+ ...(error ? { error } : {}),
307
+ ...(reason ? { reason } : {}),
308
+ },
309
+ };
310
+ }
311
+ } catch (error) {
312
+ if (error instanceof AppApiHttpError) {
313
+ const [unipile, mcpConnections] = await Promise.all([
314
+ fetchUnipileConnections(ctx),
315
+ fetchCustomMcpConnections(ctx),
316
+ ]);
317
+ const firstPartyConnections = [
318
+ ...unipile.connections,
319
+ ...mcpConnections,
320
+ ];
321
+ return {
322
+ viaAppApi: true,
323
+ summary: {
324
+ available: false,
325
+ count: firstPartyConnections.length,
326
+ connections: firstPartyConnections,
327
+ nativeAvailable: unipile.available,
328
+ ...(unipile.error ? { nativeError: unipile.error } : {}),
329
+ ...(error.status === 401 || error.status === 403
330
+ ? { reason: error.message }
331
+ : { error: error.message }),
332
+ },
333
+ };
334
+ }
335
+ throw error;
336
+ }
337
+ }
338
+
276
339
  const [unipile, mcpConnections] = await Promise.all([
277
340
  fetchUnipileConnections(ctx),
278
341
  fetchCustomMcpConnections(ctx),
@@ -284,30 +347,36 @@ export async function fetchConnectedAppsSummary(
284
347
  const firstPartyConnections = [...unipile.connections, ...mcpConnections];
285
348
  if (ctx.gatewayAuthError) {
286
349
  return {
287
- available: false,
288
- count: firstPartyConnections.length,
289
- connections: firstPartyConnections,
290
- ...unipileFields,
291
- reason: ctx.gatewayAuthError,
350
+ viaAppApi: false,
351
+ summary: {
352
+ available: false,
353
+ count: firstPartyConnections.length,
354
+ connections: firstPartyConnections,
355
+ ...unipileFields,
356
+ reason: ctx.gatewayAuthError,
357
+ },
292
358
  };
293
359
  }
294
360
  let payload: unknown;
295
361
  try {
296
362
  payload = await callGateway(ctx, "GET", "/v1/composio/connections");
297
363
  } catch (error) {
298
- // Composio being unreachable must not hide a connected calendar, so the
299
- // Unipile rows are still reported alongside the failure.
364
+ // Third-party broker being unreachable must not hide a connected calendar,
365
+ // so the native rows are still reported alongside the failure.
300
366
  const failure = {
301
367
  available: false,
302
368
  count: firstPartyConnections.length,
303
369
  connections: firstPartyConnections,
304
370
  ...unipileFields,
305
371
  };
306
- return ctx.gatewayAuthError
307
- ? { ...failure, reason: ctx.gatewayAuthError }
308
- : error instanceof MissingApiKeyError
309
- ? { ...failure, reason: error.message }
310
- : { ...failure, error: errorMessage(error) };
372
+ return {
373
+ viaAppApi: false,
374
+ summary: ctx.gatewayAuthError
375
+ ? { ...failure, reason: ctx.gatewayAuthError }
376
+ : error instanceof MissingApiKeyError
377
+ ? { ...failure, reason: error.message }
378
+ : { ...failure, error: errorMessage(error) },
379
+ };
311
380
  }
312
381
  const connections = [
313
382
  ...extractConnections(payload)
@@ -316,10 +385,13 @@ export async function fetchConnectedAppsSummary(
316
385
  ...firstPartyConnections,
317
386
  ];
318
387
  return {
319
- available: true,
320
- count: connections.length,
321
- connections,
322
- ...unipileFields,
388
+ viaAppApi: false,
389
+ summary: {
390
+ available: true,
391
+ count: connections.length,
392
+ connections,
393
+ ...unipileFields,
394
+ },
323
395
  };
324
396
  }
325
397
 
@@ -337,7 +409,8 @@ async function runStatusSubcommand(ctx: ToolCliContext): Promise<void> {
337
409
  : null;
338
410
  const filterToolkit = unipileToolkit ?? requestedToolkit;
339
411
 
340
- let connectionsSummary: Awaited<ReturnType<typeof fetchConnectedAppsSummary>>;
412
+ let connectionsSummary: ConnectedAppsSummary;
413
+ let viaAppApi = false;
341
414
  if (unipileToolkit) {
342
415
  const unipile = await fetchUnipileConnections(ctx);
343
416
  connectionsSummary = {
@@ -348,10 +421,17 @@ async function runStatusSubcommand(ctx: ToolCliContext): Promise<void> {
348
421
  ...(unipile.error ? { nativeError: unipile.error } : {}),
349
422
  };
350
423
  } else {
351
- connectionsSummary = await fetchConnectedAppsSummary(ctx);
424
+ const result = await fetchConnectedAppsSummaryInternal(ctx);
425
+ connectionsSummary = result.summary;
426
+ viaAppApi = result.viaAppApi;
352
427
  }
353
428
  let toolkitsPayload: unknown = null;
354
- if (filterToolkit && !unipileToolkit && connectionsSummary.available) {
429
+ if (
430
+ filterToolkit &&
431
+ !unipileToolkit &&
432
+ !viaAppApi &&
433
+ connectionsSummary.available
434
+ ) {
355
435
  const search = encodeURIComponent(filterToolkit);
356
436
  toolkitsPayload = await callGateway(
357
437
  ctx,
@@ -423,6 +503,44 @@ async function runSearchSubcommand(ctx: ToolCliContext): Promise<void> {
423
503
  );
424
504
  }
425
505
 
506
+ if (!ownedToolkit && canUseAppApi(ctx)) {
507
+ const apiBody: Record<string, unknown> = { query };
508
+ if (toolkit) apiBody.toolkit = toolkit;
509
+ if (limit) apiBody.limit = limit;
510
+ const apiRes = await tryCallAppApi(ctx, "POST", "/tools/search", apiBody);
511
+ if (apiRes.supported) {
512
+ const record = asRecord(apiRes.payload) ?? {};
513
+ const items = extractSearchItems(record).slice(0, limit ?? 100);
514
+ const connectedToolkits = new Set<string>(connectedToolkitSet(record));
515
+ for (const item of items) {
516
+ if (booleanField(asRecord(item.connection_status), "is_connected")) {
517
+ const slug =
518
+ stringField(item, "toolkit_slug") ??
519
+ stringField(asRecord(item.toolkit), "slug");
520
+ if (slug && !nativeToolkit(slug)) {
521
+ connectedToolkits.add(slug.toLowerCase());
522
+ }
523
+ }
524
+ }
525
+ const merged = {
526
+ query,
527
+ items,
528
+ connected_toolkits: [...connectedToolkits],
529
+ nativeAvailable: booleanField(record, "nativeAvailable") ?? true,
530
+ ...(stringField(record, "nativeError")
531
+ ? { nativeError: stringField(record, "nativeError") }
532
+ : {}),
533
+ ...(toolkit ? { toolkit } : {}),
534
+ };
535
+ if (ctx.jsonOutput) {
536
+ console.log(JSON.stringify(merged, null, 2));
537
+ return;
538
+ }
539
+ console.log(formatSearchResult(merged, compact));
540
+ return;
541
+ }
542
+ }
543
+
426
544
  const body: Record<string, unknown> = { query };
427
545
  if (toolkit) body.toolkit_slug = toolkit;
428
546
  if (limit) body.limit = limit;
@@ -630,14 +748,29 @@ async function runRunSubcommand(ctx: ToolCliContext): Promise<void> {
630
748
 
631
749
  let payload: unknown;
632
750
  try {
633
- payload = await callGateway(
634
- ctx,
635
- "POST",
636
- "/v1/composio/tools/execute",
637
- body,
638
- );
751
+ let handledViaAppApi = false;
752
+ if (canUseAppApi(ctx)) {
753
+ const apiRes = await tryCallAppApi(ctx, "POST", "/tools/run", body);
754
+ if (apiRes.supported) {
755
+ payload = apiRes.payload;
756
+ handledViaAppApi = true;
757
+ }
758
+ }
759
+ if (!handledViaAppApi) {
760
+ payload = await callGateway(
761
+ ctx,
762
+ "POST",
763
+ "/v1/composio/tools/execute",
764
+ body,
765
+ );
766
+ }
639
767
  } catch (error) {
640
- if (!(error instanceof GatewayHttpError)) throw error;
768
+ if (
769
+ !(error instanceof GatewayHttpError) &&
770
+ !(error instanceof AppApiHttpError)
771
+ ) {
772
+ throw error;
773
+ }
641
774
  // Ambiguity is the opposite of a missing connection, and it has to be
642
775
  // checked first: the gateway reports it with a 400 whose body also trips
643
776
  // the no-connection hints, which would send the caller off to add a third
@@ -819,8 +952,63 @@ async function runConnectSubcommand(ctx: ToolCliContext): Promise<void> {
819
952
  }
820
953
  return;
821
954
  }
955
+ const explicitCallbackUrl = getFlag(ctx.args, "--callback-url");
956
+ if (canUseAppApi(ctx)) {
957
+ const apiRes = await tryCallAppApi(ctx, "POST", "/tools/connections", {
958
+ toolkit,
959
+ ...(explicitCallbackUrl ? { callback_url: explicitCallbackUrl } : {}),
960
+ });
961
+ if (apiRes.supported) {
962
+ const record = asRecord(apiRes.payload);
963
+ const resolvedToolkit = stringField(record, "toolkit") ?? toolkit;
964
+ const redirectUrl =
965
+ stringField(record, "redirectUrl", "redirect_url", "url", "link") ??
966
+ stringField(
967
+ asRecord(record?.data),
968
+ "redirectUrl",
969
+ "redirect_url",
970
+ "url",
971
+ "link",
972
+ );
973
+ const summary = {
974
+ ok: true,
975
+ ...(stringField(record, "source")
976
+ ? { source: stringField(record, "source") }
977
+ : {}),
978
+ toolkit: resolvedToolkit,
979
+ ...(explicitCallbackUrl ? { callbackUrl: explicitCallbackUrl } : {}),
980
+ redirectUrl: redirectUrl ?? null,
981
+ ...(stringField(record, "expiresAt")
982
+ ? { expiresAt: stringField(record, "expiresAt") }
983
+ : {}),
984
+ connectionId:
985
+ stringField(record, "connection_id", "connectionId") ??
986
+ stringField(
987
+ asRecord(record?.data),
988
+ "connection_id",
989
+ "connectionId",
990
+ ) ??
991
+ null,
992
+ ...(redirectUrl
993
+ ? { message: `Connect ${resolvedToolkit} here: ${redirectUrl}` }
994
+ : {}),
995
+ raw: apiRes.payload,
996
+ };
997
+ if (ctx.jsonOutput) {
998
+ console.log(JSON.stringify(summary, null, 2));
999
+ return;
1000
+ }
1001
+ if (redirectUrl) {
1002
+ console.log(`Connect ${resolvedToolkit} here: ${redirectUrl}`);
1003
+ return;
1004
+ }
1005
+ console.log(JSON.stringify(apiRes.payload, null, 2));
1006
+ return;
1007
+ }
1008
+ }
1009
+
822
1010
  const callbackUrl =
823
- getFlag(ctx.args, "--callback-url") ??
1011
+ explicitCallbackUrl ??
824
1012
  process.env.DENCH_OAUTH_CALLBACK_URL?.trim() ??
825
1013
  `${resolveAppPublicOrigin()}/api/composio/callback`;
826
1014
 
@@ -868,17 +1056,40 @@ async function runDisconnectSubcommand(ctx: ToolCliContext): Promise<void> {
868
1056
  }
869
1057
  ctx.args.shift();
870
1058
 
871
- const path = `/v1/composio/connections/${encodeURIComponent(connectionId)}`;
872
1059
  let payload: unknown = { ok: true, deleted: true };
873
- try {
874
- payload = await callGateway(ctx, "DELETE", path);
875
- } catch (error) {
876
- // Composio returns 404 for connections that are already gone — surface
877
- // that as a soft success so callers can keep their local state in sync.
878
- if (error instanceof GatewayHttpError && error.status === 404) {
879
- payload = { ok: true, deleted: true, alreadyGone: true };
880
- } else {
881
- throw error;
1060
+ let handledViaAppApi = false;
1061
+ if (canUseAppApi(ctx)) {
1062
+ try {
1063
+ const apiRes = await tryCallAppApi(
1064
+ ctx,
1065
+ "DELETE",
1066
+ `/tools/connections/${encodeURIComponent(connectionId)}`,
1067
+ );
1068
+ if (apiRes.supported) {
1069
+ payload = apiRes.payload ?? { ok: true, deleted: true };
1070
+ handledViaAppApi = true;
1071
+ }
1072
+ } catch (error) {
1073
+ if (error instanceof AppApiHttpError && error.status === 404) {
1074
+ payload = { ok: true, deleted: true, alreadyGone: true };
1075
+ handledViaAppApi = true;
1076
+ } else {
1077
+ throw error;
1078
+ }
1079
+ }
1080
+ }
1081
+ if (!handledViaAppApi) {
1082
+ const path = `/v1/composio/connections/${encodeURIComponent(connectionId)}`;
1083
+ try {
1084
+ payload = await callGateway(ctx, "DELETE", path);
1085
+ } catch (error) {
1086
+ // Return 404 for connections that are already gone as a soft success
1087
+ // so callers can keep their local state in sync.
1088
+ if (error instanceof GatewayHttpError && error.status === 404) {
1089
+ payload = { ok: true, deleted: true, alreadyGone: true };
1090
+ } else {
1091
+ throw error;
1092
+ }
882
1093
  }
883
1094
  }
884
1095
 
@@ -931,6 +1142,102 @@ class GatewayHttpError extends ToolCliError {
931
1142
  }
932
1143
  }
933
1144
 
1145
+ class AppApiHttpError extends ToolCliError {
1146
+ status: number;
1147
+ body: string;
1148
+ path: string;
1149
+ code?: string;
1150
+ apiMessage?: string;
1151
+
1152
+ constructor(args: {
1153
+ status: number;
1154
+ body: string;
1155
+ path: string;
1156
+ code?: string;
1157
+ apiMessage?: string;
1158
+ }) {
1159
+ const detail =
1160
+ args.apiMessage ||
1161
+ (args.body.length > 500 ? `${args.body.slice(0, 500)}…` : args.body);
1162
+ super(`Dench API error (${args.status}): ${detail || "(empty)"}`);
1163
+ this.name = "AppApiHttpError";
1164
+ this.status = args.status;
1165
+ this.body = args.body;
1166
+ this.path = args.path;
1167
+ this.code = args.code;
1168
+ this.apiMessage = args.apiMessage;
1169
+ }
1170
+ }
1171
+
1172
+ type ToolHttpError = GatewayHttpError | AppApiHttpError;
1173
+
1174
+ function canUseAppApi(
1175
+ ctx: Pick<ToolCliContext, "appOrigin" | "sessionToken">,
1176
+ ): boolean {
1177
+ return Boolean(ctx.appOrigin?.trim() && ctx.sessionToken?.trim());
1178
+ }
1179
+
1180
+ /**
1181
+ * True when a 404 response means the host does not serve `/api/v1/tools/*` at
1182
+ * all (older deployment or gateway-only test stub), as opposed to a live
1183
+ * `/api/v1` handler reporting a domain 404 ("Action X was not found", "That app
1184
+ * is not available in Integrations.", "Connection not found.").
1185
+ */
1186
+ function isMissingAppApiRoute(status: number, body: string): boolean {
1187
+ if (status !== 404) return false;
1188
+ const parsed = asRecord(parseJsonOrUndefined(body));
1189
+ const errObj = asRecord(parsed?.error);
1190
+ if (!errObj) return true;
1191
+ const message = stringField(errObj, "message") ?? "";
1192
+ return /^No API v1 operation\b/i.test(message);
1193
+ }
1194
+
1195
+ async function tryCallAppApi(
1196
+ ctx: Pick<ToolCliContext, "appOrigin" | "sessionToken">,
1197
+ method: "GET" | "POST" | "DELETE",
1198
+ path: string,
1199
+ body?: Record<string, unknown>,
1200
+ ): Promise<{ supported: false } | { supported: true; payload: unknown }> {
1201
+ const origin = stripTrailingSlashes(ctx.appOrigin?.trim() ?? "");
1202
+ const token = ctx.sessionToken?.trim() ?? "";
1203
+ if (!origin || !token) return { supported: false };
1204
+
1205
+ const init: RequestInit = {
1206
+ method,
1207
+ headers: {
1208
+ accept: "application/json",
1209
+ "content-type": "application/json",
1210
+ authorization: `Bearer ${token}`,
1211
+ },
1212
+ };
1213
+ if (body !== undefined) init.body = JSON.stringify(body);
1214
+ const response = await fetch(`${origin}/api/v1${path}`, init);
1215
+ if (!response.ok) {
1216
+ const detail = await response.text().catch(() => "");
1217
+ if (isMissingAppApiRoute(response.status, detail)) {
1218
+ return { supported: false };
1219
+ }
1220
+ const parsed = asRecord(parseJsonOrUndefined(detail));
1221
+ const errObj = asRecord(parsed?.error);
1222
+ const apiMessage =
1223
+ stringField(errObj, "message") ?? stringField(parsed, "error", "message");
1224
+ const code = stringField(errObj, "code") ?? stringField(parsed, "code");
1225
+ throw new AppApiHttpError({
1226
+ status: response.status,
1227
+ body: detail,
1228
+ path,
1229
+ code,
1230
+ apiMessage,
1231
+ });
1232
+ }
1233
+ if (response.status === 204) return { supported: true, payload: null };
1234
+ const contentType = response.headers.get("content-type") ?? "";
1235
+ if (!contentType.includes("application/json")) {
1236
+ return { supported: true, payload: await response.text() };
1237
+ }
1238
+ return { supported: true, payload: await response.json() };
1239
+ }
1240
+
934
1241
  function resolveGatewayBaseUrl(
935
1242
  ctx?: Pick<ToolCliContext, "gatewayBaseUrl">,
936
1243
  ): string {
@@ -1017,6 +1324,7 @@ async function callGateway(
1017
1324
  // ---------------------------------------------------------------------------
1018
1325
 
1019
1326
  const ACCOUNT_SELECTION_CODE = "composio_account_selection_required";
1327
+ const MULTIPLE_ACCOUNTS_HINT = "multiple accounts are connected for ";
1020
1328
 
1021
1329
  const NO_CONNECTION_HINTS = [
1022
1330
  "no active connection",
@@ -1027,19 +1335,24 @@ const NO_CONNECTION_HINTS = [
1027
1335
  "account does not exist",
1028
1336
  "connection has been disabled",
1029
1337
  "connection is disabled",
1338
+ "in integrations before running this action",
1030
1339
  ];
1031
1340
 
1032
- function isLikelyNoConnection(error: GatewayHttpError): boolean {
1033
- if (![400, 404, 422].includes(error.status)) return false;
1341
+ function isLikelyNoConnection(error: ToolHttpError): boolean {
1342
+ if (![400, 404, 409, 422].includes(error.status)) return false;
1034
1343
  const lower = error.body.toLowerCase();
1035
1344
  return NO_CONNECTION_HINTS.some((hint) => lower.includes(hint));
1036
1345
  }
1037
1346
 
1038
- function isAccountSelectionRequired(error: GatewayHttpError): boolean {
1039
- return error.body.toLowerCase().includes(ACCOUNT_SELECTION_CODE);
1347
+ function isAccountSelectionRequired(error: ToolHttpError): boolean {
1348
+ const lower = error.body.toLowerCase();
1349
+ return (
1350
+ lower.includes(ACCOUNT_SELECTION_CODE) ||
1351
+ lower.includes(MULTIPLE_ACCOUNTS_HINT)
1352
+ );
1040
1353
  }
1041
1354
 
1042
- function accountSelectionPayload(toolSlug: string, error: GatewayHttpError) {
1355
+ function accountSelectionPayload(toolSlug: string, error: ToolHttpError) {
1043
1356
  const accounts = accountChoices(error.body);
1044
1357
  return {
1045
1358
  ok: false,
@@ -1060,28 +1373,39 @@ function accountSelectionPayload(toolSlug: string, error: GatewayHttpError) {
1060
1373
  }
1061
1374
 
1062
1375
  /**
1063
- * The candidate accounts named in an account-selection error. The gateway
1064
- * already lists them, so parse them back out rather than spending a round trip
1065
- * re-listing connections the caller was just handed.
1066
- *
1067
- * They arrive as a JSON array inside the JSON-encoded error message, so decode
1068
- * the body first: that hands the array back unescaped instead of leaving us to
1069
- * undo the escaping by hand.
1376
+ * The candidate accounts named in an account-selection error. Both the legacy
1377
+ * gateway (JSON array inside the error message) and Dench's `/api/v1/tools/run`
1378
+ * (`Pass connected_account_id: id1, id2.`) list the candidate ids inline, so
1379
+ * parse them directly rather than spending another round trip.
1070
1380
  */
1071
1381
  function accountChoices(body: string) {
1072
1382
  const error = asRecord(asRecord(parseJsonOrUndefined(body))?.error);
1073
1383
  const message = stringField(error, "message") ?? "";
1074
1384
  const start = message.indexOf("[");
1075
1385
  const end = message.lastIndexOf("]");
1076
- if (start === -1 || end <= start) return [];
1077
- const parsed = parseJsonOrUndefined(message.slice(start, end + 1));
1078
- return asRecordArray(parsed).flatMap((entry) => {
1079
- const id = stringField(entry, "connected_account_id");
1080
- if (!id) return [];
1081
- return [
1082
- { connected_account_id: id, label: stringField(entry, "label", "email") },
1083
- ];
1084
- });
1386
+ if (start !== -1 && end > start) {
1387
+ const parsed = parseJsonOrUndefined(message.slice(start, end + 1));
1388
+ const entries = asRecordArray(parsed).flatMap((entry) => {
1389
+ const id = stringField(entry, "connected_account_id");
1390
+ if (!id) return [];
1391
+ return [
1392
+ {
1393
+ connected_account_id: id,
1394
+ label: stringField(entry, "label", "email"),
1395
+ },
1396
+ ];
1397
+ });
1398
+ if (entries.length > 0) return entries;
1399
+ }
1400
+ const inlineMatch = message.match(/Pass connected_account_id:\s*(.+?)\.?$/i);
1401
+ if (inlineMatch?.[1]) {
1402
+ return inlineMatch[1]
1403
+ .split(",")
1404
+ .map((id) => id.trim())
1405
+ .filter(Boolean)
1406
+ .map((id) => ({ connected_account_id: id, label: undefined }));
1407
+ }
1408
+ return [];
1085
1409
  }
1086
1410
 
1087
1411
  function parseJsonOrUndefined(value: string): unknown {
@@ -1107,7 +1431,7 @@ function formatAccountSelection(
1107
1431
  .join("\n");
1108
1432
  }
1109
1433
 
1110
- function noConnectionPayload(toolSlug: string, error: GatewayHttpError) {
1434
+ function noConnectionPayload(toolSlug: string, error: ToolHttpError) {
1111
1435
  const toolkit = toolkitFromSlug(toolSlug);
1112
1436
  return {
1113
1437
  ok: false,
@@ -1138,6 +1462,15 @@ function formatNoConnection(payload: ReturnType<typeof noConnectionPayload>) {
1138
1462
  }
1139
1463
 
1140
1464
  function toolkitFromSlug(toolSlug: string): string | undefined {
1465
+ const parts = toolSlug.split("__");
1466
+ const prefix = parts[0]?.toUpperCase();
1467
+ if (
1468
+ parts.length >= 3 &&
1469
+ (prefix === "APP" || prefix === "NANGO") &&
1470
+ parts[1]
1471
+ ) {
1472
+ return parts[1].toLowerCase().replace(/_mcp$/, "").replace(/_/g, "-");
1473
+ }
1141
1474
  const head = toolSlug.split("_")[0];
1142
1475
  return head ? head.toLowerCase() : undefined;
1143
1476
  }
@@ -1191,6 +1524,11 @@ export type CompactConnection = {
1191
1524
  };
1192
1525
 
1193
1526
  function compactConnection(connection: JsonRecord): CompactConnection {
1527
+ const ownerName = stringField(asRecord(connection.owner), "name");
1528
+ const visibility =
1529
+ connection.visibility === "private" || connection.visibility === "shared"
1530
+ ? connection.visibility
1531
+ : undefined;
1194
1532
  return {
1195
1533
  source: connectionSource(connection.source, "app"),
1196
1534
  toolkit:
@@ -1203,26 +1541,70 @@ function compactConnection(connection: JsonRecord): CompactConnection {
1203
1541
  connection,
1204
1542
  "connected_account_id",
1205
1543
  "connectedAccountId",
1544
+ "connectionId",
1206
1545
  "id",
1207
1546
  ) ?? null,
1208
1547
  accountLabel:
1209
1548
  stringField(connection, "account_label", "accountLabel", "label") ?? null,
1549
+ ...(ownerName ? { ownerName } : {}),
1550
+ ...(visibility ? { visibility } : {}),
1210
1551
  };
1211
1552
  }
1212
1553
 
1213
1554
  function compactUnipileConnection(connection: JsonRecord): CompactConnection {
1214
1555
  return {
1215
1556
  source: connectionSource(connection.source, "dench"),
1216
- toolkit: stringField(connection, "toolkit") ?? "unknown",
1557
+ toolkit:
1558
+ stringField(connection, "toolkit", "toolkit_slug") ??
1559
+ stringField(asRecord(connection.toolkit), "slug", "name") ??
1560
+ "unknown",
1217
1561
  status: stringField(connection, "status") ?? "unknown",
1218
1562
  connectedAccountId: null,
1219
- accountLabel: stringField(connection, "accountLabel") ?? null,
1563
+ accountLabel:
1564
+ stringField(connection, "accountLabel", "account_label") ?? null,
1220
1565
  isOwner: connection.isOwner === true,
1221
1566
  ownerName: stringField(connection, "ownerName") ?? undefined,
1222
1567
  visibility: connection.visibility === "private" ? "private" : "shared",
1223
1568
  };
1224
1569
  }
1225
1570
 
1571
+ function compactAppApiConnection(connection: JsonRecord): CompactConnection {
1572
+ const source = connectionSource(connection.source, "app");
1573
+ if (source === "dench") {
1574
+ return compactUnipileConnection(connection);
1575
+ }
1576
+ if (source === "mcp") {
1577
+ return {
1578
+ source: "mcp",
1579
+ toolkit:
1580
+ stringField(connection, "toolkit_slug", "toolkit") ??
1581
+ stringField(asRecord(connection.toolkit), "slug", "name") ??
1582
+ "unknown",
1583
+ status: stringField(connection, "status") ?? "active",
1584
+ connectedAccountId: null,
1585
+ accountLabel:
1586
+ stringField(
1587
+ connection,
1588
+ "account_label",
1589
+ "accountLabel",
1590
+ "toolkit_name",
1591
+ "name",
1592
+ ) ?? null,
1593
+ ...(typeof connection.isOwner === "boolean"
1594
+ ? { isOwner: connection.isOwner }
1595
+ : {}),
1596
+ ...(stringField(connection, "ownerName")
1597
+ ? { ownerName: stringField(connection, "ownerName") }
1598
+ : {}),
1599
+ ...(connection.visibility === "private" ||
1600
+ connection.visibility === "shared"
1601
+ ? { visibility: connection.visibility }
1602
+ : {}),
1603
+ };
1604
+ }
1605
+ return compactConnection(connection);
1606
+ }
1607
+
1226
1608
  function formatConnectionLine(connection: CompactConnection): string {
1227
1609
  const label = connection.accountLabel ? ` (${connection.accountLabel})` : "";
1228
1610
  const id = connection.connectedAccountId