@privateclaw/privateclaw 0.1.14 → 0.1.16

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.
@@ -6,7 +6,11 @@ import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { unzipSync } from "fflate";
9
- import type { BridgeResponse, PrivateClawAgentBridge } from "../types.js";
9
+ import type {
10
+ BridgeResponse,
11
+ PrivateClawAgentBridge,
12
+ PrivateClawAudioTranscriptionRequest,
13
+ } from "../types.js";
10
14
 
11
15
  type OpenClawThinkingLevel = "off" | "minimal" | "low" | "medium" | "high";
12
16
 
@@ -277,36 +281,85 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
277
281
  this.log(
278
282
  `handle_user_message session=${params.sessionId} textChars=${params.message.length} attachments=${params.attachments?.length ?? 0} promptChars=${promptMessage.length}`,
279
283
  );
280
- const args = this.buildArgs(params.sessionId, promptMessage);
281
- const sessionLogCursor = await this.captureSessionLogCursor(params.sessionId);
284
+ return this.executePrompt(params.sessionId, promptMessage, {
285
+ includeArtifacts: true,
286
+ noDisplayFallbackMessage: params.message,
287
+ });
288
+ }
289
+
290
+ async transcribeAudioAttachments(
291
+ params: PrivateClawAudioTranscriptionRequest,
292
+ ): Promise<string> {
293
+ const transcriptionSessionId = buildVoiceTranscriptionSessionId(
294
+ params.sessionId,
295
+ params.requestId,
296
+ );
297
+ this.log(
298
+ `voice_transcription_start session=${params.sessionId} request=${params.requestId} attachments=${params.attachments.length} sttSession=${transcriptionSessionId}`,
299
+ );
300
+ const stagedAttachments = await this.stageAttachments(
301
+ transcriptionSessionId,
302
+ params.attachments,
303
+ );
304
+ if (stagedAttachments.length === 0) {
305
+ throw new Error(
306
+ "OpenClaw voice transcription requires at least one inline audio attachment.",
307
+ );
308
+ }
309
+ const promptMessage = appendStructuredResponseContract(
310
+ buildAudioTranscriptionPrompt(stagedAttachments),
311
+ );
312
+ const response = await this.executePrompt(transcriptionSessionId, promptMessage, {
313
+ includeArtifacts: false,
314
+ });
315
+ const transcript = extractTextFromBridgeResponse(response).trim();
316
+ if (transcript === "") {
317
+ throw new Error("OpenClaw voice transcription returned an empty transcript.");
318
+ }
319
+ this.log(
320
+ `voice_transcription_complete session=${params.sessionId} request=${params.requestId} transcriptChars=${transcript.length} attachments=${stagedAttachments.length}`,
321
+ );
322
+ return transcript;
323
+ }
324
+
325
+ private async executePrompt(
326
+ sessionId: string,
327
+ promptMessage: string,
328
+ options?: {
329
+ includeArtifacts?: boolean;
330
+ noDisplayFallbackMessage?: string;
331
+ },
332
+ ): Promise<BridgeResponse> {
333
+ const args = this.buildArgs(sessionId, promptMessage);
334
+ const sessionLogCursor = await this.captureSessionLogCursor(sessionId);
282
335
  const stdout = await this.execOpenClaw(args);
283
336
  let parsed: OpenClawAgentJsonResult | undefined;
284
337
  let parseError: unknown;
285
338
  try {
286
339
  parsed = parseOpenClawAgentJson(stdout);
287
340
  this.log(
288
- `openclaw_agent_complete session=${params.sessionId} status=${parsed.status ?? "unknown"} summary=${JSON.stringify(parsed.summary ?? "")}`,
341
+ `openclaw_agent_complete session=${sessionId} status=${parsed.status ?? "unknown"} summary=${JSON.stringify(parsed.summary ?? "")}`,
289
342
  );
290
343
  if (!parsed.status) {
291
344
  this.log(
292
- `openclaw_agent_missing_status session=${params.sessionId} topLevelKeys=${Object.keys(parsed).join(",") || "none"}`,
345
+ `openclaw_agent_missing_status session=${sessionId} topLevelKeys=${Object.keys(parsed).join(",") || "none"}`,
293
346
  );
294
347
  }
295
348
  } catch (error) {
296
349
  parseError = error;
297
350
  this.log(
298
- `openclaw_agent_parse_failed session=${params.sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`,
351
+ `openclaw_agent_parse_failed session=${sessionId} stdoutChars=${stdout.length} stdoutPreview=${JSON.stringify(stdout.slice(0, 400))}`,
299
352
  );
300
353
  }
301
- const collectedMessages = await this.collectSessionMessages(params.sessionId, sessionLogCursor);
354
+ const collectedMessages = await this.collectSessionMessages(sessionId, sessionLogCursor);
302
355
  const recoveredMessages = [
303
356
  ...collectedMessages.assistantMessages,
304
- ...collectedMessages.artifactMessages,
357
+ ...(options?.includeArtifacts === false ? [] : collectedMessages.artifactMessages),
305
358
  ];
306
359
  if (!parsed) {
307
360
  if (recoveredMessages.length > 0) {
308
361
  this.log(
309
- `session_log_fallback session=${params.sessionId} reason=parse_failed recoveredMessages=${recoveredMessages.length}`,
362
+ `session_log_fallback session=${sessionId} reason=parse_failed recoveredMessages=${recoveredMessages.length}`,
310
363
  );
311
364
  return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
312
365
  }
@@ -314,16 +367,21 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
314
367
  }
315
368
  try {
316
369
  const response = parseOpenClawAgentResult(parsed);
317
- return mergeBridgeResponses(response, collectedMessages.artifactMessages);
370
+ return options?.includeArtifacts === false
371
+ ? response
372
+ : mergeBridgeResponses(response, collectedMessages.artifactMessages);
318
373
  } catch (error) {
319
374
  if (recoveredMessages.length > 0) {
320
375
  this.log(
321
- `session_log_fallback session=${params.sessionId} reason=${JSON.stringify(error instanceof Error ? error.message : String(error))} recoveredMessages=${recoveredMessages.length}`,
376
+ `session_log_fallback session=${sessionId} reason=${JSON.stringify(error instanceof Error ? error.message : String(error))} recoveredMessages=${recoveredMessages.length}`,
322
377
  );
323
378
  return toBridgeResponse(recoveredMessages, collectedMessages.assistantData);
324
379
  }
325
380
  if (error instanceof OpenClawAgentNoDisplayPayloadError) {
326
- return buildNoDisplayPayloadNotice(params.message, error.parsed);
381
+ if (options?.noDisplayFallbackMessage) {
382
+ return buildNoDisplayPayloadNotice(options.noDisplayFallbackMessage, error.parsed);
383
+ }
384
+ throw new Error("OpenClaw returned no displayable voice transcription.");
327
385
  }
328
386
  throw error;
329
387
  }
@@ -767,6 +825,13 @@ function normalizeBridgeResponse(response: BridgeResponse): NormalizedBridgeMess
767
825
  );
768
826
  }
769
827
 
828
+ function extractTextFromBridgeResponse(response: BridgeResponse): string {
829
+ return normalizeBridgeResponse(response)
830
+ .map((message) => message.text.trim())
831
+ .filter((text) => text !== "")
832
+ .join("\n\n");
833
+ }
834
+
770
835
  function toBridgeResponse(
771
836
  messages: NormalizedBridgeMessage[],
772
837
  data?: unknown,
@@ -848,6 +913,28 @@ function appendStructuredResponseContract(prompt: string): string {
848
913
  return `${prompt}\n\n${buildStructuredResponseContractPrompt()}`;
849
914
  }
850
915
 
916
+ function buildAudioTranscriptionPrompt(
917
+ stagedAttachments: ReadonlyArray<StagedAttachment>,
918
+ ): string {
919
+ const lines = [
920
+ "PrivateClaw voice transcription request.",
921
+ "Use OpenClaw's speech-to-text or audio understanding capabilities on the exact staged files below.",
922
+ "Return only the recognized spoken content from the user's audio message.",
923
+ "- Do not answer the user's request.",
924
+ "- Do not summarize, explain, or translate unless the speech itself says to do so.",
925
+ "- Preserve the original language and natural punctuation.",
926
+ "- If multiple audio attachments are present, transcribe them in order and separate each transcript with a blank line.",
927
+ "",
928
+ "Staged audio attachments:",
929
+ ];
930
+ for (const attachment of stagedAttachments) {
931
+ lines.push(`- ${attachment.name}`);
932
+ lines.push(` mimeType: ${attachment.effectiveMimeType}`);
933
+ lines.push(` workspacePath: ${attachment.workspacePath}`);
934
+ }
935
+ return lines.join("\n");
936
+ }
937
+
851
938
  function buildStructuredResponseContractPrompt(): string {
852
939
  return [
853
940
  "PrivateClaw response contract:",
@@ -962,6 +1049,23 @@ function normalizeMediaPath(mediaPath: string): string {
962
1049
  return path.isAbsolute(trimmed) ? trimmed : path.resolve(trimmed);
963
1050
  }
964
1051
 
1052
+ function buildVoiceTranscriptionSessionId(sessionId: string, requestId: string): string {
1053
+ return [
1054
+ "privateclaw-voice-stt",
1055
+ sanitizeSessionIdSegment(sessionId),
1056
+ sanitizeSessionIdSegment(requestId),
1057
+ ].join("-");
1058
+ }
1059
+
1060
+ function sanitizeSessionIdSegment(value: string): string {
1061
+ const sanitized = value
1062
+ .trim()
1063
+ .replace(/[^A-Za-z0-9_-]+/gu, "-")
1064
+ .replace(/-+/gu, "-")
1065
+ .replace(/^-|-$/gu, "");
1066
+ return sanitized === "" ? randomUUID().slice(0, 8) : sanitized;
1067
+ }
1068
+
965
1069
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
966
1070
  return error instanceof Error && "code" in error;
967
1071
  }
package/src/cli.ts CHANGED
@@ -27,6 +27,7 @@ import { resolveRelayEndpoints } from "./relay-endpoints.js";
27
27
  import {
28
28
  buildManagedSessionQrLegacyLines,
29
29
  buildManagedSessionsReportLines,
30
+ closeManagedSessionsFromStateDir,
30
31
  closeManagedSessionFromStateDir,
31
32
  getManagedSessionQrBundleFromStateDir,
32
33
  isManagedSessionQrLegacyResult,
@@ -41,6 +42,7 @@ import {
41
42
  PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION,
42
43
  PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION,
43
44
  PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION,
45
+ PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION,
44
46
  PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION,
45
47
  } from "./text.js";
46
48
  import type { PrivateClawProviderHandoffState } from "./types.js";
@@ -252,17 +254,21 @@ async function readHandoffState(
252
254
  }
253
255
 
254
256
  function printHelp(): void {
255
- console.log(`privateclaw-provider <pair|sessions|kick>
257
+ console.log(`privateclaw-provider <pair|sessions|kick|killall>
256
258
 
257
259
  pair [--ttl-ms <ms>] [--label <label>] [--relay <url>] [--group] [--print-only] [--open] [--foreground]
258
260
  sessions
259
261
  sessions qr <sessionId> [--open] [--notify]
260
262
  sessions kill <sessionId>
263
+ sessions killall
264
+ killall
261
265
  kick <sessionId> <appId>`);
262
266
  console.log(`\n--relay <url>: ${PRIVATECLAW_CLI_RELAY_OPTION_DESCRIPTION}`);
263
267
  console.log(`--notify: ${PRIVATECLAW_CLI_NOTIFY_OPTION_DESCRIPTION}`);
264
268
  console.log(`sessions qr: ${PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION}`);
265
269
  console.log(`sessions kill: ${PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION}`);
270
+ console.log(`sessions killall: ${PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION}`);
271
+ console.log(`killall: ${PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION}`);
266
272
  }
267
273
 
268
274
  async function runPairCommand(args: string[]): Promise<void> {
@@ -454,6 +460,10 @@ async function runSessionsCommand(args: string[]): Promise<void> {
454
460
  await runSessionsQrCommand(args.slice(1));
455
461
  return;
456
462
  }
463
+ if (args[0] === "killall") {
464
+ await runSessionsKillallCommand(args.slice(1));
465
+ return;
466
+ }
457
467
  if (args[0] === "kill") {
458
468
  await runSessionsKillCommand(args.slice(1));
459
469
  return;
@@ -516,6 +526,84 @@ async function runSessionsKillCommand(args: string[]): Promise<void> {
516
526
  );
517
527
  }
518
528
 
529
+ async function runSessionsKillallCommand(args: string[]): Promise<void> {
530
+ const parsed = parseArgs({
531
+ args,
532
+ allowPositionals: true,
533
+ options: {
534
+ help: { type: "boolean", short: "h" },
535
+ },
536
+ });
537
+ if (parsed.values.help) {
538
+ printHelp();
539
+ return;
540
+ }
541
+ if (parsed.positionals.length > 0) {
542
+ throw new Error(
543
+ formatBilingualInline(
544
+ "`sessions killall` 不接受额外参数。",
545
+ "`sessions killall` does not accept extra arguments.",
546
+ ),
547
+ );
548
+ }
549
+
550
+ const result = await closeManagedSessionsFromStateDir({
551
+ stateDir: resolvePrivateClawStateDir(),
552
+ hostKinds: ["pair-daemon"],
553
+ reason: "operator_terminated_all",
554
+ });
555
+
556
+ if (result.closed.length === 0 && result.failed.length === 0) {
557
+ console.log(
558
+ formatBilingualInline(
559
+ "当前没有需要终止的后台 daemon 会话。",
560
+ "There are no background daemon sessions to terminate.",
561
+ ),
562
+ );
563
+ return;
564
+ }
565
+
566
+ if (result.closed.length > 0) {
567
+ console.log(
568
+ formatBilingualInline(
569
+ `已终止 ${result.closed.length} 个后台 daemon 会话。`,
570
+ `Terminated ${result.closed.length} background daemon session(s).`,
571
+ ),
572
+ );
573
+ for (const item of result.closed) {
574
+ console.log(
575
+ item.terminatedHost
576
+ ? formatBilingualInline(
577
+ `- ${item.session.sessionId}:已通过终止 legacy host ${item.host.kind}#${item.host.pid} 停止。`,
578
+ `- ${item.session.sessionId}: stopped by terminating the legacy host ${item.host.kind}#${item.host.pid}.`,
579
+ )
580
+ : formatBilingualInline(
581
+ `- ${item.session.sessionId}:已终止。`,
582
+ `- ${item.session.sessionId}: terminated.`,
583
+ ),
584
+ );
585
+ }
586
+ }
587
+
588
+ if (result.failed.length > 0) {
589
+ console.error(
590
+ formatBilingualInline(
591
+ `${result.failed.length} 个后台 daemon 会话终止失败。`,
592
+ `${result.failed.length} background daemon session(s) failed to terminate.`,
593
+ ),
594
+ );
595
+ for (const item of result.failed) {
596
+ console.error(
597
+ formatBilingualInline(
598
+ `- ${item.session.sessionId}(${item.host.kind}#${item.host.pid}):${item.error}`,
599
+ `- ${item.session.sessionId} (${item.host.kind}#${item.host.pid}): ${item.error}`,
600
+ ),
601
+ );
602
+ }
603
+ process.exitCode = 1;
604
+ }
605
+ }
606
+
519
607
  async function runSessionsQrCommand(args: string[]): Promise<void> {
520
608
  const parsed = parseArgs({
521
609
  args,
@@ -634,6 +722,8 @@ try {
634
722
  await runPairCommand(rest);
635
723
  } else if (command === "sessions") {
636
724
  await runSessionsCommand(rest);
725
+ } else if (command === "killall") {
726
+ await runSessionsKillallCommand(rest);
637
727
  } else if (command === "kick") {
638
728
  await runKickCommand(rest);
639
729
  } else if (command === "help" || command === "--help" || command === "-h") {
@@ -34,6 +34,7 @@ import { resolveRelayEndpoints } from "./relay-endpoints.js";
34
34
  import {
35
35
  buildManagedSessionQrLegacyLines,
36
36
  buildManagedSessionsReportLines,
37
+ closeManagedSessionsFromStateDir,
37
38
  closeManagedSessionFromStateDir,
38
39
  getManagedSessionQrBundleFromStateDir,
39
40
  isManagedSessionQrLegacyResult,
@@ -59,6 +60,7 @@ import {
59
60
  PRIVATECLAW_CLI_ROOT_DESCRIPTION,
60
61
  PRIVATECLAW_CLI_SESSIONS_DESCRIPTION,
61
62
  PRIVATECLAW_CLI_SESSIONS_KILL_DESCRIPTION,
63
+ PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION,
62
64
  PRIVATECLAW_CLI_SESSIONS_QR_DESCRIPTION,
63
65
  PRIVATECLAW_CLI_TTL_OPTION_DESCRIPTION,
64
66
  PRIVATECLAW_COMMAND_DESCRIPTION,
@@ -886,6 +888,14 @@ class PrivateClawPluginRuntime {
886
888
  });
887
889
  }
888
890
 
891
+ async closeBackgroundManagedSessions() {
892
+ return closeManagedSessionsFromStateDir({
893
+ stateDir: this.ensureStateDir(),
894
+ hostKinds: ["pair-daemon"],
895
+ reason: "operator_terminated_all",
896
+ });
897
+ }
898
+
889
899
  async printManagedSessionQr(
890
900
  sessionId: string,
891
901
  params?: {
@@ -1125,6 +1135,65 @@ function createPluginDefinition(
1125
1135
  }
1126
1136
  });
1127
1137
 
1138
+ sessions
1139
+ .command("killall")
1140
+ .description(PRIVATECLAW_CLI_SESSIONS_KILLALL_DESCRIPTION)
1141
+ .action(async () => {
1142
+ try {
1143
+ const result = await runtime.closeBackgroundManagedSessions();
1144
+ if (result.closed.length === 0 && result.failed.length === 0) {
1145
+ console.log(
1146
+ formatBilingualInline(
1147
+ "当前没有需要终止的后台 daemon 会话。",
1148
+ "There are no background daemon sessions to terminate.",
1149
+ ),
1150
+ );
1151
+ return;
1152
+ }
1153
+ if (result.closed.length > 0) {
1154
+ console.log(
1155
+ formatBilingualInline(
1156
+ `已终止 ${result.closed.length} 个后台 daemon 会话。`,
1157
+ `Terminated ${result.closed.length} background daemon session(s).`,
1158
+ ),
1159
+ );
1160
+ for (const item of result.closed) {
1161
+ console.log(
1162
+ item.terminatedHost
1163
+ ? formatBilingualInline(
1164
+ `- ${item.session.sessionId}:已通过终止 legacy host ${item.host.kind}#${item.host.pid} 停止。`,
1165
+ `- ${item.session.sessionId}: stopped by terminating the legacy host ${item.host.kind}#${item.host.pid}.`,
1166
+ )
1167
+ : formatBilingualInline(
1168
+ `- ${item.session.sessionId}:已终止。`,
1169
+ `- ${item.session.sessionId}: terminated.`,
1170
+ ),
1171
+ );
1172
+ }
1173
+ }
1174
+ if (result.failed.length > 0) {
1175
+ console.error(
1176
+ formatBilingualInline(
1177
+ `${result.failed.length} 个后台 daemon 会话终止失败。`,
1178
+ `${result.failed.length} background daemon session(s) failed to terminate.`,
1179
+ ),
1180
+ );
1181
+ for (const item of result.failed) {
1182
+ console.error(
1183
+ formatBilingualInline(
1184
+ `- ${item.session.sessionId}(${item.host.kind}#${item.host.pid}):${item.error}`,
1185
+ `- ${item.session.sessionId} (${item.host.kind}#${item.host.pid}): ${item.error}`,
1186
+ ),
1187
+ );
1188
+ }
1189
+ process.exitCode = 1;
1190
+ }
1191
+ } catch (error) {
1192
+ console.error(formatCommandError(error));
1193
+ process.exitCode = 1;
1194
+ }
1195
+ });
1196
+
1128
1197
  privateclaw
1129
1198
  .command("kick")
1130
1199
  .description(PRIVATECLAW_CLI_KICK_DESCRIPTION)
@@ -0,0 +1,48 @@
1
+ import assert from "node:assert/strict";
2
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { pathToFileURL } from "node:url";
7
+ import { resolveCliInvocation } from "./pair-daemon.js";
8
+
9
+ test("resolveCliInvocation prefers the built dist cli when the source entry comes from src/", async (t) => {
10
+ const packageRoot = await mkdtemp(
11
+ path.join(os.tmpdir(), "privateclaw-pair-daemon-cli-"),
12
+ );
13
+
14
+ t.after(async () => {
15
+ await rm(packageRoot, { recursive: true, force: true });
16
+ });
17
+
18
+ await mkdir(path.join(packageRoot, "src"), { recursive: true });
19
+ await mkdir(path.join(packageRoot, "dist"), { recursive: true });
20
+ await writeFile(path.join(packageRoot, "src", "cli.ts"), "export {};\n", "utf8");
21
+ await writeFile(path.join(packageRoot, "dist", "cli.js"), "export {};\n", "utf8");
22
+
23
+ const invocation = await resolveCliInvocation(
24
+ pathToFileURL(path.join(packageRoot, "src", "cli.ts")).href,
25
+ );
26
+
27
+ assert.equal(invocation.command, process.execPath);
28
+ assert.deepEqual(invocation.args, [path.join(packageRoot, "dist", "cli.js")]);
29
+ });
30
+
31
+ test("resolveCliInvocation falls back to tsx when no built dist cli is present", async (t) => {
32
+ const packageRoot = await mkdtemp(
33
+ path.join(os.tmpdir(), "privateclaw-pair-daemon-cli-"),
34
+ );
35
+
36
+ t.after(async () => {
37
+ await rm(packageRoot, { recursive: true, force: true });
38
+ });
39
+
40
+ await mkdir(path.join(packageRoot, "src"), { recursive: true });
41
+ await writeFile(path.join(packageRoot, "src", "cli.ts"), "export {};\n", "utf8");
42
+
43
+ const sourceCliPath = path.join(packageRoot, "src", "cli.ts");
44
+ const invocation = await resolveCliInvocation(pathToFileURL(sourceCliPath).href);
45
+
46
+ assert.equal(invocation.command, process.execPath);
47
+ assert.deepEqual(invocation.args, ["--import", "tsx", sourceCliPath]);
48
+ });
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { spawn } from "node:child_process";
3
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
3
+ import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { constants } from "node:fs";
4
5
  import os from "node:os";
5
6
  import path from "node:path";
6
7
  import { fileURLToPath } from "node:url";
@@ -28,10 +29,44 @@ interface PairDaemonHandoffSuccessResult {
28
29
 
29
30
  type PairDaemonHandoffResult = PairDaemonHandoffSuccessResult | PairDaemonErrorResult;
30
31
 
31
- async function resolveCliInvocation(
32
+ async function pathExists(filePath: string): Promise<boolean> {
33
+ try {
34
+ await access(filePath, constants.F_OK);
35
+ return true;
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ function resolveBuiltCliCandidate(cliPath: string): string | null {
42
+ if (path.extname(cliPath) !== ".ts") {
43
+ return null;
44
+ }
45
+
46
+ const sourceDir = path.dirname(cliPath);
47
+ if (path.basename(sourceDir) !== "src") {
48
+ return null;
49
+ }
50
+
51
+ return path.join(
52
+ path.dirname(sourceDir),
53
+ "dist",
54
+ `${path.basename(cliPath, ".ts")}.js`,
55
+ );
56
+ }
57
+
58
+ export async function resolveCliInvocation(
32
59
  cliModuleUrl: string,
33
60
  ): Promise<{ command: string; args: string[] }> {
34
61
  const cliPath = fileURLToPath(cliModuleUrl);
62
+ const builtCliPath = resolveBuiltCliCandidate(cliPath);
63
+ if (builtCliPath && (await pathExists(builtCliPath))) {
64
+ return {
65
+ command: process.execPath,
66
+ args: [builtCliPath],
67
+ };
68
+ }
69
+
35
70
  return path.extname(cliPath) === ".ts"
36
71
  ? {
37
72
  command: process.execPath,