-
Notifications
You must be signed in to change notification settings - Fork 491
Expand file tree
/
Copy pathsdk.ts
More file actions
1709 lines (1587 loc) · 61 KB
/
sdk.ts
File metadata and controls
1709 lines (1587 loc) · 61 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
import {
Agent,
type AgentEvent,
type AgentMessage,
type AgentTool,
INTENT_FIELD,
type ThinkingLevel,
} from "@oh-my-pi/pi-agent-core";
import type { Message, Model } from "@oh-my-pi/pi-ai";
import {
getOpenAICodexTransportDetails,
prewarmOpenAICodexResponses,
} from "@oh-my-pi/pi-ai/providers/openai-codex-responses";
import type { Component } from "@oh-my-pi/pi-tui";
import {
$env,
$flag,
getAgentDbPath,
getAgentDir,
getProjectDir,
logger,
postmortem,
prompt,
Snowflake,
} from "@oh-my-pi/pi-utils";
import chalk from "chalk";
import { AsyncJobManager, isBackgroundJobSupportEnabled } from "./async";
import { createAutoresearchExtension } from "./autoresearch";
import type { Rule } from "./capability/rule";
import { ModelRegistry } from "./config/model-registry";
import { formatModelString, parseModelPattern, parseModelString, resolveModelRoleValue } from "./config/model-resolver";
import { loadPromptTemplates as loadPromptTemplatesInternal, type PromptTemplate } from "./config/prompt-templates";
import { Settings, type SkillsSettings } from "./config/settings";
import { CursorExecHandlers } from "./cursor";
import "./discovery";
import { resolveConfigValue } from "./config/resolve-config-value";
import { initializeWithSettings } from "./discovery";
import {
type CustomCommandsLoadResult,
type LoadedCustomCommand,
loadCustomCommands as loadCustomCommandsInternal,
} from "./extensibility/custom-commands";
import { discoverAndLoadCustomTools } from "./extensibility/custom-tools";
import type { CustomTool, CustomToolContext, CustomToolSessionEvent } from "./extensibility/custom-tools/types";
import { CustomToolAdapter } from "./extensibility/custom-tools/wrapper";
import {
discoverAndLoadExtensions,
type ExtensionContext,
type ExtensionFactory,
ExtensionRunner,
ExtensionToolWrapper,
type ExtensionUIContext,
type LoadExtensionsResult,
type ToolDefinition,
wrapRegisteredTools,
} from "./extensibility/extensions";
import { loadSkills as loadSkillsInternal, type Skill, type SkillWarning } from "./extensibility/skills";
import { type FileSlashCommand, loadSlashCommands as loadSlashCommandsInternal } from "./extensibility/slash-commands";
import {
AgentProtocolHandler,
ArtifactProtocolHandler,
InternalUrlRouter,
JobsProtocolHandler,
LocalProtocolHandler,
McpProtocolHandler,
MemoryProtocolHandler,
PiProtocolHandler,
RuleProtocolHandler,
SkillProtocolHandler,
} from "./internal-urls";
import { disposeAllKernelSessions, disposeKernelSessionsByOwner } from "./ipy/executor";
import { LSP_STARTUP_EVENT_CHANNEL, type LspStartupEvent } from "./lsp/startup-events";
import { discoverAndLoadMCPTools, type MCPManager, type MCPToolsLoadResult } from "./mcp";
import {
collectDiscoverableMCPTools,
formatDiscoverableMCPToolServerSummary,
selectDiscoverableMCPToolNamesByServer,
summarizeDiscoverableMCPTools,
} from "./mcp/discoverable-tool-metadata";
import { buildMemoryToolDeveloperInstructions, getMemoryRoot, startMemoryStartupTask } from "./memories";
import asyncResultTemplate from "./prompts/tools/async-result.md" with { type: "text" };
import { AgentRegistry, MAIN_AGENT_ID } from "./registry/agent-registry";
import { RuntimeResourceLoader } from "./runtime/resource-loader";
import {
collectEnvSecrets,
deobfuscateSessionContext,
loadSecrets,
obfuscateMessages,
SecretObfuscator,
} from "./secrets";
import { AgentSession } from "./session/agent-session";
import { AuthStorage } from "./session/auth-storage";
import { convertToLlm } from "./session/messages";
import { SessionManager } from "./session/session-manager";
import { closeAllConnections } from "./ssh/connection-manager";
import { unmountAll } from "./ssh/sshfs-mount";
import {
buildSystemPrompt as buildSystemPromptInternal,
buildSystemPromptToolMetadata,
loadProjectContextFiles as loadContextFilesInternal,
} from "./system-prompt";
import { AgentOutputManager } from "./task/output-manager";
import { parseThinkingLevel, resolveThinkingLevelForModel, toReasoningEffort } from "./thinking";
import {
BashTool,
BUILTIN_TOOLS,
createTools,
discoverStartupLspServers,
EditTool,
FindTool,
getSearchTools,
HIDDEN_TOOLS,
isSearchProviderPreference,
type LspStartupServerInfo,
loadSshTool,
PythonTool,
ReadTool,
ResolveTool,
renderSearchToolBm25Description,
SearchTool,
setPreferredImageProvider,
setPreferredSearchProvider,
type Tool,
type ToolSession,
WebSearchTool,
WriteTool,
warmupLspServers,
} from "./tools";
import { ToolContextStore } from "./tools/context";
import { getImageGenTools } from "./tools/image-gen";
import { wrapToolWithMetaNotice } from "./tools/output-meta";
import { queueResolveHandler } from "./tools/resolve";
import { EventBus } from "./utils/event-bus";
import { buildNamedToolChoice } from "./utils/tool-choice";
// Types
export interface CreateAgentSessionOptions {
/** Working directory for project-local discovery. Default: getProjectDir() */
cwd?: string;
/** Global config directory. Default: ~/.omp/agent */
agentDir?: string;
/** Spawns to allow. Default: "*" */
spawns?: string;
/** Auth storage for credentials. Default: discoverAuthStorage(agentDir) */
authStorage?: AuthStorage;
/** Model registry. Default: discoverModels(authStorage, agentDir) */
modelRegistry?: ModelRegistry;
/** Model to use. Default: from settings, else first available */
model?: Model;
/** Raw model pattern string (e.g. from --model CLI flag) to resolve after extensions load.
* Used when model lookup is deferred because extension-provided models aren't registered yet. */
modelPattern?: string;
/** Thinking selector. Default: from settings, else unset */
thinkingLevel?: ThinkingLevel;
/** Models available for cycling (Ctrl+P in interactive mode) */
scopedModels?: Array<{ model: Model; thinkingLevel?: ThinkingLevel }>;
/** System prompt. String replaces default, function receives default and returns final. */
systemPrompt?: string | ((defaultPrompt: string) => string);
/** Optional provider-facing session identifier for prompt caches and sticky auth selection.
* Keeps persisted session files isolated while reusing provider-side caches. */
providerSessionId?: string;
/** Custom tools to register (in addition to built-in tools). Accepts both CustomTool and ToolDefinition. */
customTools?: (CustomTool | ToolDefinition)[];
/** Inline extensions (merged with discovery). */
extensions?: ExtensionFactory[];
/** Additional extension paths to load (merged with discovery). */
additionalExtensionPaths?: string[];
/** Disable extension discovery (explicit paths still load). */
disableExtensionDiscovery?: boolean;
/**
* Pre-loaded extensions (skips file discovery).
* @internal Used by CLI when extensions are loaded early to parse custom flags.
*/
preloadedExtensions?: LoadExtensionsResult;
/** Shared event bus for tool/extension communication. Default: creates new bus. */
eventBus?: EventBus;
/** Skills. Default: discovered from multiple locations */
skills?: Skill[];
/** Rules. Default: discovered from multiple locations */
rules?: Rule[];
/** Context files (AGENTS.md content). Default: discovered walking up from cwd */
contextFiles?: Array<{ path: string; content: string }>;
/** Prompt templates. Default: discovered from cwd/.omp/prompts/ + agentDir/prompts/ */
promptTemplates?: PromptTemplate[];
/** File-based slash commands. Default: discovered from commands/ directories */
slashCommands?: FileSlashCommand[];
/** Enable MCP server discovery from .mcp.json files. Default: true */
enableMCP?: boolean;
/** Existing MCP manager to reuse (skips discovery, propagates to toolSession). */
mcpManager?: MCPManager;
/** Enable LSP integration (tool, formatting, diagnostics, warmup). Default: true */
enableLsp?: boolean;
/** Skip Python kernel availability check and prelude warmup */
skipPythonPreflight?: boolean;
/** Force Python prelude warmup even when test env would normally skip it */
forcePythonWarmup?: boolean;
/** Tool names explicitly requested (enables disabled-by-default tools) */
toolNames?: string[];
/** Output schema for structured completion (subagents) */
outputSchema?: unknown;
/** Whether to include the yield tool by default */
requireYieldTool?: boolean;
/** Task recursion depth (for subagent sessions). Default: 0 */
taskDepth?: number;
/** Pre-allocated agent identity for IRC routing. Default: "0-Main" for top-level, parentTaskPrefix-derived for sub. */
agentId?: string;
/** Display name for the agent in IRC. Default: "main" or "sub". */
agentDisplayName?: string;
/** Optional shared agent registry for IRC routing. Default: AgentRegistry.global(). */
agentRegistry?: AgentRegistry;
/** Parent task ID prefix for nested artifact naming (e.g., "6-Extensions") */
parentTaskPrefix?: string;
/** Session manager. Default: session stored under the configured agentDir sessions root */
sessionManager?: SessionManager;
/** Settings instance. Default: Settings.init({ cwd, agentDir }) */
settings?: Settings;
/** Whether UI is available (enables interactive tools like ask). Default: false */
hasUI?: boolean;
}
/** Result from createAgentSession */
export interface CreateAgentSessionResult {
/** The created session */
session: AgentSession;
/** Extensions result (loaded extensions + runtime) */
extensionsResult: LoadExtensionsResult;
/** Update tool UI context (interactive mode) */
setToolUIContext: (uiContext: ExtensionUIContext, hasUI: boolean) => void;
/** MCP manager for server lifecycle management (undefined if MCP disabled) */
mcpManager?: MCPManager;
/** Warning if session was restored with a different model than saved */
modelFallbackMessage?: string;
/** LSP servers detected for startup; warmup may continue in the background */
lspServers?: LspStartupServerInfo[];
/** Shared event bus for tool/extension communication */
eventBus: EventBus;
}
// Re-exports
export type { PromptTemplate } from "./config/prompt-templates";
export { Settings, type SkillsSettings } from "./config/settings";
export type { CustomCommand, CustomCommandFactory } from "./extensibility/custom-commands/types";
export type { CustomTool, CustomToolFactory } from "./extensibility/custom-tools/types";
export type * from "./extensibility/extensions";
export type { Skill } from "./extensibility/skills";
export type { FileSlashCommand } from "./extensibility/slash-commands";
export type { MCPManager, MCPServerConfig, MCPServerConnection, MCPToolsLoadResult } from "./mcp";
export type { Tool } from "./tools";
export {
// Individual tool classes (for custom usage)
BashTool,
// Tool classes and factories
BUILTIN_TOOLS,
createTools,
EditTool,
FindTool,
HIDDEN_TOOLS,
loadSshTool,
PythonTool,
ReadTool,
ResolveTool,
SearchTool,
type ToolSession,
WebSearchTool,
WriteTool,
};
// Helper Functions
function getDefaultAgentDir(): string {
return getAgentDir();
}
// Discovery Functions
/**
* Create an AuthStorage instance with fallback support.
* Reads from primary path first, then falls back to legacy paths (.pi, .claude).
*/
export async function discoverAuthStorage(agentDir: string = getDefaultAgentDir()): Promise<AuthStorage> {
const dbPath = getAgentDbPath(agentDir);
logger.debug("discoverAuthStorage", { agentDir, dbPath });
const storage = await AuthStorage.create(dbPath, { configValueResolver: resolveConfigValue });
await storage.reload();
return storage;
}
/**
* Discover extensions from cwd.
*/
export async function discoverExtensions(cwd?: string): Promise<LoadExtensionsResult> {
const resolvedCwd = cwd ?? getProjectDir();
return discoverAndLoadExtensions([], resolvedCwd);
}
/**
* Discover skills from cwd and agentDir.
*/
export async function discoverSkills(
cwd?: string,
_agentDir?: string,
settings?: SkillsSettings,
): Promise<{ skills: Skill[]; warnings: SkillWarning[] }> {
return await loadSkillsInternal({
...settings,
cwd: cwd ?? getProjectDir(),
});
}
/**
* Discover context files (AGENTS.md) walking up from cwd.
* Returns files sorted by depth (farther from cwd first, so closer files appear last/more prominent).
*/
export async function discoverContextFiles(
cwd?: string,
_agentDir?: string,
): Promise<Array<{ path: string; content: string; depth?: number }>> {
return await loadContextFilesInternal({
cwd: cwd ?? getProjectDir(),
});
}
/**
* Discover prompt templates from cwd and agentDir.
*/
export async function discoverPromptTemplates(cwd?: string, agentDir?: string): Promise<PromptTemplate[]> {
return await loadPromptTemplatesInternal({
cwd: cwd ?? getProjectDir(),
agentDir: agentDir ?? getDefaultAgentDir(),
});
}
/**
* Discover file-based slash commands from commands/ directories.
*/
export async function discoverSlashCommands(cwd?: string): Promise<FileSlashCommand[]> {
return loadSlashCommandsInternal({ cwd: cwd ?? getProjectDir() });
}
/**
* Discover custom commands (TypeScript slash commands) from cwd and agentDir.
*/
export async function discoverCustomTSCommands(cwd?: string, agentDir?: string): Promise<CustomCommandsLoadResult> {
const resolvedCwd = cwd ?? getProjectDir();
const resolvedAgentDir = agentDir ?? getDefaultAgentDir();
return loadCustomCommandsInternal({
cwd: resolvedCwd,
agentDir: resolvedAgentDir,
});
}
/**
* Discover MCP servers from .mcp.json files.
* Returns the manager and loaded tools.
*/
export async function discoverMCPServers(cwd?: string): Promise<MCPToolsLoadResult> {
const resolvedCwd = cwd ?? getProjectDir();
return discoverAndLoadMCPTools(resolvedCwd);
}
// API Key Helpers
// System Prompt
export interface BuildSystemPromptOptions {
tools?: Tool[];
skills?: Skill[];
contextFiles?: Array<{ path: string; content: string }>;
cwd?: string;
appendPrompt?: string;
repeatToolDescriptions?: boolean;
}
/**
* Build the default system prompt.
*/
export async function buildSystemPrompt(options: BuildSystemPromptOptions = {}): Promise<string> {
return await buildSystemPromptInternal({
cwd: options.cwd,
skills: options.skills,
contextFiles: options.contextFiles,
appendSystemPrompt: options.appendPrompt,
repeatToolDescriptions: options.repeatToolDescriptions,
});
}
// Internal Helpers
function createCustomToolContext(ctx: ExtensionContext): CustomToolContext {
return {
sessionManager: ctx.sessionManager,
modelRegistry: ctx.modelRegistry,
model: ctx.model,
isIdle: ctx.isIdle,
hasQueuedMessages: ctx.hasPendingMessages,
abort: ctx.abort,
};
}
function isCustomTool(tool: CustomTool | ToolDefinition): tool is CustomTool {
// To distinguish, we mark converted tools with a hidden symbol property.
// If the tool doesn't have this marker, it's a CustomTool that needs conversion.
return !(tool as any).__isToolDefinition;
}
const TOOL_DEFINITION_MARKER = Symbol("__isToolDefinition");
let sshCleanupRegistered = false;
async function cleanupSshResources(): Promise<void> {
const results = await Promise.allSettled([closeAllConnections(), unmountAll()]);
for (const result of results) {
if (result.status === "rejected") {
logger.warn("SSH cleanup failed", { error: String(result.reason) });
}
}
}
function registerSshCleanup(): void {
if (sshCleanupRegistered) return;
sshCleanupRegistered = true;
postmortem.register("ssh-cleanup", cleanupSshResources);
}
let pythonCleanupRegistered = false;
function registerPythonCleanup(): void {
if (pythonCleanupRegistered) return;
pythonCleanupRegistered = true;
postmortem.register("python-cleanup", disposeAllKernelSessions);
}
function customToolToDefinition(tool: CustomTool): ToolDefinition {
const definition: ToolDefinition & { [TOOL_DEFINITION_MARKER]: true } = {
name: tool.name,
label: tool.label,
description: tool.description,
parameters: tool.parameters,
hidden: tool.hidden,
deferrable: tool.deferrable,
mcpServerName: tool.mcpServerName,
mcpToolName: tool.mcpToolName,
execute: (toolCallId, params, signal, onUpdate, ctx) =>
tool.execute(toolCallId, params, onUpdate, createCustomToolContext(ctx), signal),
onSession: tool.onSession ? (event, ctx) => tool.onSession?.(event, createCustomToolContext(ctx)) : undefined,
renderCall: tool.renderCall,
renderResult: tool.renderResult
? (result, options, theme): Component => {
const component = tool.renderResult?.(
result,
{ expanded: options.expanded, isPartial: options.isPartial, spinnerFrame: options.spinnerFrame },
theme,
);
// Return empty component if undefined to match Component type requirement
return component ?? ({ render: () => [] } as unknown as Component);
}
: undefined,
[TOOL_DEFINITION_MARKER]: true,
};
return definition;
}
function createCustomToolsExtension(tools: CustomTool[]): ExtensionFactory {
return api => {
for (const tool of tools) {
api.registerTool(customToolToDefinition(tool));
}
const runOnSession = async (event: CustomToolSessionEvent, ctx: ExtensionContext) => {
for (const tool of tools) {
if (!tool.onSession) continue;
try {
await tool.onSession(event, createCustomToolContext(ctx));
} catch (err) {
logger.warn("Custom tool onSession error", { tool: tool.name, error: String(err) });
}
}
};
api.on("session_start", async (_event, ctx) =>
runOnSession({ reason: "start", previousSessionFile: undefined }, ctx),
);
api.on("session_switch", async (event, ctx) =>
runOnSession({ reason: "switch", previousSessionFile: event.previousSessionFile }, ctx),
);
api.on("session_branch", async (event, ctx) =>
runOnSession({ reason: "branch", previousSessionFile: event.previousSessionFile }, ctx),
);
api.on("session_tree", async (_event, ctx) =>
runOnSession({ reason: "tree", previousSessionFile: undefined }, ctx),
);
api.on("session_shutdown", async (_event, ctx) =>
runOnSession({ reason: "shutdown", previousSessionFile: undefined }, ctx),
);
api.on("auto_compaction_start", async (event, ctx) =>
runOnSession({ reason: "auto_compaction_start", trigger: event.reason, action: event.action }, ctx),
);
api.on("auto_compaction_end", async (event, ctx) =>
runOnSession(
{
reason: "auto_compaction_end",
action: event.action,
result: event.result,
aborted: event.aborted,
willRetry: event.willRetry,
errorMessage: event.errorMessage,
},
ctx,
),
);
api.on("auto_retry_start", async (event, ctx) =>
runOnSession(
{
reason: "auto_retry_start",
attempt: event.attempt,
maxAttempts: event.maxAttempts,
delayMs: event.delayMs,
errorMessage: event.errorMessage,
},
ctx,
),
);
api.on("auto_retry_end", async (event, ctx) =>
runOnSession(
{
reason: "auto_retry_end",
success: event.success,
attempt: event.attempt,
finalError: event.finalError,
},
ctx,
),
);
api.on("ttsr_triggered", async (event, ctx) =>
runOnSession({ reason: "ttsr_triggered", rules: event.rules }, ctx),
);
api.on("todo_reminder", async (event, ctx) =>
runOnSession(
{
reason: "todo_reminder",
todos: event.todos,
attempt: event.attempt,
maxAttempts: event.maxAttempts,
},
ctx,
),
);
};
}
// Factory
/**
* Build LoadedCustomCommand entries for all MCP prompts across connected servers.
* These are re-created whenever prompts change (setOnPromptsChanged callback).
*/
function buildMCPPromptCommands(manager: MCPManager): LoadedCustomCommand[] {
const commands: LoadedCustomCommand[] = [];
for (const serverName of manager.getConnectedServers()) {
const prompts = manager.getServerPrompts(serverName);
if (!prompts?.length) continue;
for (const prompt of prompts) {
const commandName = `${serverName}:${prompt.name}`;
commands.push({
path: `mcp:${commandName}`,
resolvedPath: `mcp:${commandName}`,
source: "bundled",
command: {
name: commandName,
description: prompt.description ?? `MCP prompt from ${serverName}`,
async execute(args: string[]) {
const promptArgs: Record<string, string> = {};
for (const arg of args) {
const eqIdx = arg.indexOf("=");
if (eqIdx > 0) {
promptArgs[arg.slice(0, eqIdx)] = arg.slice(eqIdx + 1);
}
}
const result = await manager.executePrompt(serverName, prompt.name, promptArgs);
if (!result) return "";
const parts: string[] = [];
for (const msg of result.messages) {
const contentItems = Array.isArray(msg.content) ? msg.content : [msg.content];
for (const item of contentItems) {
if (item.type === "text") {
parts.push(item.text);
} else if (item.type === "resource") {
const resource = item.resource;
if (resource.text) parts.push(resource.text);
}
}
}
return parts.join("\n\n");
},
},
});
}
}
return commands;
}
/**
* Create an AgentSession with the specified options.
*
* @example
* ```typescript
* // Minimal - uses defaults
* const { session } = await createAgentSession();
*
* // With explicit model
* import { getModel } from '@oh-my-pi/pi-ai';
* const { session } = await createAgentSession({
* model: getModel('anthropic', 'claude-opus-4-5'),
* thinkingLevel: 'high',
* });
*
* // Continue previous session
* const { session, modelFallbackMessage } = await createAgentSession({
* continueSession: true,
* });
*
* // Full control
* const { session } = await createAgentSession({
* model: myModel,
* getApiKey: async () => Bun.env.MY_KEY,
* systemPrompt: 'You are helpful.',
* tools: codingTools({ cwd: getProjectDir() }),
* skills: [],
* sessionManager: SessionManager.inMemory(),
* });
* ```
*/
export async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {
const cwd = options.cwd ?? getProjectDir();
const agentDir = options.agentDir ?? getDefaultAgentDir();
const eventBus = options.eventBus ?? new EventBus();
registerSshCleanup();
registerPythonCleanup();
// Use provided or create AuthStorage and ModelRegistry
const authStorage = options.authStorage ?? (await logger.time("discoverModels", discoverAuthStorage, agentDir));
const modelRegistry = options.modelRegistry ?? new ModelRegistry(authStorage);
const settings = options.settings ?? (await logger.time("settings", Settings.init, { cwd, agentDir }));
logger.time("initializeWithSettings");
initializeWithSettings(settings);
if (!options.modelRegistry) {
modelRegistry.refreshInBackground();
}
const resourceLoader = new RuntimeResourceLoader({ cwd, agentDir, settings, eventBus });
const discoveredSkillsPromise = options.skills === undefined ? resourceLoader.loadSkills({}) : undefined;
// Initialize provider preferences from settings
const webSearchProvider = settings.get("providers.webSearch");
if (typeof webSearchProvider === "string" && isSearchProviderPreference(webSearchProvider)) {
setPreferredSearchProvider(webSearchProvider);
}
const imageProvider = settings.get("providers.image");
if (
imageProvider === "auto" ||
imageProvider === "openai" ||
imageProvider === "gemini" ||
imageProvider === "openrouter"
) {
setPreferredImageProvider(imageProvider);
}
const sessionManager =
options.sessionManager ??
logger.time("sessionManager", () =>
SessionManager.create(cwd, SessionManager.getDefaultSessionDir(cwd, agentDir)),
);
const providerSessionId = options.providerSessionId ?? sessionManager.getSessionId();
const modelApiKeyAvailability = new Map<string, boolean>();
const getModelAvailabilityKey = (candidate: Model): string =>
`${candidate.provider}\u0000${candidate.baseUrl ?? ""}`;
const hasModelApiKey = async (candidate: Model): Promise<boolean> => {
const availabilityKey = getModelAvailabilityKey(candidate);
const cached = modelApiKeyAvailability.get(availabilityKey);
if (cached !== undefined) {
return cached;
}
const hasKey = !!(await modelRegistry.getApiKey(candidate, providerSessionId));
modelApiKeyAvailability.set(availabilityKey, hasKey);
return hasKey;
};
// Load and create secret obfuscator early so resumed session state and prompt warnings
// reflect actual loaded secrets, not just the setting toggle.
let obfuscator: SecretObfuscator | undefined;
if (settings.get("secrets.enabled")) {
const fileEntries = await logger.time("loadSecrets", loadSecrets, cwd, agentDir);
const envEntries = collectEnvSecrets();
const allEntries = [...envEntries, ...fileEntries];
if (allEntries.length > 0) {
obfuscator = new SecretObfuscator(allEntries);
}
}
const secretsEnabled = obfuscator?.hasSecrets() === true;
// Check if session has existing data to restore
const existingSession = logger.time("loadSessionContext", () =>
deobfuscateSessionContext(sessionManager.buildSessionContext(), obfuscator),
);
const existingBranch = logger.time("getSessionBranch", () => sessionManager.getBranch());
const hasExistingSession = existingBranch.length > 0;
const hasThinkingEntry = existingBranch.some(entry => entry.type === "thinking_level_change");
const hasServiceTierEntry = existingBranch.some(entry => entry.type === "service_tier_change");
const hasExplicitModel = options.model !== undefined || options.modelPattern !== undefined;
const modelMatchPreferences = {
usageOrder: settings.getStorage()?.getModelUsageOrder(),
};
const defaultRoleSpec = logger.time("resolveDefaultModelRole", () =>
resolveModelRoleValue(settings.getModelRole("default"), modelRegistry.getAvailable(), {
settings,
matchPreferences: modelMatchPreferences,
modelRegistry,
}),
);
let model = options.model;
let modelFallbackMessage: string | undefined;
// If session has data, try to restore model from it.
// Skip restore when an explicit model was requested.
const defaultModelStr = existingSession.models.default;
if (!hasExplicitModel && !model && hasExistingSession && defaultModelStr) {
await logger.time("restoreSessionModel", async () => {
const parsedModel = parseModelString(defaultModelStr);
if (parsedModel) {
const restoredModel = modelRegistry.find(parsedModel.provider, parsedModel.id);
if (restoredModel && (await hasModelApiKey(restoredModel))) {
model = restoredModel;
}
}
if (!model) {
modelFallbackMessage = `Could not restore model ${defaultModelStr}`;
}
});
}
// If still no model, try settings default.
// Skip settings fallback when an explicit model was requested.
if (!hasExplicitModel && !model && defaultRoleSpec.model) {
const settingsDefaultModel = defaultRoleSpec.model;
logger.time("resolveSettingsDefaultModel", () => {
// defaultRoleSpec.model already comes from modelRegistry.getAvailable(),
// so re-validating auth here just repeats the expensive lookup path.
model = settingsDefaultModel;
});
}
const taskDepth = options.taskDepth ?? 0;
let thinkingLevel = options.thinkingLevel;
// If session has data and includes a thinking entry, restore it
if (thinkingLevel === undefined && hasExistingSession && hasThinkingEntry) {
thinkingLevel = parseThinkingLevel(existingSession.thinkingLevel);
}
if (thinkingLevel === undefined && !hasExplicitModel && !hasThinkingEntry && defaultRoleSpec.explicitThinkingLevel) {
thinkingLevel = defaultRoleSpec.thinkingLevel;
}
// Fall back to settings default
if (thinkingLevel === undefined) {
thinkingLevel = settings.get("defaultThinkingLevel");
}
if (model) {
const resolvedModel = model;
thinkingLevel = logger.time("resolveThinkingLevelForModel", () =>
resolveThinkingLevelForModel(resolvedModel, thinkingLevel),
);
}
let skills: Skill[];
let skillWarnings: SkillWarning[];
if (options.skills !== undefined) {
const loaded = await resourceLoader.loadSkills({ skills: options.skills });
skills = loaded.skills;
skillWarnings = loaded.warnings;
} else {
const discovered = await logger.time(
"discoverSkills",
() => discoveredSkillsPromise ?? resourceLoader.loadSkills({}),
);
skills = discovered.skills;
skillWarnings = discovered.warnings;
}
// Discover rules and bucket them in one pass to avoid repeated scans over large rule sets.
const { ttsrManager, rulebookRules, alwaysApplyRules } = await logger.time("discoverTtsrRules", () =>
resourceLoader.loadRules({
rules: options.rules,
injectedTtsrRules: existingSession.injectedTtsrRules,
}),
);
const contextFiles = await logger.time("discoverContextFiles", () =>
resourceLoader.loadContextFiles({ contextFiles: options.contextFiles }),
);
let agent: Agent;
let session!: AgentSession;
let hasSession = false;
const enableLsp = options.enableLsp ?? true;
const backgroundJobsEnabled = isBackgroundJobSupportEnabled(settings);
const asyncMaxJobs = Math.min(100, Math.max(1, settings.get("async.maxJobs") ?? 100));
const ASYNC_INLINE_RESULT_MAX_CHARS = 12_000;
const ASYNC_PREVIEW_MAX_CHARS = 4_000;
const formatAsyncResultForFollowUp = async (result: string): Promise<string> => {
if (result.length <= ASYNC_INLINE_RESULT_MAX_CHARS) {
return result;
}
const preview = `${result.slice(0, ASYNC_PREVIEW_MAX_CHARS)}\n\n[Output truncated. Showing first ${ASYNC_PREVIEW_MAX_CHARS.toLocaleString()} characters.]`;
try {
const { path: artifactPath, id: artifactId } = await sessionManager.allocateArtifactPath("async");
if (artifactPath && artifactId) {
await Bun.write(artifactPath, result);
return `${preview}\nFull output: artifact://${artifactId}`;
}
} catch (error) {
logger.warn("Failed to persist async follow-up artifact", {
error: error instanceof Error ? error.message : String(error),
});
}
return preview;
};
const asyncJobManager = backgroundJobsEnabled
? new AsyncJobManager({
maxRunningJobs: asyncMaxJobs,
onJobComplete: async (jobId, result, job) => {
if (!session || asyncJobManager!.isDeliverySuppressed(jobId)) return;
const formattedResult = await formatAsyncResultForFollowUp(result);
if (asyncJobManager!.isDeliverySuppressed(jobId)) return;
const message = prompt.render(asyncResultTemplate, { jobId, result: formattedResult });
const durationMs = job ? Math.max(0, Date.now() - job.startTime) : undefined;
await session.sendCustomMessage(
{
customType: "async-result",
content: message,
display: true,
attribution: "agent",
details: {
jobId,
type: job?.type,
label: job?.label,
durationMs,
},
},
{ deliverAs: "followUp", triggerTurn: true },
);
},
})
: undefined;
const agentRegistry = options.agentRegistry ?? AgentRegistry.global();
const resolvedAgentId = options.agentId ?? options.parentTaskPrefix ?? MAIN_AGENT_ID;
const resolvedAgentDisplayName =
options.agentDisplayName ?? ((options.taskDepth ?? 0) > 0 || options.parentTaskPrefix ? "sub" : "main");
const pythonKernelOwnerId = `agent-session:${Snowflake.next()}`;
try {
const getActiveModelString = (): string | undefined => {
const activeModel = agent?.state.model;
if (activeModel) return formatModelString(activeModel);
if (model) return formatModelString(model);
return undefined;
};
const toolSession: ToolSession = {
cwd,
hasUI: options.hasUI ?? false,
enableLsp,
get hasEditTool() {
const requestedToolNames = options.toolNames
? [...new Set(options.toolNames.map(name => name.toLowerCase()))]
: undefined;
return !requestedToolNames || requestedToolNames.includes("edit");
},
skipPythonPreflight: options.skipPythonPreflight,
forcePythonWarmup: options.forcePythonWarmup,
contextFiles,
skills,
eventBus,
outputSchema: options.outputSchema,
requireYieldTool: options.requireYieldTool,
taskDepth: options.taskDepth ?? 0,
getSessionFile: () => sessionManager.getSessionFile() ?? null,
getPythonKernelOwnerId: () => pythonKernelOwnerId,
assertPythonExecutionAllowed: () => session?.assertPythonExecutionAllowed(),
trackPythonExecution: (execution, abortController) =>
session ? session.trackPythonExecution(execution, abortController) : execution,
getSessionId: () => sessionManager.getSessionId?.() ?? null,
getAgentId: () => resolvedAgentId,
agentRegistry,
getSessionSpawns: () => options.spawns ?? "*",
getModelString: () => (hasExplicitModel && model ? formatModelString(model) : undefined),
getActiveModelString,
getPlanModeState: () => session.getPlanModeState(),
getCompactContext: () => session.formatCompactContext(),
getTodoPhases: () => session.getTodoPhases(),
setTodoPhases: phases => session.setTodoPhases(phases),
isMCPDiscoveryEnabled: () => session.isMCPDiscoveryEnabled(),
getDiscoverableMCPTools: () => session.getDiscoverableMCPTools(),
getDiscoverableMCPSearchIndex: () => session.getDiscoverableMCPSearchIndex(),
getSelectedMCPToolNames: () => session.getSelectedMCPToolNames(),
activateDiscoveredMCPTools: toolNames => session.activateDiscoveredMCPTools(toolNames),
getCheckpointState: () => session.getCheckpointState(),
setCheckpointState: state => session.setCheckpointState(state ?? undefined),
getToolChoiceQueue: () => session.toolChoiceQueue,
buildToolChoice: name => {
const m = session.model;
return m ? buildNamedToolChoice(name, m) : undefined;
},
steer: msg =>
session.agent.steer({
role: "custom",
customType: msg.customType,
content: msg.content,
display: false,
details: msg.details,
attribution: "agent",
timestamp: Date.now(),
}),
peekQueueInvoker: () => session.peekQueueInvoker(),
allocateOutputArtifact: async toolType => {
try {
return await sessionManager.allocateArtifactPath(toolType);
} catch {
return {};
}
},
settings,
authStorage,
modelRegistry,
asyncJobManager,
};
// Initialize internal URL router for internal protocols (agent://, artifact://, memory://, skill://, rule://, mcp://, local://)
const internalRouter = new InternalUrlRouter();
const getArtifactsDir = () => sessionManager.getArtifactsDir();
internalRouter.register(new AgentProtocolHandler({ getArtifactsDir }));
internalRouter.register(new ArtifactProtocolHandler({ getArtifactsDir }));
internalRouter.register(
new MemoryProtocolHandler({
getMemoryRoot: () => getMemoryRoot(agentDir, settings.getCwd()),
}),
);
internalRouter.register(
new LocalProtocolHandler({
getArtifactsDir,
getSessionId: () => sessionManager.getSessionId(),
}),
);
internalRouter.register(
new SkillProtocolHandler({
getSkills: () => skills,
}),
);
internalRouter.register(
new RuleProtocolHandler({
getRules: () => [...rulebookRules, ...alwaysApplyRules],
}),
);
internalRouter.register(new PiProtocolHandler());
internalRouter.register(new JobsProtocolHandler({ getAsyncJobManager: () => asyncJobManager }));
internalRouter.register(new McpProtocolHandler({ getMcpManager: () => mcpManager }));
toolSession.internalRouter = internalRouter;
toolSession.getArtifactsDir = getArtifactsDir;
toolSession.agentOutputManager = new AgentOutputManager(
getArtifactsDir,
options.parentTaskPrefix ? { parentPrefix: options.parentTaskPrefix } : undefined,
);
// Create built-in tools (already wrapped with meta notice formatting)
const builtinTools = await logger.time("createAllTools", createTools, toolSession, options.toolNames);