Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
1656 lines (1539 loc) · 63.7 KB
/
Copy pathmain.ts
File metadata and controls
1656 lines (1539 loc) · 63.7 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
// allow: SIZE_OK - CLI coordinator is pre-existing oversized glue; a full main split needs behavior-locked follow-up coverage.
/**
* Main entry point for the coding agent CLI.
*
* This file handles CLI argument parsing and translates them into
* createAgentSession() options. The SDK does the heavy lifting.
*/
import { existsSync } from "node:fs";
import { join } from "node:path";
import { createInterface } from "node:readline";
import { type ImageContent, modelsAreEqual } from "@earendil-works/pi-ai";
import { setCapabilityOverrides } from "@earendil-works/pi-tui";
import chalk from "chalk";
import { type Args, type Mode, normalizeSessionName, parseArgs, printHelp, resolveSessionRuntime } from "./cli/args.ts";
import {
type AuthCheckResult,
checkProviderAuth,
createAuthCheckModelRuntime,
getProviderCredential,
} from "./cli/auth-check.ts";
import {
type AuthCommand,
AuthCommandError,
getAuthCommandName,
getAuthCommandUsage,
isAuthCommandHelp,
parseAuthCommand,
printAuthCommandHelp,
validateAuthCommandArgs,
} from "./cli/auth-command.ts";
import { movedSessionToContinue } from "./cli/continue-moved.ts";
import { resolveCredentialForPrint } from "./cli/credential-print.ts";
import { chooseCrossProjectAction, confirmSameRepositoryRebind } from "./cli/cross-project-session.ts";
import {
dispatchConfigCommand,
dispatchHostCommand,
dispatchPackageCommand,
dispatchScheduleCommand,
} from "./cli/deferred-commands.ts";
import { processFileArguments } from "./cli/file-processor.ts";
import { resolveHelpExtensionFlags } from "./cli/help-extension-flags.ts";
import { helpFlagsScope, isPlainHelpRequest, resolveHelpProjectTrust } from "./cli/help-fast-path.ts";
import { writeHelpFlagsCache } from "./cli/help-flags-cache.ts";
import { buildInitialMessage } from "./cli/initial-message.ts";
import { listModels } from "./cli/list-models.ts";
import { isModelsDiscoverCommand, runModelsDiscoverCommand } from "./cli/models-command.ts";
import { printPromptSizes } from "./cli/print-prompt-sizes.ts";
import { pipedStdinOptions } from "./cli/piped-stdin-options.ts";
import { exitAfterOutput, printThenExit } from "./cli/print-then-exit.ts";
import { createProjectTrustContext } from "./cli/project-trust.ts";
import { prepareSessionOpening } from "./cli/session-opening.ts";
import {
createStartupLoadingIndicator,
pauseIndicatorDuringPrompts,
shouldShowStartupLoadingIndicator,
} from "./cli/startup-loading-indicator.ts";
import { shouldRunFirstTimeSetup, showFirstTimeSetup, showStartupSelector } from "./cli/startup-ui.ts";
import { resolveToolRuntime, type ToolRuntimeKind } from "./cli/tool-runtime.ts";
import {
APP_NAME,
DISPLAY_VERSION,
ENV_SESSION_DIR,
expandTildePath,
getAgentDir,
getInstallPackageDir,
} from "./config.ts";
import {
applyRetryFallbackProfile,
type CreateAgentSessionRuntimeFactory,
createAgentSessionRuntime,
} from "./core/agent-session-runtime.ts";
import {
type AgentSessionRuntimeDiagnostic,
createAgentSessionFromServices,
createAgentSessionServices,
} from "./core/agent-session-services.ts";
import { formatNoModelsAvailableMessage } from "./core/auth-guidance.ts";
import { AuthStorage, ReadOnlyAuthStorage } from "./core/auth-storage.ts";
import { envValue } from "./core/brand.ts";
import { type CredentialAccountSummary, summarizeCredentialAccounts } from "./core/credential-accounts.ts";
import { exportFromFile } from "./core/export-html/index.ts";
import { ModelUsabilityBudgetError } from "./core/extensions/builtin/compaction/model-usability-budget.ts";
import { resolveMovedPath } from "./core/extensions/builtin/moved-path-guard/resolve.ts";
import type { InlineExtension } from "./core/extensions/types.ts";
import { applyHttpProxySettings, configureHttpDispatcher } from "./core/http-dispatcher.ts";
import { installMemoryReportSignal } from "./core/memory-report/memory-report-write.ts";
import {
getModelNarrowingPatterns,
resolveCliModel,
resolveModelScope,
type ScopedModel,
} from "./core/model-resolver.ts";
import { ModelRuntime } from "./core/model-runtime.ts";
import { markMovedSessions, movedHereSessionToContinue, withMovedSessions } from "./core/moved-sessions.ts";
import { restoreStdout, takeOverStdout } from "./core/output-guard.ts";
import { recordProcessLifetime } from "./core/process-crash-record.ts";
import { type AppMode, presetTrustsProject, resolveProjectTrusted } from "./core/project-trust.ts";
import { resolveResumeTarget } from "./core/resume-target.ts";
import type { CreateAgentSessionOptions } from "./core/sdk.ts";
import {
formatMissingSessionCwdPrompt,
getMissingSessionCwdIssue,
MissingSessionCwdError,
type SessionCwdIssue,
} from "./core/session-cwd.ts";
import { sessionExtensionFlagValues } from "./core/session-extension-flags.ts";
import { assertValidSessionId, SessionManager, sessionFileNameId } from "./core/session-manager.ts";
import { classifySessionRepository, readSessionCwd, rebindSessionFile } from "./core/session-rebind.ts";
import { collectSettingsDiagnosticsWithContext } from "./core/settings-diagnostics.ts";
import { SettingsManager } from "./core/settings-manager.ts";
import { startSubscriptionUsagePolling } from "./core/subscription-limits/usage-poller.ts";
import { type ClampedThinkingSelection, formatThinkingClampWarning } from "./core/thinking-levels.ts";
import { printTimings, recordTiming, resetTimings, time } from "./core/timings.ts";
import { hasTrustRequiringProjectResources, ProjectTrustStore } from "./core/trust-manager.ts";
import { builtInExtensions } from "./extensions/index.ts";
import { getFromSourceRealConfigWarning } from "./from-source-config-guard.ts";
import { legacyPiEditStartupNotice } from "./legacy-pi-edits.ts";
import { runMigrations, showDeprecationWarnings } from "./migrations.ts";
import { initTheme, stopThemeWatcher } from "./modes/interactive/theme/theme.ts";
import { runPrintMode } from "./modes/print-mode.ts";
import { startHostChildReaper } from "./modes/rpc/child-reaper.ts";
import { AUTO_TITLE_SESSIONS_CAPABILITY, parseClientCapabilities } from "./modes/rpc/custom-capability.ts";
import type { PreparableRuntimeFactory, PrepareRuntimeOptions } from "./modes/rpc/host-warm.ts";
import { dispatchInternalSupervisor } from "./modes/rpc/supervisor-route.ts";
import { isLocalPath, normalizePath, resolvePath } from "./utils/paths.ts";
import { readPipedStdin } from "./utils/piped-stdin.ts";
import { cleanupWindowsSelfUpdateQuarantine } from "./utils/windows-self-update.ts";
const EXTENSION_LOAD_FAILURE_HINT = `Hint: Start without extensions using "${APP_NAME} -ne".`;
/**
* Auth problems for a run's diagnostics. Each credential notice appears once per process; with
* `persistSeen` (a run a person reads) it is also recorded as seen, so later runs stay quiet until
* the problem changes (senpi#3486).
*/
export function collectAuthDiagnostics(
authStorage: AuthStorage,
context: string,
options: { persistSeen: boolean },
): AgentSessionRuntimeDiagnostic[] {
return [
...authStorage.drainErrors().map((error) => error.message),
...authStorage.takePendingNotices(options).map((notice) => notice.message),
].map((message) => ({ type: "warning", message: `(${context}, auth storage) ${message}` }));
}
/** The TUI shows auth problems at startup; credential notices are marked seen once shown (senpi#3486). */
export function interactiveAuthNotices(authStorage: AuthStorage): { messages: string[]; markSeen: () => void } {
const pending = authStorage.takePendingNotices({ persistSeen: false });
return {
messages: [
...authStorage.drainErrors().map((error) => error.message),
...pending.map((notice) => notice.message),
],
markSeen: () => authStorage.markNoticesSeen(pending.map((notice) => notice.id)),
};
}
export function collectExtensionLoadDiagnostics(
errors: readonly { path: string; error: string }[],
): AgentSessionRuntimeDiagnostic[] {
return errors.map(({ path, error }) => ({
type: "warning",
message: `Failed to load extension "${path}": ${error}`,
}));
}
function reportDiagnostics(diagnostics: readonly AgentSessionRuntimeDiagnostic[]): void {
for (const diagnostic of diagnostics) {
const color = diagnostic.type === "error" ? chalk.red : diagnostic.type === "warning" ? chalk.yellow : chalk.dim;
const prefix = diagnostic.type === "error" ? "Error: " : diagnostic.type === "warning" ? "Warning: " : "";
console.error(color(`${prefix}${diagnostic.message}`));
}
}
function isTruthyEnvFlag(value: string | undefined): boolean {
if (!value) return false;
return value === "1" || value.toLowerCase() === "true" || value.toLowerCase() === "yes";
}
function resolveAppMode(parsed: Args, stdinIsTTY: boolean, stdoutIsTTY: boolean): AppMode {
if (parsed.mode === "rpc") {
return "rpc";
}
if (parsed.mode === "json") {
return "json";
}
if (parsed.print || !stdinIsTTY || !stdoutIsTTY) {
return "print";
}
return "interactive";
}
function toPrintOutputMode(appMode: AppMode): Exclude<Mode, "rpc"> {
return appMode === "json" ? "json" : "text";
}
/**
* Interactive launches auto-title by default. RPC clients can opt in through
* `auto_title_sessions`; every other non-interactive app mode opts in with
* `--auto-title-sessions`. A per-session `open_session.auto_title`, when present,
* replaces that host-wide decision for that session only. Sessions resumed with
* existing context messages are never retitled, whatever the mode, capability,
* flag, or per-session override.
*/
export function resolveAutoTitleSessions(
appMode: AppMode,
parsed: Args,
hasContextMessages: boolean,
clientCapabilities: readonly string[] = parseClientCapabilities(envValue("RPC_CLIENT_CAPABILITIES")),
sessionAutoTitle?: boolean,
): boolean {
if (hasContextMessages) return false;
if (sessionAutoTitle !== undefined) return sessionAutoTitle;
return (
appMode === "interactive" ||
parsed.autoTitleSessions === true ||
(appMode === "rpc" && clientCapabilities.includes(AUTO_TITLE_SESSIONS_CAPABILITY))
);
}
function isPlainRuntimeMetadataCommand(parsed: Args): boolean {
return (
!parsed.print &&
parsed.mode === undefined &&
(parsed.help === true || parsed.listModels !== undefined || parsed.listTips === true)
);
}
async function runAuthCommand(args: string[]): Promise<boolean> {
if (isAuthCommandHelp(args)) {
printAuthCommandHelp();
return true;
}
let command: AuthCommand | undefined;
try {
command = parseAuthCommand(args);
} catch (error) {
const message = error instanceof AuthCommandError ? error.message : "Failed to parse auth command";
console.error(chalk.red(`Error: ${message}`));
process.exitCode = 1;
return true;
}
if (!command) return false;
const parsed = parseArgs(command.args);
if (parsed.unknownFlags.size > 0) {
const option = parsed.unknownFlags.keys().next().value;
console.error(chalk.red(`Unknown option --${option} for "${getAuthCommandName(command.kind)}".`));
console.error(chalk.dim(`Use "${APP_NAME} --help" or "${getAuthCommandUsage(command.kind)}".`));
process.exitCode = 1;
return true;
}
try {
if (parsed.diagnostics.length > 0) {
throw new AuthCommandError(parsed.diagnostics.map((diagnostic) => diagnostic.message).join("\n"));
}
if (command.kind !== "check") {
const signal = AbortSignal.timeout(15_000);
const modelRuntime = await ModelRuntime.create({ allowModelNetwork: false, signal });
const credential = await resolveCredentialForPrint(
parsed,
modelRuntime,
command.kind,
command.minExpiryMs,
signal,
);
process.stdout.write(`${credential}\n`);
return true;
}
const requestedAuth = validateAuthCommandArgs(parsed, command.kind);
let result: AuthCheckResult;
let credential: string | undefined;
try {
const credentials = command.noRefresh ? new ReadOnlyAuthStorage() : AuthStorage.create();
const modelRuntime = await createAuthCheckModelRuntime(credentials);
result = await checkProviderAuth(parsed, modelRuntime, { refresh: !command.noRefresh });
if (command.credentials && result.status === "ready") {
credential = await getProviderCredential(result.provider, modelRuntime, credentials, {
refresh: !command.noRefresh,
});
if (!credential) {
result = { status: "not_ready", provider: result.provider, reason: "credential_not_available" };
}
}
} catch {
result = {
status: "invalid",
provider: requestedAuth.provider ?? requestedAuth.model!,
reason: "invalid_state",
};
}
let accounts: CredentialAccountSummary[] = [];
if (command.json && result.status !== "invalid") {
try {
const credentials = command.noRefresh ? new ReadOnlyAuthStorage() : AuthStorage.create();
accounts = await summarizeCredentialAccounts(result.provider, await credentials.read(result.provider));
} catch {
// Account enrichment must never turn a readable auth state into a failure.
}
}
const output = command.json
? JSON.stringify({ ...result, accounts, ...(credential ? { credentials: credential } : {}) })
: (credential ?? result.status);
process.stdout.write(`${output}\n`);
process.exitCode = result.status === "ready" ? 0 : result.status === "not_ready" ? 1 : 2;
} catch (error) {
const message = error instanceof AuthCommandError ? error.message : "Failed to resolve credential";
console.error(chalk.red(`Error: ${message}`));
process.exitCode = command.kind === "check" ? 2 : 1;
}
return true;
}
async function prepareInitialMessage(
parsed: Args,
autoResizeImages: boolean,
stdinContent?: string,
): Promise<{
initialMessage?: string;
initialImages?: ImageContent[];
initialTitlePrompt?: string;
}> {
if (parsed.fileArgs.length === 0) {
return buildInitialMessage({ parsed, stdinContent });
}
const { text, images } = await processFileArguments(parsed.fileArgs, { autoResizeImages });
return buildInitialMessage({
parsed,
fileText: text,
fileImages: images,
stdinContent,
});
}
/** Result from resolving a session argument */
type ResolvedSession =
| { type: "path"; path: string } // Direct file path
| { type: "local"; path: string } // Found in current project
| { type: "global"; path: string; cwd: string } // Found in different project
| { type: "not_found"; arg: string }; // Not found anywhere
/**
* Resolve a session argument to a file path.
* If it looks like a path, use as-is. Otherwise try to match as session ID prefix.
*/
async function findLocalSessionByExactId(
sessionId: string,
cwd: string,
sessionDir?: string,
): Promise<{ type: "local"; path: string } | undefined> {
const localSessions = sessionDir ? await SessionManager.listAll(sessionDir) : await SessionManager.list(cwd);
// The id a file name carries counts too: a session named after it must not get a second file under that id.
const localMatch =
localSessions.find((s) => s.id === sessionId) ??
localSessions.find((s) => sessionFileNameId(s.path) === sessionId);
return localMatch ? { type: "local", path: localMatch.path } : undefined;
}
/** Header id first, then the id the file name carries (what a resume hint printed), then an id prefix. */
function findSessionByIdOrFileName<T extends { id: string; path: string }>(sessions: T[], arg: string): T | undefined {
return (
sessions.find((s) => s.id === arg) ??
sessions.find((s) => sessionFileNameId(s.path) === arg) ??
sessions.find((s) => s.id.startsWith(arg))
);
}
async function resolveSessionPath(sessionArg: string, cwd: string, sessionDir?: string): Promise<ResolvedSession> {
// If it looks like a file path, resolve it before handing it to the session manager.
if (sessionArg.includes("/") || sessionArg.includes("\\") || sessionArg.endsWith(".jsonl")) {
return { type: "path", path: resolvePath(sessionArg, cwd) };
}
// Try to match as session ID in current project first
const localSessions = await SessionManager.list(cwd, sessionDir);
const localMatch = findSessionByIdOrFileName(localSessions, sessionArg);
if (localMatch) {
return { type: "local", path: localMatch.path };
}
// Try global search across all projects
const allSessions = await SessionManager.listAll(sessionDir);
const globalMatch = findSessionByIdOrFileName(allSessions, sessionArg);
if (globalMatch) {
return { type: "global", path: globalMatch.path, cwd: globalMatch.cwd };
}
// Not found anywhere
return { type: "not_found", arg: sessionArg };
}
/**
* Prompt user for yes/no confirmation.
* Resolves false on stdin EOF (Ctrl+D, closed pipe): without the close handler a
* readline question never settles once the input stream ends, hanging the process.
*/
export async function promptConfirm(message: string): Promise<boolean> {
return new Promise((resolve) => {
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
let settled = false;
const settle = (result: boolean): void => {
if (settled) return;
settled = true;
resolve(result);
};
rl.question(`${message} [y/N] `, (answer) => {
const normalized = answer.trim().toLowerCase();
settle(normalized === "y" || normalized === "yes");
rl.close();
});
rl.once("close", () => settle(false));
});
}
function validateForkFlags(parsed: Args): void {
if (!parsed.fork) return;
const conflictingFlags = [
parsed.session ? "--session" : undefined,
parsed.continue ? "--continue" : undefined,
parsed.resume ? "--resume" : undefined,
parsed.noSession ? "--no-session" : undefined,
].filter((flag): flag is string => flag !== undefined);
if (conflictingFlags.length > 0) {
console.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(", ")}`));
process.exit(1);
}
}
function validateRebindFlags(parsed: Args): void {
if (!parsed.rebind) return;
const conflictingFlags = [
parsed.session ? "--session" : undefined,
parsed.fork ? "--fork" : undefined,
parsed.continue ? "--continue" : undefined,
parsed.resume ? "--resume" : undefined,
parsed.noSession ? "--no-session" : undefined,
parsed.sessionId !== undefined ? "--session-id" : undefined,
].filter((flag): flag is string => flag !== undefined);
if (conflictingFlags.length > 0) {
console.error(chalk.red(`Error: --rebind cannot be combined with ${conflictingFlags.join(", ")}`));
process.exit(1);
}
}
function validateSessionIdFlags(parsed: Args): void {
if (parsed.sessionId === undefined) return;
const conflictingFlags = [
parsed.session ? "--session" : undefined,
parsed.continue ? "--continue" : undefined,
parsed.resume ? "--resume" : undefined,
].filter((flag): flag is string => flag !== undefined);
if (conflictingFlags.length > 0) {
console.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(", ")}`));
process.exit(1);
}
try {
assertValidSessionId(parsed.sessionId);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(chalk.red(`Error: ${message}`));
process.exit(1);
}
}
function openSessionOrExit(path: string, sessionDir?: string): SessionManager {
try {
return SessionManager.open(path, sessionDir);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(chalk.red(`Error: ${message}`));
process.exit(1);
}
}
function forkSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string, sessionId?: string): SessionManager {
try {
return SessionManager.forkFrom(sourcePath, cwd, sessionDir, { id: sessionId });
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(chalk.red(`Error: ${message}`));
process.exit(1);
}
}
async function rebindSessionOrExit(sourcePath: string, cwd: string, sessionDir?: string): Promise<SessionManager> {
try {
const reboundPath = await rebindSessionFile(sourcePath, cwd, sessionDir);
console.log(chalk.dim(`Session moved to ${cwd}`));
return SessionManager.open(reboundPath, sessionDir);
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
console.error(chalk.red(`Error: ${message}`));
process.exit(1);
}
}
async function sessionCwdOrUndefined(sessionFile: string): Promise<string | undefined> {
try {
return await readSessionCwd(sessionFile);
} catch {
return undefined;
}
}
export async function createSessionManager(
parsed: Args,
cwd: string,
sessionDir: string | undefined,
settingsManager: SettingsManager,
appMode: AppMode,
): Promise<SessionManager> {
if (parsed.spawnedBy && (parsed.session || parsed.resume || parsed.continue || parsed.fork || parsed.rebind)) {
console.error(chalk.yellow("Warning: --spawned-by is ignored when resuming or forking a session."));
}
if (parsed.noSession || parsed.help || parsed.listModels !== undefined || parsed.listTips) {
return SessionManager.inMemory(cwd, { id: parsed.sessionId, spawnedBy: parsed.spawnedBy });
}
if (parsed.fork) {
if (parsed.sessionId) {
const existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);
if (existingTarget) {
console.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));
process.exit(1);
}
}
const resolved = await resolveSessionPath(parsed.fork, cwd, sessionDir);
switch (resolved.type) {
case "path":
case "local":
case "global":
return forkSessionOrExit(resolved.path, cwd, sessionDir, parsed.sessionId);
case "not_found":
console.error(chalk.red(`No session found matching '${resolved.arg}'`));
process.exit(1);
}
}
if (parsed.rebind) {
const resolved = await resolveSessionPath(parsed.rebind, cwd, sessionDir);
if (resolved.type === "not_found") {
console.error(chalk.red(`No session found matching '${resolved.arg}'`));
process.exit(1);
}
const sessionCwd = resolved.type === "global" ? resolved.cwd : await sessionCwdOrUndefined(resolved.path);
if (resolved.type === "local" || sessionCwd === undefined || resolvePath(sessionCwd) === resolvePath(cwd)) {
return openSessionOrExit(resolved.path, sessionDir);
}
if ((await classifySessionRepository(resolved.path, sessionCwd, cwd)) === "different") {
console.error(
chalk.red(
`Refusing to rebind: ${cwd} is a different git repository than ${sessionCwd}. Use --fork '${parsed.rebind}' to copy the session into this directory instead.`,
),
);
process.exit(1);
}
return rebindSessionOrExit(resolved.path, cwd, sessionDir);
}
if (parsed.session) {
const resolved = await resolveSessionPath(parsed.session, cwd, sessionDir);
switch (resolved.type) {
case "path":
case "local":
return openSessionOrExit(resolved.path, sessionDir);
case "global": {
// Recorded under a folder the OmO desktop moved here: this folder's own session (senpi#2990).
if (resolved.cwd !== "" && resolvePath(resolveMovedPath(resolved.cwd)) === resolvePath(cwd))
return openSessionOrExit(resolved.path, sessionDir);
// The confirmation blocks on readline, which only an interactive session can
// answer. Print, JSON, and RPC runs reach here with a TTY attached
// too (`-p` from a terminal), where the question hangs the process or resolves
// as "no" on stdin EOF, so they get the exact commands and a non-zero exit.
const action = await chooseCrossProjectAction({
sessionArg: parsed.session,
sessionCwd: resolved.cwd,
cwd,
match: await classifySessionRepository(resolved.path, resolved.cwd, cwd),
interactive: appMode === "interactive",
confirm: promptConfirm,
out: (line) => console.log(line),
err: (line) => console.error(line),
});
if (action === "rebind") return rebindSessionOrExit(resolved.path, cwd, sessionDir);
if (action === "fork") return forkSessionOrExit(resolved.path, cwd, sessionDir);
if (action === "abort") console.log(chalk.dim("Aborted."));
return process.exit(action === "abort" ? 0 : 1);
}
case "not_found":
console.error(chalk.red(`No session found matching '${resolved.arg}'`));
process.exit(1);
}
}
if (parsed.resume) {
try {
const { selectSession } = await import("./cli/session-picker.ts");
const movedOptions = sessionDir === undefined ? {} : { sessionDir };
const selectedPath = await selectSession(
(onProgress) => withMovedSessions(SessionManager.list(cwd, sessionDir, onProgress), cwd, movedOptions),
async (onProgress) => markMovedSessions(await SessionManager.listAll(sessionDir, onProgress), cwd),
settingsManager,
);
if (!selectedPath) {
console.log(chalk.dim("No session selected"));
process.exit(0);
}
const target = await resolveResumeTarget({
sessionPath: selectedPath,
cwd,
...movedOptions,
confirm: (selectedCwd) => {
console.log(chalk.yellow(`Session found in different project: ${selectedCwd}`));
return confirmSameRepositoryRebind({
sessionArg: selectedPath,
cwd,
confirm: promptConfirm,
out: (line) => console.log(line),
});
},
}).catch((error: unknown) => {
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
return process.exit(1);
});
if (target.rebound) console.log(chalk.dim(`Session moved to ${cwd}`));
return SessionManager.open(target.path, sessionDir);
} finally {
stopThemeWatcher();
}
}
if (parsed.continue) {
// A shared session dir matches sessions the OmO desktop moved here in continueRecent. In the default per-folder
// layout they sit in the old folder's dir: continue the newest of those and the folder's own, in place (senpi#2990).
const movedHere = sessionDir === undefined ? await movedHereSessionToContinue(cwd) : undefined;
if (movedHere !== undefined) return SessionManager.open(movedHere, sessionDir);
const recent = SessionManager.continueRecent(cwd, sessionDir);
const recentFile = recent.getSessionFile();
if (recentFile !== undefined && existsSync(recentFile)) return recent;
const movedChoice = await movedSessionToContinue({
cwd,
...(sessionDir === undefined ? {} : { sessionDir }),
interactive: appMode === "interactive",
confirm: promptConfirm,
out: (line) => console.log(line),
err: (line) => console.error(line),
});
return movedChoice === undefined ? recent : rebindSessionOrExit(movedChoice, cwd, sessionDir);
}
if (parsed.sessionId) {
const existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, sessionDir);
if (existingSession) {
if (parsed.spawnedBy)
console.error(chalk.yellow("Warning: --spawned-by is ignored when resuming an existing session."));
return SessionManager.open(existingSession.path, sessionDir);
}
console.error(
chalk.yellow(
`Warning: No project session found with id '${parsed.sessionId}'; creating a new session with that id.`,
),
);
}
return SessionManager.create(cwd, sessionDir, { id: parsed.sessionId, spawnedBy: parsed.spawnedBy });
}
function buildSessionOptions(
parsed: Args,
scopedModels: ScopedModel[],
hasExistingSession: boolean,
modelRuntime: ModelRuntime,
settingsManager: SettingsManager,
): {
options: CreateAgentSessionOptions;
cliThinkingFromModel: boolean;
diagnostics: AgentSessionRuntimeDiagnostic[];
} {
const options: CreateAgentSessionOptions = {};
const diagnostics: AgentSessionRuntimeDiagnostic[] = [];
let cliThinkingFromModel = false;
// Model from CLI
// - supports --provider <name> --model <pattern>
// - supports --model <provider>/<pattern>
if (parsed.provider && !parsed.model) {
diagnostics.push({
type: "error",
message: `--provider requires --model (for example: --provider ${parsed.provider} --model <pattern>)`,
});
}
if (parsed.model) {
const resolved = resolveCliModel({
cliProvider: parsed.provider,
cliModel: parsed.model,
cliThinking: parsed.thinking,
modelRuntime,
});
if (resolved.warning) {
diagnostics.push({ type: "warning", message: resolved.warning });
}
if (resolved.error) {
diagnostics.push({ type: "error", message: resolved.error, code: "model_unresolved" });
}
if (resolved.model) {
options.model = resolved.model;
options.serviceTier = resolved.serviceTier;
options.initialModelProvenance = "cli";
// Allow "--model <pattern>:<thinking>" as a shorthand.
// Explicit --thinking still takes precedence (applied later).
if (!parsed.thinking && resolved.thinkingLevel) {
options.thinkingLevel = resolved.thinkingLevel;
options.thinkingSelection = resolved.thinkingSelection;
cliThinkingFromModel = true;
}
}
}
if (!options.model && scopedModels.length > 0 && !hasExistingSession) {
// Check if saved default is in scoped models - use it if so, otherwise first scoped model
const savedProvider = settingsManager.getDefaultProvider();
const savedModelId = settingsManager.getDefaultModel();
const savedModel = savedProvider && savedModelId ? modelRuntime.getModel(savedProvider, savedModelId) : undefined;
const savedInScope = savedModel ? scopedModels.find((sm) => modelsAreEqual(sm.model, savedModel)) : undefined;
if (savedInScope) {
options.model = savedInScope.model;
options.initialModelProvenance = "scoped";
// Use thinking level from scoped model config if explicitly set
if (!parsed.thinking && savedInScope.thinkingLevel) {
options.thinkingLevel = savedInScope.thinkingLevel;
options.thinkingSelection = savedInScope.thinkingSelection;
}
} else {
options.model = scopedModels[0].model;
options.initialModelProvenance = "scoped";
// Use thinking level from first scoped model if explicitly set
if (!parsed.thinking && scopedModels[0].thinkingLevel) {
options.thinkingLevel = scopedModels[0].thinkingLevel;
options.thinkingSelection = scopedModels[0].thinkingSelection;
}
}
}
// Thinking level from CLI (takes precedence over scoped model thinking levels set above)
if (parsed.thinking) {
options.thinkingLevel = parsed.thinking;
options.thinkingSelection = { level: parsed.thinking, source: "explicit" };
}
// Scoped models for Ctrl+P cycling
// Keep thinking level undefined when not explicitly set in the model pattern.
// Undefined means "inherit current session thinking level" during cycling.
if (scopedModels.length > 0) {
options.scopedModels = scopedModels.map((sm) => ({
model: sm.model,
thinkingLevel: sm.thinkingLevel,
thinkingSelection: sm.thinkingSelection,
serviceTier: sm.serviceTier,
}));
}
// API key from CLI - set as a non-persistent runtime override
// (handled by caller before createAgentSession)
// Tools
if (parsed.noTools) {
options.noTools = "all";
} else if (parsed.noBuiltinTools) {
options.noTools = "builtin";
}
if (parsed.tools) {
options.tools = [...parsed.tools];
}
if (parsed.excludeTools) {
options.excludeTools = [...parsed.excludeTools];
}
return { options, cliThinkingFromModel, diagnostics };
}
function resolveCliPaths(cwd: string, paths: string[] | undefined): string[] | undefined {
return paths?.map((value) => (isLocalPath(value) ? resolvePath(value, cwd) : value));
}
async function promptForMissingSessionCwd(
issue: SessionCwdIssue,
settingsManager: SettingsManager,
): Promise<string | undefined> {
return showStartupSelector(settingsManager, formatMissingSessionCwdPrompt(issue), [
{ label: "Continue", value: issue.fallbackCwd },
{ label: "Cancel", value: undefined },
]);
}
export interface MainOptions {
extensionFactories?: InlineExtension[];
}
/**
* Supply grok-night as a non-persistent fallback until a user explicitly chooses
* a theme. Existing settings are always returned first.
*/
export function applyGrokNeoThemeFallback(settingsManager: SettingsManager): void {
if (settingsManager.getThemeSetting() !== undefined) return;
const getThemeSetting = settingsManager.getThemeSetting.bind(settingsManager);
const setTheme = settingsManager.setTheme.bind(settingsManager);
let fallbackActive = true;
settingsManager.getThemeSetting = () => getThemeSetting() ?? (fallbackActive ? "grok-night" : undefined);
settingsManager.setTheme = (theme) => {
fallbackActive = false;
setTheme(theme);
};
}
export interface CliRuntimeConfiguration {
parsed: Args;
cwd: string;
agentDir: string;
appMode: AppMode;
/** Resolved `--tool-runtime` (flag, then env); absent means `in-process`. A worker isolate never re-reads env. */
toolRuntime?: ToolRuntimeKind;
}
/** Fixed launch data is cloneable; UI callbacks and extension factories stay in their isolate. */
export function createCliRuntimeFactory(
configuration: CliRuntimeConfiguration,
local: {
extensionFactories?: InlineExtension[];
startupSettingsManager?: SettingsManager;
startupLoadingIndicator?: ReturnType<typeof createStartupLoadingIndicator>;
/**
* One model runtime for every session this factory creates. A shared host's
* sessions all live in one agent dir, so they would each build an identical
* runtime - ~100 ms of loop CPU per open that, concurrent, every open pays
* N times over (senpi#1844). Provider registration is keyed by id and
* merges, so replaying each session's extension providers into one runtime
* is idempotent.
*/
modelRuntime?: ModelRuntime;
} = {},
): PreparableRuntimeFactory {
const { parsed, cwd, agentDir, appMode, toolRuntime } = configuration;
const extensionFactories = local.extensionFactories ?? builtInExtensions;
const startupSettingsManager = local.startupSettingsManager ?? SettingsManager.create(cwd, agentDir);
const startupLoadingIndicator =
local.startupLoadingIndicator ??
createStartupLoadingIndicator({
writer: () => {},
isTTY: false,
label: `Loading ${APP_NAME}`,
});
const trustStore = new ProjectTrustStore(agentDir);
const projectTrustByCwd = new Map<string, boolean>();
const trustPromptMode: AppMode =
parsed.help || parsed.listModels !== undefined || parsed.listTips ? "print" : appMode;
const resolvedExtensionPaths = resolveCliPaths(cwd, parsed.extensions);
const resolvedSkillPaths = resolveCliPaths(cwd, parsed.skills);
const resolvedPromptTemplatePaths = resolveCliPaths(cwd, parsed.promptTemplates);
const resolvedThemePaths = resolveCliPaths(cwd, parsed.themes);
// The cwd-bound services one session needs, built alone: the runtime factory below builds them
// before its session, and a multi-session host's `warm` builds and drops them (senpi#2314).
const createServices = async ({
cwd,
agentDir,
projectTrustContext,
launchProfile,
mcpRegistry,
isInitialRuntime,
}: Omit<Parameters<CreateAgentSessionRuntimeFactory>[0], "sessionManager" | "sessionStartEvent"> & {
isInitialRuntime: boolean;
}) => {
const projectTrustDiagnostics: AgentSessionRuntimeDiagnostic[] = [];
const cachedProjectTrust = projectTrustByCwd.get(cwd);
const hasTrustRequiringResources = hasTrustRequiringProjectResources(cwd);
// A full-access session trusts its project without asking, for that session only: nothing is
// cached here or saved to the trust store, and a saved "do not trust" still wins (#2465).
const fullAccessTrust =
presetTrustsProject(
sessionExtensionFlagValues(parsed.unknownFlags, launchProfile).get("permission-preset"),
(startupSettingsManager.getGlobalSettings() as { readonly permissionPreset?: unknown }).permissionPreset,
) && trustStore.get(cwd) !== false;
const shouldResolveProjectTrust =
parsed.projectTrustOverride === undefined &&
cachedProjectTrust === undefined &&
!fullAccessTrust &&
hasTrustRequiringResources;
const projectTrusted = shouldResolveProjectTrust
? false
: (cachedProjectTrust ??
parsed.projectTrustOverride ??
(fullAccessTrust || !hasTrustRequiringResources || trustStore.get(cwd) === true));
// Trusted only because of Full access (resources need trust and nothing else granted it): leaving
// Full access withdraws it (#3420 review T5).
const trustFromFullAccess =
fullAccessTrust &&
hasTrustRequiringResources &&
cachedProjectTrust === undefined &&
parsed.projectTrustOverride === undefined &&
trustStore.get(cwd) !== true;
const runtimeSettingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted, trustFromFullAccess });
// The opener's per-session fallback policy is an in-memory override: never saved, never shared.
if (launchProfile?.retryFallback) applyRetryFallbackProfile(runtimeSettingsManager, launchProfile.retryFallback);
const services = await createAgentSessionServices({
cwd,
agentDir,
settingsManager: runtimeSettingsManager,
...(local.modelRuntime === undefined ? {} : { modelRuntime: local.modelRuntime }),
mcpRegistry,
modelRuntimeSignal: AbortSignal.timeout(15_000),
extensionFlagValues: sessionExtensionFlagValues(parsed.unknownFlags, launchProfile),
resourceLoaderReloadOptions: shouldResolveProjectTrust
? {
resolveProjectTrust: async ({ extensionsResult }) => {
const trusted = await resolveProjectTrusted({
cwd,
trustStore,
trustOverride: parsed.projectTrustOverride,
defaultProjectTrust: startupSettingsManager.getDefaultProjectTrust(),
extensionsResult,
projectTrustContext:
projectTrustContext ??
pauseIndicatorDuringPrompts(
createProjectTrustContext({
cwd,
mode: isInitialRuntime ? trustPromptMode : appMode,
settingsManager: startupSettingsManager,
hasUI: isInitialRuntime && trustPromptMode === "interactive",
}),
startupLoadingIndicator,
),
onExtensionError: (message) => projectTrustDiagnostics.push({ type: "warning", message }),
});
projectTrustByCwd.set(cwd, trusted);
return trusted;
},
}
: undefined,
resourceLoaderOptions: {
// Per-session identity reaches the extensions this session loads and stops
// there: it is deliberately NOT merged into `parsed`, so it can never move
// a model, an auth decision or a CLI flag.
sessionKind: launchProfile?.sessionKind,
sessionContext: launchProfile?.sessionContext,
additionalExtensionPaths: resolvedExtensionPaths,
additionalSkillPaths: resolvedSkillPaths,
additionalPromptTemplatePaths: resolvedPromptTemplatePaths,
additionalThemePaths: resolvedThemePaths,
noExtensions: parsed.noExtensions,
noSkills: parsed.noSkills,
noPromptTemplates: parsed.noPromptTemplates,
noThemes: parsed.noThemes,
noContextFiles: parsed.noContextFiles,
systemPrompt: parsed.systemPrompt,
appendSystemPrompt: parsed.appendSystemPrompt,
extensionFactories,
},
});
return { services, projectTrustDiagnostics };
};
const createRuntime: CreateAgentSessionRuntimeFactory = async ({
cwd,
agentDir,
sessionManager,
sessionStartEvent,
projectTrustContext,
launchProfile,
mcpRegistry,
}) => {
const isInitialRuntime = sessionStartEvent === undefined;
const markSwitch = (label: string): void => {
if (sessionStartEvent?.reason === "resume") time(label, "switch");
};
const { services, projectTrustDiagnostics } = await createServices({
cwd,