-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathmain.ts
More file actions
3165 lines (2874 loc) · 111 KB
/
Copy pathmain.ts
File metadata and controls
3165 lines (2874 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// MUST be first: publishes the colocated libSQL/keyring native `.node` paths
// before any import (e.g. `@executor-js/local` → libSQL) eagerly loads them.
import "./native-bindings";
import { randomUUID } from "node:crypto";
import { existsSync, realpathSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
// Make sibling binaries (if any are added later) discoverable on $PATH so
// child processes spawned without an absolute path still find them.
const execDir = dirname(process.execPath);
if (process.env.PATH && !process.env.PATH.includes(execDir)) {
process.env.PATH = `${execDir}:${process.env.PATH}`;
}
// Pre-load QuickJS WASM for compiled binaries — must run before server imports
const wasmOnDisk = join(execDir, "emscripten-module.wasm");
if (typeof Bun !== "undefined" && (await Bun.file(wasmOnDisk).exists())) {
const { setQuickJSModule } = await import("@executor-js/runtime-quickjs");
const { newQuickJSWASMModule } = await import("quickjs-emscripten");
type QuickJSSyncVariant = import("quickjs-emscripten").QuickJSSyncVariant;
const wasmBinary = await Bun.file(wasmOnDisk).arrayBuffer();
const importFFI: QuickJSSyncVariant["importFFI"] = () =>
import("@jitl/quickjs-wasmfile-release-sync/ffi").then((m) => m.QuickJSFFI);
const importModuleLoader: QuickJSSyncVariant["importModuleLoader"] = async () => {
const { default: original } =
await import("@jitl/quickjs-wasmfile-release-sync/emscripten-module");
return (moduleArg = {}) => original({ ...moduleArg, wasmBinary });
};
const variant: QuickJSSyncVariant = {
type: "sync" as const,
importFFI,
importModuleLoader,
};
const mod = await newQuickJSWASMModule(variant);
setQuickJSModule(mod);
}
const sentryDsn = process.env.EXECUTOR_SENTRY_DSN;
if (sentryDsn) {
const Sentry = await import("@sentry/bun");
Sentry.init({
dsn: sentryDsn,
release: process.env.EXECUTOR_SENTRY_RELEASE,
environment: process.env.EXECUTOR_SENTRY_ENVIRONMENT ?? "production",
tracesSampleRate: 0,
initialScope: {
tags: {
process: "daemon",
platform: process.platform,
arch: process.arch,
...(process.env.EXECUTOR_RUN_ID ? { runId: process.env.EXECUTOR_RUN_ID } : {}),
},
},
});
}
import { Argument as Args, Command, Flag as Options } from "effect/unstable/cli";
import { BunRuntime, BunServices } from "@effect/platform-bun";
import { HttpApiClient } from "effect/unstable/httpapi";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
import { FileSystem, Path as PlatformPath } from "effect";
import type { PlatformError } from "effect/PlatformError";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Cause from "effect/Cause";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
import { ExecutorApi, checkForUpdate } from "@executor-js/api";
import {
getExecutorServerAuthorizationHeader,
normalizeExecutorServerConnection,
normalizeExecutorServerOrigin,
type ExecutorLocalServerKind,
type ExecutorLocalServerManifest,
type ExecutorServerConnection,
type ExecutorServerConnectionInput,
} from "@executor-js/sdk/shared";
import {
decodeAccessTokenClaims,
discoverCliLogin,
openBrowser,
pollForDeviceTokens,
refreshDeviceTokens,
requestDeviceCode,
} from "./device-login";
import {
startServer,
rotateLocalAuthToken,
localAuthTokenPath,
findDataDirOwnershipHeld,
type ServerInstance,
type StartServerOptions,
} from "@executor-js/local";
import { fetchIntegrations } from "./integrations";
import {
buildDaemonSpawnSpec,
chooseDaemonPort,
canAutoStartLocalDaemonForHost,
isExecutorServerReachable,
isDevCliEntrypoint,
parseDaemonBaseUrl,
planServiceInstall,
spawnDetached,
terminateSpawnedDetachedProcess,
waitForReachable,
waitForUnreachable,
} from "./daemon";
import {
acquireDaemonStartLock,
canonicalDaemonHost,
currentDaemonScopeId,
isPidAlive,
readDaemonPointer,
readDaemonRecord,
releaseDaemonStartLock,
removeDaemonPointer,
removeDaemonRecord,
terminatePid,
writeDaemonPointer,
writeDaemonRecord,
} from "./daemon-state";
import {
canAutoStartCliServerConnection,
chooseCliServerConnectionWithActiveLocal,
parseCliExecutorServerConnection,
type CliServerConnectionSource,
withCliServerAuthFallback,
} from "./server-connection";
import {
readLocalServerManifest,
removeLocalServerManifestIfOwnedBy,
resolveExecutorDataDir,
writeLocalServerManifest,
} from "./local-server-manifest";
import {
DEFAULT_SERVICE_PORT,
getServiceBackend,
SERVICE_LABEL,
stopWindowsExecutorListenersOnPort,
} from "./service";
import {
defaultCliServerConnectionProfile,
findCliServerConnectionProfile,
readCliServerConnectionStore,
removeCliServerConnectionProfile,
setDefaultCliServerConnectionProfile,
upsertCliServerConnectionProfile,
validateCliServerConnectionProfileName,
type CliServerConnectionStore,
} from "./server-profile";
import {
buildResumeContentTemplate,
buildDescribeToolCode,
filterToolPathChildren,
buildInvokeToolCode,
buildListSourcesCode,
buildSearchToolsCode,
extractExecutionId,
extractPausedInteraction,
extractExecutionResult,
inspectToolPath,
normalizeCliErrorText,
parseJsonObjectInput,
resolveToolInvocation,
sanitizeCliOutputText,
shellQuoteArg,
} from "./tooling";
// Embedded web UI — baked into compiled binaries via `with { type: "file" }`
import embeddedWebUI from "./embedded-web-ui.gen";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const { version: CLI_VERSION } = await import("../package.json");
const DEFAULT_PORT = 4788;
/** Canonical public docs (Mintlify), matching the web shell's DEFAULT_DOCS_URL. */
const DOCS_URL = "https://executor.sh/docs";
const DEFAULT_BASE_URL = `http://localhost:${DEFAULT_PORT}`;
const DESKTOP_SIDECAR_READY_SENTINEL = "EXECUTOR_READY";
const DESKTOP_SIDECAR_ATTACHED_SENTINEL = "EXECUTOR_ATTACHED";
const DAEMON_BOOT_TIMEOUT_MS = 15_000;
const DAEMON_BOOT_POLL_MS = 150;
const DAEMON_STOP_TIMEOUT_MS = 10_000;
const SERVICE_BOOT_TIMEOUT_MS = 45_000;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const shouldEmitDesktopSidecarSentinels = (): boolean => process.env.EXECUTOR_CLIENT === "desktop";
const waitForShutdownSignal = () =>
Effect.callback<void, never>((resume) => {
const shutdown = () => resume(Effect.void);
process.once("SIGINT", shutdown);
process.once("SIGTERM", shutdown);
return Effect.sync(() => {
process.off("SIGINT", shutdown);
process.off("SIGTERM", shutdown);
});
});
// ---------------------------------------------------------------------------
// Background server management
// ---------------------------------------------------------------------------
const isServerReachable = (baseUrl: string): Effect.Effect<boolean> =>
isExecutorServerReachable({ baseUrl });
const readReachableLocalServerHint = (): Effect.Effect<
ExecutorLocalServerManifest | null,
never,
FileSystem.FileSystem | PlatformPath.Path
> =>
Effect.gen(function* () {
const manifest = yield* readLocalServerManifest();
if (!manifest) return null;
if (yield* isServerReachable(manifest.connection.origin)) {
return manifest;
}
if (!isPidAlive(manifest.pid)) {
yield* removeLocalServerManifestIfOwnedBy({ pid: manifest.pid }).pipe(Effect.ignore);
return null;
}
return null;
});
const readActiveLocalServerManifest = readReachableLocalServerHint;
const normalizeDaemonScopeDir = (dir: string): string => {
const resolved = resolve(dir);
return existsSync(resolved) ? realpathSync.native(resolved) : resolved;
};
const currentScopeDirForManifest = (): string | null =>
process.env.EXECUTOR_SCOPE_DIR ? normalizeDaemonScopeDir(process.env.EXECUTOR_SCOPE_DIR) : null;
const script = process.argv[1];
const isDevMode = isDevCliEntrypoint(script);
const cliPrefix = isDevMode ? `bun run ${script}` : "executor";
const toError = (cause: unknown): Error =>
cause instanceof Error ? cause : new Error(String(cause));
interface ServerTarget {
readonly baseUrl?: string;
readonly serverName?: string;
}
interface RequestedExecutorServerConnection {
readonly connection: ExecutorServerConnection;
readonly source: CliServerConnectionSource;
}
interface ExecuteCodeResult {
readonly connection: ExecutorServerConnection;
readonly outcome: ExecuteCodeOutcome;
}
type LocalServerStartResult =
| { readonly kind: "started"; readonly server: ServerInstance }
| { readonly kind: "attached"; readonly manifest: ExecutorLocalServerManifest };
const attachToOwnedDataDirServerOrFail = (input: {
readonly lockPath: string;
}): Effect.Effect<ExecutorLocalServerManifest, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const manifest = yield* readReachableLocalServerHint();
if (manifest) return manifest;
const path = yield* PlatformPath.Path;
const dataDir = resolveExecutorDataDir(path);
return yield* Effect.fail(
new Error(
[
"Executor data directory is owned by another live process, but no reachable local server was advertised.",
`Data directory: ${dataDir}`,
`Ownership lock: ${input.lockPath}`,
"Wait for the existing process to finish starting, or stop it and retry.",
].join("\n"),
),
);
});
const startServerOrAttachOwnedDataDir = (
options: StartServerOptions,
): Effect.Effect<LocalServerStartResult, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.tryPromise({
try: () => startServer(options),
catch: (cause) => cause,
}).pipe(
Effect.map((server) => ({ kind: "started" as const, server })),
Effect.catch((cause) => {
const ownership = findDataDirOwnershipHeld(cause);
if (!ownership) return Effect.fail(toError(cause));
return attachToOwnedDataDirServerOrFail({ lockPath: ownership.lockPath }).pipe(
Effect.map((manifest) => ({ kind: "attached" as const, manifest })),
);
}),
);
const parseDaemonUrl = (baseUrl: string) =>
Effect.try({
try: () => parseDaemonBaseUrl(baseUrl, DEFAULT_PORT),
catch: (cause) =>
cause instanceof Error ? cause : new Error(`Invalid base URL: ${String(cause)}`),
});
const parseExecutorServerConnection = (baseUrl: string) =>
Effect.try({
try: () => parseCliExecutorServerConnection(baseUrl),
catch: (cause) =>
cause instanceof Error ? cause : new Error(`Invalid server URL: ${String(cause)}`),
});
const daemonBaseUrl = (hostname: string, port: number): string =>
`http://${canonicalDaemonHost(hostname)}:${port}`;
const makeLocalServerManifest = (input: {
readonly kind: ExecutorLocalServerKind;
readonly connection: ExecutorServerConnection;
}): Effect.Effect<ExecutorLocalServerManifest, never, PlatformPath.Path> =>
Effect.gen(function* () {
const path = yield* PlatformPath.Path;
return {
version: 1,
kind: input.kind,
pid: process.pid,
startedAt: new Date().toISOString(),
dataDir: resolveExecutorDataDir(path),
scopeDir: currentScopeDirForManifest(),
connection: input.connection,
owner: {
client: process.env.EXECUTOR_CLIENT === "desktop" ? "desktop" : "cli",
version: CLI_VERSION,
executablePath: isDevMode ? (script ?? null) : process.execPath,
},
};
});
// Friendly, intentionally racy fast-path: it reads the server.json hint to fail
// early with a helpful message when another local server is already up. It is
// NOT the ownership gate — the DB ownership lock inside startServer
// (openOwnedLocalDatabase) is. A stale/missing manifest only costs the nice
// message; the kernel lock still refuses a second owner.
const assertNoOtherActiveLocalServer = (): Effect.Effect<
void,
Error,
FileSystem.FileSystem | PlatformPath.Path
> =>
Effect.gen(function* () {
const active = yield* readActiveLocalServerManifest();
if (!active || active.pid === process.pid) return;
return yield* Effect.fail(
new Error(
[
`A local Executor ${active.kind} is already running at ${active.connection.origin} (pid ${active.pid}).`,
`It owns the current data directory: ${active.dataDir}`,
"Stop it before starting another local server.",
].join("\n"),
),
);
});
const takeOverActiveLocalServer = (input?: {
readonly onlyKind?: ExecutorLocalServerKind;
}): Effect.Effect<
ExecutorLocalServerManifest | null,
Error,
FileSystem.FileSystem | PlatformPath.Path
> =>
Effect.gen(function* () {
const manifest = yield* readLocalServerManifest();
if (!manifest) return null;
if (input?.onlyKind && manifest.kind !== input.onlyKind) return null;
if (!isPidAlive(manifest.pid) || manifest.pid === process.pid) {
yield* removeLocalServerManifestIfOwnedBy({ pid: manifest.pid }).pipe(Effect.ignore);
return null;
}
yield* terminatePid(manifest.pid).pipe(Effect.ignore);
const stopped = yield* waitForUnreachable({
check: isServerReachable(manifest.connection.origin),
timeoutMs: DAEMON_STOP_TIMEOUT_MS,
intervalMs: DAEMON_BOOT_POLL_MS,
});
if (!stopped) {
return yield* Effect.fail(
new Error(
[
`The existing Executor ${manifest.kind} at ${manifest.connection.origin} (pid ${manifest.pid}) did not stop within ${DAEMON_STOP_TIMEOUT_MS / 1000}s.`,
"Stop it manually and re-run.",
].join("\n"),
),
);
}
yield* removeLocalServerManifestIfOwnedBy({ pid: manifest.pid }).pipe(Effect.ignore);
return manifest;
});
const publishLocalServerManifest = (input: {
readonly kind: ExecutorLocalServerKind;
readonly connection: ExecutorServerConnection;
}): Effect.Effect<void, PlatformError, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const manifest = yield* makeLocalServerManifest(input);
yield* writeLocalServerManifest(manifest);
});
const installDefaultExecutorWebBaseUrl = (baseUrl: string): (() => void) => {
if (process.env.EXECUTOR_WEB_BASE_URL !== undefined) {
return () => {};
}
process.env.EXECUTOR_WEB_BASE_URL = baseUrl;
return () => {
delete process.env.EXECUTOR_WEB_BASE_URL;
};
};
const cleanupPointer = (input: { hostname: string; scopeId: string; port: number }) =>
Effect.gen(function* () {
yield* removeDaemonPointer({ hostname: input.hostname, scopeId: input.scopeId }).pipe(
Effect.ignore,
);
yield* removeDaemonRecord({ hostname: input.hostname, port: input.port }).pipe(Effect.ignore);
});
const resolveDaemonTarget = (baseUrl: string) =>
Effect.gen(function* () {
const parsed = yield* parseDaemonUrl(baseUrl);
const host = canonicalDaemonHost(parsed.hostname);
const scopeId = currentDaemonScopeId();
const pointer = yield* readDaemonPointer({ hostname: host, scopeId });
if (pointer) {
const pointerUrl = daemonBaseUrl(pointer.hostname, pointer.port);
if (isPidAlive(pointer.pid) && (yield* isServerReachable(pointerUrl))) {
return {
baseUrl: pointerUrl,
hostname: pointer.hostname,
port: pointer.port,
scopeId,
fromPointer: true,
};
}
yield* cleanupPointer({ hostname: pointer.hostname, scopeId, port: pointer.port });
}
return {
baseUrl: daemonBaseUrl(host, parsed.port),
hostname: host,
port: parsed.port,
scopeId,
fromPointer: false,
};
});
const waitForDaemonStartupTarget = (input: {
readonly requestedBaseUrl: string;
}): Effect.Effect<string | null, never, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
let readyBaseUrl: string | null = null;
let requestedFallbackBaseUrl: string | null = null;
const ready = yield* waitForReachable({
check: Effect.gen(function* () {
// Prefer the manifest: it is written after the server has opened the
// owned DB and started serving, and it carries the bearer token the next
// API call needs. A bare health response on the requested URL is only a
// last-ditch fallback; keep polling for the manifest so tool calls do
// not race ahead without auth.
const manifest = yield* readReachableLocalServerHint();
if (manifest) {
readyBaseUrl = manifest.connection.origin;
return true;
}
if (yield* isServerReachable(input.requestedBaseUrl)) {
requestedFallbackBaseUrl = input.requestedBaseUrl;
}
return false;
}),
timeoutMs: DAEMON_BOOT_TIMEOUT_MS,
intervalMs: DAEMON_BOOT_POLL_MS,
});
return ready ? readyBaseUrl : requestedFallbackBaseUrl;
});
// Serialize daemon startup behind a filesystem lock so concurrent CLI invocations don't
// each spawn their own daemon. The post-lock pointer recheck catches the case where
// another invocation finished bootstrapping while we were waiting for the lock.
// A storm of concurrent cold starts should elect ONE owner with the rest
// attaching, never N-1 hard failures. Each attempt either wins the per-scope
// start lock and spawns the daemon, or waits for the current holder's manifest.
// Re-acquiring after a wait timeout is what recovers the one window the wait
// alone cannot: acquireDaemonStartLock reclaims a STALE lock at acquisition, so
// a holder that took the lock then died BEFORE spawning (no daemon, no manifest)
// is recovered when a loser loops back and re-acquires.
const MAX_DAEMON_ELECTION_ATTEMPTS = 3;
/** The stable message acquireDaemonStartLock fails with on genuine lock
* contention. Only this should be treated as "another process is electing";
* any other failure (e.g. an unwritable data dir) must propagate, not masquerade
* as a race the caller should wait out. */
const isStartLockContention = (error: Error): boolean =>
error.message.includes("Another daemon startup is already in progress");
const spawnDaemonAsLockHolder = (input: {
host: string;
scopeId: string;
preferredPort: number;
allowedHosts: ReadonlyArray<string>;
}): Effect.Effect<string, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const existing = yield* readDaemonPointer({ hostname: input.host, scopeId: input.scopeId });
if (existing && isPidAlive(existing.pid)) {
const existingUrl = daemonBaseUrl(existing.hostname, existing.port);
if (yield* isServerReachable(existingUrl)) {
return existingUrl;
}
}
const selectedPort = yield* chooseDaemonPort({
preferredPort: input.preferredPort,
hostname: input.host,
});
if (selectedPort !== input.preferredPort) {
console.error(
`Port ${input.preferredPort} is in use. Starting daemon on available port ${selectedPort} instead.`,
);
}
const spec = yield* Effect.try({
try: () =>
buildDaemonSpawnSpec({
port: selectedPort,
hostname: input.host,
isDevMode,
scriptPath: script,
executablePath: process.execPath,
allowedHosts: input.allowedHosts,
}),
catch: (cause) =>
cause instanceof Error
? cause
: new Error(`Failed to build daemon command: ${String(cause)}`),
});
const startBaseUrl = daemonBaseUrl(input.host, selectedPort);
console.error(`Starting daemon on ${input.host}:${selectedPort}...`);
const child = yield* spawnDetached({
command: spec.command,
args: spec.args,
env: process.env,
});
const readyBaseUrl = yield* waitForDaemonStartupTarget({ requestedBaseUrl: startBaseUrl });
if (!readyBaseUrl) {
yield* terminateSpawnedDetachedProcess(child).pipe(Effect.ignore);
return yield* Effect.fail(
new Error(
[
`Daemon did not become reachable at ${startBaseUrl} and no reachable local server manifest appeared within ${DAEMON_BOOT_TIMEOUT_MS}ms.`,
`Run in foreground to inspect logs: ${cliPrefix} daemon run --foreground --port ${selectedPort} --hostname ${input.host}`,
].join("\n"),
),
);
}
return readyBaseUrl;
});
const spawnAndWaitForDaemon = (input: {
host: string;
scopeId: string;
preferredPort: number;
allowedHosts: ReadonlyArray<string>;
}): Effect.Effect<string, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const requestedBaseUrl = daemonBaseUrl(input.host, input.preferredPort);
for (let attempt = 1; attempt <= MAX_DAEMON_ELECTION_ATTEMPTS; attempt++) {
const acquired = yield* acquireDaemonStartLock({
hostname: input.host,
scopeId: input.scopeId,
}).pipe(
Effect.map((lock) => ({ held: true as const, lock })),
Effect.catch((error) =>
isStartLockContention(error)
? Effect.succeed({ held: false as const, lock: null })
: Effect.fail(error),
),
);
if (acquired.held) {
const lock = acquired.lock;
return yield* spawnDaemonAsLockHolder(input).pipe(
Effect.ensuring(releaseDaemonStartLock(lock).pipe(Effect.ignore)),
);
}
// Lost the lock: wait for the current holder to advertise a manifest.
const ready = yield* waitForDaemonStartupTarget({ requestedBaseUrl });
if (ready) return ready;
// Timed out with no manifest. The holder may have died mid-startup; loop to
// re-acquire, which reclaims its now-stale lock.
}
return yield* Effect.fail(
new Error(
[
`Could not elect or attach to a local Executor daemon after ${MAX_DAEMON_ELECTION_ATTEMPTS} attempts.`,
"A daemon startup may be stuck. Stop any partial daemon and retry, or run it in the foreground:",
`${cliPrefix} daemon run --foreground --port ${input.preferredPort} --hostname ${input.host}`,
].join("\n"),
),
);
});
// Auto-start a local daemon on demand so commands like `executor call` work without the
// user having to run `daemon run` first. Refuses non-local hosts because spawning a
// daemon process on the user's behalf only makes sense when "the user's machine" is
// also where the request will land.
const ensureDaemon = (
baseUrl: string,
): Effect.Effect<string, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const resolvedTarget = yield* resolveDaemonTarget(baseUrl);
if (resolvedTarget.fromPointer && (yield* isServerReachable(resolvedTarget.baseUrl))) {
return resolvedTarget.baseUrl;
}
const active = yield* readActiveLocalServerManifest();
const activeOrigin = active
? normalizeExecutorServerConnection({ origin: active.connection.origin }).origin
: null;
const targetOrigin = normalizeExecutorServerConnection({
origin: resolvedTarget.baseUrl,
}).origin;
if (activeOrigin === targetOrigin) {
return resolvedTarget.baseUrl;
}
if (active && activeOrigin !== targetOrigin) {
return yield* Effect.fail(
new Error(
[
`A local Executor ${active.kind} is already running at ${active.connection.origin} (pid ${active.pid}).`,
`It owns the current data directory: ${active.dataDir}`,
"Refusing to start another local daemon against the same database.",
].join("\n"),
),
);
}
const parsed = yield* parseDaemonUrl(baseUrl);
const host = canonicalDaemonHost(parsed.hostname);
if (!canAutoStartLocalDaemonForHost(host)) {
return yield* Effect.fail(
new Error(
[
`Executor daemon is not reachable at ${baseUrl}.`,
"Auto-start is only supported for local hosts.",
`Start it manually: ${cliPrefix} daemon run --port ${parsed.port} --hostname ${host}`,
].join("\n"),
),
);
}
return yield* spawnAndWaitForDaemon({
host,
scopeId: resolvedTarget.scopeId,
preferredPort: parsed.port,
allowedHosts: [],
});
}).pipe(Effect.mapError(toError));
const resolveRequestedExecutorServerConnection = (
target: ServerTarget,
): Effect.Effect<
RequestedExecutorServerConnection,
Error,
FileSystem.FileSystem | PlatformPath.Path
> =>
Effect.gen(function* () {
if (target.baseUrl && target.serverName) {
return yield* Effect.fail(new Error("Use either --server or --base-url, not both."));
}
if (target.serverName) {
const store = yield* readCliServerConnectionStore();
const profile = findCliServerConnectionProfile(store, target.serverName);
if (!profile) {
return yield* Effect.fail(new Error(`No server profile named "${target.serverName}".`));
}
return { connection: withCliServerAuthFallback(profile.connection), source: "explicit" };
}
if (!target.baseUrl) {
const store = yield* readCliServerConnectionStore();
const profile = defaultCliServerConnectionProfile(store);
if (profile) {
return {
connection: withCliServerAuthFallback(profile.connection),
source: "default-profile",
};
}
const active = yield* readActiveLocalServerManifest();
if (active) return { connection: active.connection, source: "active-local" };
}
return {
connection: yield* parseExecutorServerConnection(target.baseUrl ?? DEFAULT_BASE_URL),
source: target.baseUrl ? "explicit" : "implicit-default",
};
});
// Refresh an `oauth` (device-login) credential a minute before it expires, so
// `executor call` against a hosted server keeps working long after the browser
// login. The refreshed tokens are written back to the originating profile.
const OAUTH_REFRESH_SKEW_SECONDS = 60;
const profileNameFromKey = (key: string): string | null =>
key.startsWith("profile:") ? key.slice("profile:".length) : null;
const refreshOAuthConnection = (
connection: ExecutorServerConnection,
): Effect.Effect<ExecutorServerConnection, never, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const auth = connection.auth;
if (!auth || auth.kind !== "oauth") return connection;
const now = Math.floor(Date.now() / 1000);
if (auth.expiresAt && auth.expiresAt - now > OAUTH_REFRESH_SKEW_SECONDS) return connection;
// Destructure so the narrowed string types survive into the deferred
// `tryPromise` callback (where TS would otherwise re-widen the fields).
const { refreshToken, tokenEndpoint, clientId } = auth;
if (!refreshToken || !tokenEndpoint || !clientId) return connection;
const refreshed = yield* Effect.tryPromise({
try: () => refreshDeviceTokens({ tokenEndpoint, clientId, refreshToken }),
catch: toError,
// On a failed refresh, keep the existing token and let the eventual 401
// surface, better than blocking the command on a transient hiccup.
}).pipe(Effect.option);
if (Option.isNone(refreshed)) return connection;
const next = refreshed.value;
const nextConnection = normalizeExecutorServerConnection({
...connection,
auth: {
kind: "oauth",
accessToken: next.accessToken,
refreshToken: next.refreshToken ?? refreshToken,
...(next.expiresAt ? { expiresAt: next.expiresAt } : {}),
tokenEndpoint,
clientId,
},
});
const profileName = profileNameFromKey(connection.key);
if (profileName) {
yield* upsertCliServerConnectionProfile({
name: profileName,
connection: nextConnection,
makeDefault: false,
}).pipe(Effect.ignore);
}
return nextConnection;
});
const resolveExecutorServerConnection = (
target: ServerTarget,
): Effect.Effect<ExecutorServerConnection, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const requestedResult = yield* resolveRequestedExecutorServerConnection(target);
const active = yield* readActiveLocalServerManifest();
const decision = chooseCliServerConnectionWithActiveLocal({
requested: requestedResult.connection,
source: requestedResult.source,
active,
});
if (decision.kind === "conflict") {
return yield* Effect.fail(
new Error(
[
`A local Executor ${decision.active.kind} is already running at ${decision.active.connection.origin} (pid ${decision.active.pid}).`,
`It owns the current data directory: ${decision.active.dataDir}`,
"Refusing to auto-start another local server against the same database.",
`Use the active server, or stop it before starting ${cliPrefix} daemon run.`,
].join("\n"),
),
);
}
const requested = yield* refreshOAuthConnection(decision.connection);
if (decision.kind === "use-active") return requested;
if (!canAutoStartCliServerConnection(requested)) {
// An authenticated remote connection (oauth device-login, bearer key, or
// basic password): use it directly. The /api/health liveness probe is only
// a gate for the local auto-start decision and isn't necessarily exposed
// by hosted servers, the real API call surfaces any connectivity/auth
// error with proper context.
if (requested.auth) return requested;
if (yield* isServerReachable(requested.origin)) {
return requested;
}
return yield* Effect.fail(
new Error(
[
`Executor server is not reachable at ${requested.origin}.`,
"For hosted Executor, set EXECUTOR_API_KEY to a bearer API key.",
"For local or desktop servers, set EXECUTOR_AUTH_TOKEN to the server's bearer token.",
].join("\n"),
),
);
}
const daemonUrl = yield* ensureDaemon(requested.origin);
// The daemon we just ensured published a manifest carrying its bearer token
// (minted into auth.json). Prefer that authed connection — otherwise the
// next API call hits the now-gated server with no credential and 401s.
const started = yield* readActiveLocalServerManifest().pipe(Effect.orElseSucceed(() => null));
const daemonOrigin = normalizeExecutorServerConnection({ origin: daemonUrl }).origin;
const startedOrigin = started
? normalizeExecutorServerConnection({ origin: started.connection.origin }).origin
: null;
if (started && startedOrigin === daemonOrigin) {
return started.connection;
}
return normalizeExecutorServerConnection({
...requested,
origin: daemonUrl,
});
}).pipe(Effect.mapError(toError));
const stopDaemon = (
baseUrl: string,
): Effect.Effect<void, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const target = yield* resolveDaemonTarget(baseUrl);
const host = canonicalDaemonHost(target.hostname);
const scopeId = target.scopeId;
const record = yield* readDaemonRecord({ hostname: host, port: target.port });
const reachable = yield* isServerReachable(target.baseUrl);
if (!record) {
if (reachable) {
return yield* Effect.fail(
new Error(
[
`Executor is reachable at ${target.baseUrl} but no daemon record exists.`,
"It may not be managed by this CLI process.",
"Stop it from the terminal/session where it was started.",
].join("\n"),
),
);
}
console.log(`No daemon running at ${target.baseUrl}.`);
return;
}
if (!isPidAlive(record.pid)) {
yield* removeDaemonRecord({ hostname: host, port: target.port });
yield* removeDaemonPointer({ hostname: host, scopeId }).pipe(Effect.ignore);
if (reachable) {
return yield* Effect.fail(
new Error(
[
`Daemon record for ${target.baseUrl} points to dead pid ${record.pid}, but endpoint is still reachable.`,
"Refusing to stop an unknown process without ownership metadata.",
].join("\n"),
),
);
}
console.log(
`No daemon running at ${target.baseUrl} (removed stale record for pid ${record.pid}).`,
);
return;
}
console.log(`Stopping daemon at ${target.baseUrl} (pid ${record.pid})...`);
yield* terminatePid(record.pid);
const stopped = yield* waitForUnreachable({
check: isServerReachable(target.baseUrl),
timeoutMs: DAEMON_STOP_TIMEOUT_MS,
intervalMs: DAEMON_BOOT_POLL_MS,
});
if (!stopped) {
return yield* Effect.fail(
new Error(
[
`Daemon at ${target.baseUrl} did not stop within ${DAEMON_STOP_TIMEOUT_MS}ms.`,
"Try terminating the process manually.",
].join("\n"),
),
);
}
yield* removeDaemonRecord({ hostname: host, port: target.port });
yield* removeDaemonPointer({ hostname: host, scopeId }).pipe(Effect.ignore);
yield* removeLocalServerManifestIfOwnedBy({ pid: record.pid }).pipe(Effect.ignore);
console.log(`Daemon stopped at ${target.baseUrl}.`);
}).pipe(Effect.mapError(toError));
type ExecuteCodeOutcome =
| {
readonly status: "completed";
readonly result: unknown;
}
| {
readonly status: "paused";
readonly text: string;
readonly executionId: string | undefined;
readonly approvalUrl: string | undefined;
readonly interaction:
| {
readonly kind: "url" | "form";
readonly message: string;
readonly url?: string;
readonly requestedSchema?: Record<string, unknown>;
}
| undefined;
};
const buildResumeApprovalUrl = (baseUrl: string, executionId: string): string => {
const url = new URL(`/resume/${encodeURIComponent(executionId)}`, baseUrl);
return url.toString();
};
const executeCode = (input: {
target: ServerTarget;
code: string;
}): Effect.Effect<ExecuteCodeResult, Error, FileSystem.FileSystem | PlatformPath.Path> =>
Effect.gen(function* () {
const connection = yield* resolveExecutorServerConnection(input.target);
const client = yield* makeApiClient(connection);
const response = yield* client.executions.execute({
payload: {
code: input.code,
},
});
if (response.status === "paused") {
const executionId = extractExecutionId(response.structured);
return {
connection,
outcome: {
status: "paused" as const,
text: response.text,
executionId,
approvalUrl: executionId
? buildResumeApprovalUrl(connection.origin, executionId)
: undefined,
interaction: extractPausedInteraction(response.structured),
},
};
}
if (response.isError) {
return yield* Effect.fail(new Error(response.text));
}
return {
connection,
outcome: {
status: "completed" as const,
result: extractExecutionResult(response.structured),
},
};
}).pipe(Effect.mapError(toError));
const serverTargetResumeFlag = (
target: ServerTarget,
connection: ExecutorServerConnection,
): string =>
target.serverName
? `--server ${shellQuoteArg(target.serverName)}`
: `--base-url ${shellQuoteArg(target.baseUrl ?? connection.origin)}`;