@cortask/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1193 @@
1
+ import { z } from 'zod';
2
+ import OpenAI from 'openai';
3
+
4
+ interface Message {
5
+ role: "user" | "assistant" | "system";
6
+ content: string | ContentPart[];
7
+ }
8
+ interface ContentPart {
9
+ type: "text" | "image" | "tool_use" | "tool_result" | "thinking";
10
+ text?: string;
11
+ imageUrl?: string;
12
+ imageBase64?: string;
13
+ mimeType?: string;
14
+ toolCallId?: string;
15
+ toolName?: string;
16
+ toolArguments?: Record<string, unknown>;
17
+ isError?: boolean;
18
+ }
19
+ interface ToolDefinition {
20
+ name: string;
21
+ description: string;
22
+ inputSchema: Record<string, unknown>;
23
+ }
24
+ interface ToolCall {
25
+ id: string;
26
+ name: string;
27
+ arguments: Record<string, unknown>;
28
+ }
29
+ interface ToolResult {
30
+ toolCallId: string;
31
+ content: string;
32
+ isError?: boolean;
33
+ artifactType?: string;
34
+ artifactId?: string;
35
+ artifacts?: Array<{
36
+ id: string;
37
+ type: string;
38
+ meta?: Record<string, unknown>;
39
+ }>;
40
+ }
41
+ interface GenerateTextParams {
42
+ model: string;
43
+ messages: Message[];
44
+ systemPrompt?: string;
45
+ tools?: ToolDefinition[];
46
+ temperature?: number;
47
+ maxTokens?: number;
48
+ }
49
+ interface GenerateTextResult {
50
+ content: string;
51
+ thinking?: string;
52
+ toolCalls: ToolCall[];
53
+ usage: {
54
+ inputTokens: number;
55
+ outputTokens: number;
56
+ };
57
+ stopReason: "end" | "tool_use" | "max_tokens";
58
+ }
59
+ interface StreamChunk {
60
+ type: "text" | "thinking" | "tool_call_start" | "tool_call_delta" | "tool_call_end" | "message_end";
61
+ text?: string;
62
+ toolCall?: Partial<ToolCall>;
63
+ usage?: {
64
+ inputTokens: number;
65
+ outputTokens: number;
66
+ };
67
+ }
68
+ interface EmbedParams {
69
+ model: string;
70
+ inputs: string[];
71
+ }
72
+ interface EmbedResult {
73
+ embeddings: number[][];
74
+ usage: {
75
+ totalTokens: number;
76
+ };
77
+ }
78
+ interface ModelInfo {
79
+ id: string;
80
+ name: string;
81
+ contextWindow?: number;
82
+ inputPricePer1m?: number;
83
+ outputPricePer1m?: number;
84
+ }
85
+ interface LLMProvider {
86
+ readonly id: string;
87
+ generateText(params: GenerateTextParams): Promise<GenerateTextResult>;
88
+ generateStream(params: GenerateTextParams): AsyncIterable<StreamChunk>;
89
+ embed(params: EmbedParams): Promise<EmbedResult>;
90
+ listModels(): Promise<ModelInfo[]>;
91
+ }
92
+
93
+ declare class OpenAICompatibleProvider implements LLMProvider {
94
+ readonly id: string;
95
+ protected client: OpenAI;
96
+ constructor(id: string, apiKey: string, baseURL?: string);
97
+ generateText(params: GenerateTextParams): Promise<GenerateTextResult>;
98
+ generateStream(params: GenerateTextParams): AsyncIterable<StreamChunk>;
99
+ embed(params: EmbedParams): Promise<EmbedResult>;
100
+ listModels(): Promise<ModelInfo[]>;
101
+ }
102
+
103
+ declare class AnthropicProvider implements LLMProvider {
104
+ readonly id = "anthropic";
105
+ private client;
106
+ constructor(apiKey: string);
107
+ generateText(params: GenerateTextParams): Promise<GenerateTextResult>;
108
+ generateStream(params: GenerateTextParams): AsyncIterable<StreamChunk>;
109
+ embed(_params: EmbedParams): Promise<EmbedResult>;
110
+ listModels(): Promise<ModelInfo[]>;
111
+ }
112
+
113
+ declare class OpenAIProvider extends OpenAICompatibleProvider {
114
+ constructor(apiKey: string);
115
+ }
116
+
117
+ declare class GoogleProvider implements LLMProvider {
118
+ readonly id = "google";
119
+ private client;
120
+ constructor(apiKey: string);
121
+ generateText(params: GenerateTextParams): Promise<GenerateTextResult>;
122
+ generateStream(params: GenerateTextParams): AsyncIterable<StreamChunk>;
123
+ embed(params: EmbedParams): Promise<EmbedResult>;
124
+ listModels(): Promise<ModelInfo[]>;
125
+ }
126
+
127
+ declare class MoonshotProvider extends OpenAICompatibleProvider {
128
+ constructor(apiKey: string);
129
+ }
130
+
131
+ declare class GrokProvider extends OpenAICompatibleProvider {
132
+ constructor(apiKey: string);
133
+ }
134
+
135
+ declare class OpenRouterProvider extends OpenAICompatibleProvider {
136
+ private apiKeyValue;
137
+ constructor(apiKey: string);
138
+ listModels(): Promise<ModelInfo[]>;
139
+ }
140
+
141
+ declare class MiniMaxProvider extends OpenAICompatibleProvider {
142
+ constructor(apiKey: string);
143
+ }
144
+
145
+ declare class OllamaProvider implements LLMProvider {
146
+ readonly id = "ollama";
147
+ private host;
148
+ constructor(host: string);
149
+ generateText(params: GenerateTextParams): Promise<GenerateTextResult>;
150
+ generateStream(params: GenerateTextParams): AsyncIterable<StreamChunk>;
151
+ embed(params: EmbedParams): Promise<EmbedResult>;
152
+ listModels(): Promise<ModelInfo[]>;
153
+ }
154
+
155
+ type ProviderId = "anthropic" | "openai" | "google" | "moonshot" | "grok" | "openrouter" | "minimax" | "ollama";
156
+ interface ProviderInfo {
157
+ id: ProviderId;
158
+ name: string;
159
+ requiresApiKey: boolean;
160
+ }
161
+ declare const AVAILABLE_PROVIDERS: ProviderInfo[];
162
+ declare function getProviderInfo(id: ProviderId): ProviderInfo | undefined;
163
+ declare function createProvider(id: ProviderId, apiKey: string): LLMProvider;
164
+
165
+ interface Attachment {
166
+ mimeType: string;
167
+ base64: string;
168
+ name?: string;
169
+ }
170
+ interface AgentRunParams {
171
+ prompt: string;
172
+ attachments?: Attachment[];
173
+ sessionId?: string;
174
+ workspaceId?: string;
175
+ signal?: AbortSignal;
176
+ }
177
+ interface AgentRunResult {
178
+ runId: string;
179
+ response: string;
180
+ toolCalls: ToolCall[];
181
+ usage: {
182
+ inputTokens: number;
183
+ outputTokens: number;
184
+ };
185
+ }
186
+ interface PermissionRequest {
187
+ id: string;
188
+ type: "file_write" | "file_delete" | "bash" | "other";
189
+ description: string;
190
+ details?: string;
191
+ }
192
+ interface QuestionnaireQuestion {
193
+ id: string;
194
+ question: string;
195
+ type: "single" | "multiple" | "text" | "textarea";
196
+ options?: Array<{
197
+ value: string;
198
+ label: string;
199
+ description?: string;
200
+ }>;
201
+ required?: boolean;
202
+ placeholder?: string;
203
+ allowOther?: boolean;
204
+ }
205
+ interface QuestionnaireRequest {
206
+ id: string;
207
+ title?: string;
208
+ description?: string;
209
+ questions: QuestionnaireQuestion[];
210
+ }
211
+ interface QuestionnaireResponse {
212
+ [questionId: string]: string | string[];
213
+ }
214
+ interface AgentStreamEvent {
215
+ type: "thinking_delta" | "text_delta" | "tool_call_start" | "tool_call_delta" | "tool_call_end" | "tool_result" | "permission_request" | "questionnaire_request" | "done" | "error";
216
+ text?: string;
217
+ toolName?: string;
218
+ toolCallId?: string;
219
+ toolArgs?: Record<string, unknown>;
220
+ toolResult?: ToolResult;
221
+ permissionRequest?: PermissionRequest;
222
+ questionnaireRequest?: QuestionnaireRequest;
223
+ usage?: {
224
+ inputTokens: number;
225
+ outputTokens: number;
226
+ costUsd?: number;
227
+ };
228
+ error?: string;
229
+ }
230
+ interface ToolHandler {
231
+ definition: ToolDefinition;
232
+ execute: (args: Record<string, unknown>, context: ToolExecutionContext) => Promise<ToolResult>;
233
+ }
234
+ interface ToolExecutionContext {
235
+ workspacePath: string;
236
+ dataDir: string;
237
+ sessionId: string;
238
+ runId: string;
239
+ requestPermission: (req: PermissionRequest) => Promise<boolean>;
240
+ requestQuestionnaire: (req: QuestionnaireRequest) => Promise<QuestionnaireResponse>;
241
+ }
242
+
243
+ interface AgentRunnerConfig {
244
+ provider: LLMProvider;
245
+ model: string;
246
+ maxTurns: number;
247
+ temperature?: number;
248
+ maxTokens?: number;
249
+ }
250
+ interface AgentRunnerDeps {
251
+ config: AgentRunnerConfig;
252
+ tools: ToolHandler[];
253
+ getWorkspacePath: () => string;
254
+ getDataDir: () => string;
255
+ getMemoryContent: () => Promise<string | undefined>;
256
+ getGlobalMemoryContent: () => Promise<string | undefined>;
257
+ getSkillPrompts: () => string[];
258
+ getSessionMessages: (sessionId: string) => Promise<Message[]>;
259
+ saveSessionMessages: (sessionId: string, messages: Message[]) => Promise<void>;
260
+ channel?: {
261
+ type: string;
262
+ chatId: string;
263
+ };
264
+ onPermissionRequest?: (req: PermissionRequest) => Promise<boolean>;
265
+ onQuestionnaireRequest?: (req: QuestionnaireRequest) => Promise<QuestionnaireResponse>;
266
+ }
267
+ declare class AgentRunner {
268
+ private deps;
269
+ constructor(deps: AgentRunnerDeps);
270
+ private buildToolDefinitions;
271
+ private getToolHandler;
272
+ private buildSystemPromptText;
273
+ private createToolContext;
274
+ run(params: AgentRunParams): Promise<AgentRunResult>;
275
+ runStream(params: AgentRunParams): AsyncIterable<AgentStreamEvent>;
276
+ }
277
+
278
+ interface CronScheduleAt {
279
+ type: "at";
280
+ datetime: string;
281
+ }
282
+ interface CronScheduleEvery {
283
+ type: "every";
284
+ intervalMs: number;
285
+ }
286
+ interface CronScheduleCron {
287
+ type: "cron";
288
+ expression: string;
289
+ timezone?: string;
290
+ }
291
+ type CronSchedule = CronScheduleAt | CronScheduleEvery | CronScheduleCron;
292
+ interface CronDelivery {
293
+ channel?: string;
294
+ target?: string;
295
+ sessionKey?: string;
296
+ }
297
+ interface CronJob {
298
+ id: string;
299
+ name: string;
300
+ enabled: boolean;
301
+ schedule: CronSchedule;
302
+ prompt: string;
303
+ delivery: CronDelivery;
304
+ workspaceId?: string;
305
+ createdAt: string;
306
+ updatedAt: string;
307
+ }
308
+ interface CronJobState {
309
+ jobId: string;
310
+ nextRunAtMs: number | null;
311
+ lastRunAtMs: number | null;
312
+ lastStatus: "success" | "error" | null;
313
+ lastError: string | null;
314
+ consecutiveErrors: number;
315
+ }
316
+ interface CronJobCreate {
317
+ name: string;
318
+ schedule: CronSchedule;
319
+ prompt: string;
320
+ delivery?: CronDelivery;
321
+ workspaceId?: string;
322
+ enabled?: boolean;
323
+ }
324
+ interface CronEvent {
325
+ type: "added" | "removed" | "started" | "finished" | "error";
326
+ jobId: string;
327
+ jobName: string;
328
+ result?: string;
329
+ error?: string;
330
+ }
331
+
332
+ type EventHandler = (event: CronEvent) => void;
333
+ type JobExecutor = (job: CronJob) => Promise<string>;
334
+ declare class CronService {
335
+ private db;
336
+ private timer;
337
+ private running;
338
+ private executor;
339
+ private eventHandlers;
340
+ constructor(dbPath: string);
341
+ private initSchema;
342
+ setExecutor(executor: JobExecutor): void;
343
+ onEvent(handler: EventHandler): void;
344
+ private emit;
345
+ start(): void;
346
+ stop(): void;
347
+ private scheduleNext;
348
+ private tick;
349
+ private executeJob;
350
+ add(input: CronJobCreate): CronJob;
351
+ update(id: string, updates: Partial<Pick<CronJob, "name" | "enabled" | "schedule" | "prompt" | "delivery">>): CronJob | null;
352
+ remove(id: string): boolean;
353
+ getJob(id: string): CronJob | null;
354
+ list(workspaceId?: string): CronJob[];
355
+ getState(jobId: string): CronJobState | null;
356
+ runNow(id: string): Promise<void>;
357
+ private upsertState;
358
+ close(): void;
359
+ }
360
+
361
+ /**
362
+ * Creates a cron tool handler bound to a CronService instance.
363
+ * This is a factory because the cron service is initialized at runtime.
364
+ */
365
+ declare function createCronTool(cronService: CronService): ToolHandler;
366
+
367
+ interface Artifact {
368
+ id: string;
369
+ type: "html" | "csv" | "image" | "json" | "text" | "svg";
370
+ title: string;
371
+ content: string;
372
+ mimeType: string;
373
+ createdAt: number;
374
+ }
375
+ declare class ArtifactStore {
376
+ private store;
377
+ create(type: Artifact["type"], title: string, content: string): Artifact;
378
+ get(id: string): Artifact | undefined;
379
+ list(): Artifact[];
380
+ delete(id: string): boolean;
381
+ private pruneExpired;
382
+ }
383
+
384
+ /**
385
+ * Creates an artifact tool handler bound to an ArtifactStore instance.
386
+ */
387
+ declare function createArtifactTool(artifactStore: ArtifactStore): ToolHandler;
388
+
389
+ declare function createBrowserTool(artifactStore: ArtifactStore): ToolHandler;
390
+
391
+ /**
392
+ * Set the AgentRunner reference for subagent spawning.
393
+ * Must be called after AgentRunner instantiation.
394
+ */
395
+ declare function setSubagentRunner(runner: AgentRunner): void;
396
+ /**
397
+ * Create the subagent tool handler.
398
+ * Factory pattern to allow runtime injection of dependencies.
399
+ */
400
+ declare function createSubagentTool(): ToolHandler;
401
+
402
+ interface Workspace {
403
+ id: string;
404
+ name: string;
405
+ rootPath: string;
406
+ lastAccessedAt: string;
407
+ provider?: string;
408
+ model?: string;
409
+ skills?: string[];
410
+ }
411
+ declare class WorkspaceManager {
412
+ private db;
413
+ private dataDir;
414
+ private activeWorkspaceId;
415
+ constructor(dbPath: string);
416
+ private initSchema;
417
+ list(): Promise<Workspace[]>;
418
+ get(id: string): Promise<Workspace | null>;
419
+ create(name: string, rootPath?: string): Promise<Workspace>;
420
+ update(id: string, updates: Partial<Pick<Workspace, "name" | "provider" | "model" | "skills">>): Promise<void>;
421
+ reorder(orderedIds: string[]): Promise<void>;
422
+ delete(id: string): Promise<void>;
423
+ open(id: string): Promise<Workspace | null>;
424
+ getActiveWorkspaceId(): string | null;
425
+ getActiveWorkspace(): Promise<Workspace | null>;
426
+ readMemory(workspacePath: string): Promise<string | undefined>;
427
+ writeMemory(workspacePath: string, content: string): Promise<void>;
428
+ readGlobalMemory(dataDir: string): Promise<string | undefined>;
429
+ writeGlobalMemory(dataDir: string, content: string): Promise<void>;
430
+ getSessionDbPath(workspacePath: string): string;
431
+ getChannelWorkspace(chatKey: string): string | null;
432
+ setChannelWorkspace(chatKey: string, workspaceId: string): void;
433
+ close(): void;
434
+ }
435
+
436
+ /**
437
+ * Creates a switch_workspace tool for channel-based runners.
438
+ * Allows the user to list workspaces or switch to a different one.
439
+ * Switching updates the workspace mapping so the next message uses the new workspace.
440
+ */
441
+ declare function createSwitchWorkspaceTool(workspaceManager: WorkspaceManager, chatKey: string): ToolHandler;
442
+
443
+ declare const builtinTools: ToolHandler[];
444
+
445
+ interface SystemPromptContext {
446
+ workspacePath: string;
447
+ globalMemoryContent?: string;
448
+ memoryContent?: string;
449
+ skillPrompts?: string[];
450
+ toolNames: string[];
451
+ channel?: {
452
+ type: string;
453
+ chatId: string;
454
+ };
455
+ }
456
+ declare function buildSystemPrompt(ctx: SystemPromptContext): string;
457
+
458
+ interface SubagentRunRecord {
459
+ runId: string;
460
+ childSessionId: string;
461
+ parentSessionId: string;
462
+ parentRunId: string;
463
+ task: string;
464
+ depth: number;
465
+ status: "running" | "done" | "error" | "timeout" | "cancelled";
466
+ result?: string;
467
+ error?: string;
468
+ createdAt: number;
469
+ endedAt?: number;
470
+ abortController?: AbortController;
471
+ }
472
+ declare const SUBAGENT_DEFAULTS: {
473
+ readonly maxDepth: 1;
474
+ readonly maxChildrenPerAgent: 5;
475
+ readonly timeoutMs: 120000;
476
+ };
477
+
478
+ /**
479
+ * Register a new subagent run in the registry.
480
+ */
481
+ declare function registerSubagentRun(record: SubagentRunRecord): void;
482
+ /**
483
+ * Retrieve a subagent run by its ID.
484
+ */
485
+ declare function getSubagentRun(runId: string): SubagentRunRecord | undefined;
486
+ /**
487
+ * Mark a subagent run as complete with result or error.
488
+ */
489
+ declare function completeSubagentRun(runId: string, status: "done" | "error" | "timeout" | "cancelled", result?: string, error?: string): void;
490
+ /**
491
+ * Cancel a subagent run and all its children.
492
+ */
493
+ declare function cancelSubagentRun(runId: string): boolean;
494
+ /**
495
+ * Cancel all children of a parent session.
496
+ */
497
+ declare function cancelChildrenOfSession(parentSessionId: string): number;
498
+ /**
499
+ * Count how many active (running) children belong to a parent session.
500
+ */
501
+ declare function countActiveChildren(parentSessionId: string): number;
502
+ /**
503
+ * Get the depth of a session (0 for root, 1+ for subagents).
504
+ */
505
+ declare function getDepthForSession(sessionId: string): number;
506
+ /**
507
+ * Cleanup old completed subagent records.
508
+ * @param maxAgeMs Maximum age in milliseconds (default: 30 minutes)
509
+ */
510
+ declare function cleanupSubagentRecords(maxAgeMs?: number): void;
511
+
512
+ interface CredentialStore {
513
+ get(key: string): Promise<string | null>;
514
+ set(key: string, value: string): Promise<void>;
515
+ delete(key: string): Promise<void>;
516
+ has(key: string): Promise<boolean>;
517
+ list(): Promise<string[]>;
518
+ }
519
+ declare class EncryptedCredentialStore implements CredentialStore {
520
+ private filePath;
521
+ private secret;
522
+ private store;
523
+ constructor(filePath: string, secret: string);
524
+ private load;
525
+ private save;
526
+ get(key: string): Promise<string | null>;
527
+ set(key: string, value: string): Promise<void>;
528
+ delete(key: string): Promise<void>;
529
+ has(key: string): Promise<boolean>;
530
+ list(): Promise<string[]>;
531
+ }
532
+ declare function getOrCreateSecret(dataDir: string): Promise<string>;
533
+ declare function credentialKey(category: string, ...parts: string[]): string;
534
+
535
+ declare const cortaskConfigSchema: z.ZodObject<{
536
+ onboarded: z.ZodDefault<z.ZodBoolean>;
537
+ workspace: z.ZodDefault<z.ZodObject<{
538
+ defaultDir: z.ZodOptional<z.ZodString>;
539
+ }, "strip", z.ZodTypeAny, {
540
+ defaultDir?: string | undefined;
541
+ }, {
542
+ defaultDir?: string | undefined;
543
+ }>>;
544
+ providers: z.ZodDefault<z.ZodObject<{
545
+ default: z.ZodDefault<z.ZodString>;
546
+ anthropic: z.ZodDefault<z.ZodObject<{
547
+ model: z.ZodOptional<z.ZodString>;
548
+ }, "strip", z.ZodTypeAny, {
549
+ model?: string | undefined;
550
+ }, {
551
+ model?: string | undefined;
552
+ }>>;
553
+ openai: z.ZodDefault<z.ZodObject<{
554
+ model: z.ZodOptional<z.ZodString>;
555
+ }, "strip", z.ZodTypeAny, {
556
+ model?: string | undefined;
557
+ }, {
558
+ model?: string | undefined;
559
+ }>>;
560
+ google: z.ZodDefault<z.ZodObject<{
561
+ model: z.ZodOptional<z.ZodString>;
562
+ }, "strip", z.ZodTypeAny, {
563
+ model?: string | undefined;
564
+ }, {
565
+ model?: string | undefined;
566
+ }>>;
567
+ moonshot: z.ZodDefault<z.ZodObject<{
568
+ model: z.ZodOptional<z.ZodString>;
569
+ }, "strip", z.ZodTypeAny, {
570
+ model?: string | undefined;
571
+ }, {
572
+ model?: string | undefined;
573
+ }>>;
574
+ grok: z.ZodDefault<z.ZodObject<{
575
+ model: z.ZodOptional<z.ZodString>;
576
+ }, "strip", z.ZodTypeAny, {
577
+ model?: string | undefined;
578
+ }, {
579
+ model?: string | undefined;
580
+ }>>;
581
+ openrouter: z.ZodDefault<z.ZodObject<{
582
+ model: z.ZodOptional<z.ZodString>;
583
+ }, "strip", z.ZodTypeAny, {
584
+ model?: string | undefined;
585
+ }, {
586
+ model?: string | undefined;
587
+ }>>;
588
+ minimax: z.ZodDefault<z.ZodObject<{
589
+ model: z.ZodOptional<z.ZodString>;
590
+ }, "strip", z.ZodTypeAny, {
591
+ model?: string | undefined;
592
+ }, {
593
+ model?: string | undefined;
594
+ }>>;
595
+ ollama: z.ZodDefault<z.ZodObject<{
596
+ model: z.ZodOptional<z.ZodString>;
597
+ }, "strip", z.ZodTypeAny, {
598
+ model?: string | undefined;
599
+ }, {
600
+ model?: string | undefined;
601
+ }>>;
602
+ }, "strip", z.ZodTypeAny, {
603
+ anthropic: {
604
+ model?: string | undefined;
605
+ };
606
+ openai: {
607
+ model?: string | undefined;
608
+ };
609
+ google: {
610
+ model?: string | undefined;
611
+ };
612
+ moonshot: {
613
+ model?: string | undefined;
614
+ };
615
+ grok: {
616
+ model?: string | undefined;
617
+ };
618
+ openrouter: {
619
+ model?: string | undefined;
620
+ };
621
+ minimax: {
622
+ model?: string | undefined;
623
+ };
624
+ default: string;
625
+ ollama: {
626
+ model?: string | undefined;
627
+ };
628
+ }, {
629
+ anthropic?: {
630
+ model?: string | undefined;
631
+ } | undefined;
632
+ openai?: {
633
+ model?: string | undefined;
634
+ } | undefined;
635
+ google?: {
636
+ model?: string | undefined;
637
+ } | undefined;
638
+ moonshot?: {
639
+ model?: string | undefined;
640
+ } | undefined;
641
+ grok?: {
642
+ model?: string | undefined;
643
+ } | undefined;
644
+ openrouter?: {
645
+ model?: string | undefined;
646
+ } | undefined;
647
+ minimax?: {
648
+ model?: string | undefined;
649
+ } | undefined;
650
+ default?: string | undefined;
651
+ ollama?: {
652
+ model?: string | undefined;
653
+ } | undefined;
654
+ }>>;
655
+ agent: z.ZodDefault<z.ZodObject<{
656
+ maxTurns: z.ZodDefault<z.ZodNumber>;
657
+ temperature: z.ZodDefault<z.ZodNumber>;
658
+ maxTokens: z.ZodOptional<z.ZodNumber>;
659
+ }, "strip", z.ZodTypeAny, {
660
+ temperature: number;
661
+ maxTurns: number;
662
+ maxTokens?: number | undefined;
663
+ }, {
664
+ temperature?: number | undefined;
665
+ maxTurns?: number | undefined;
666
+ maxTokens?: number | undefined;
667
+ }>>;
668
+ spending: z.ZodDefault<z.ZodObject<{
669
+ enabled: z.ZodDefault<z.ZodBoolean>;
670
+ maxTokens: z.ZodOptional<z.ZodNumber>;
671
+ maxCostUsd: z.ZodOptional<z.ZodNumber>;
672
+ period: z.ZodDefault<z.ZodEnum<["daily", "weekly", "monthly"]>>;
673
+ }, "strip", z.ZodTypeAny, {
674
+ enabled: boolean;
675
+ period: "daily" | "weekly" | "monthly";
676
+ maxTokens?: number | undefined;
677
+ maxCostUsd?: number | undefined;
678
+ }, {
679
+ enabled?: boolean | undefined;
680
+ maxTokens?: number | undefined;
681
+ maxCostUsd?: number | undefined;
682
+ period?: "daily" | "weekly" | "monthly" | undefined;
683
+ }>>;
684
+ channels: z.ZodDefault<z.ZodObject<{
685
+ telegram: z.ZodDefault<z.ZodObject<{
686
+ enabled: z.ZodDefault<z.ZodBoolean>;
687
+ allowedUsers: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
688
+ }, "strip", z.ZodTypeAny, {
689
+ enabled: boolean;
690
+ allowedUsers: string[];
691
+ }, {
692
+ enabled?: boolean | undefined;
693
+ allowedUsers?: string[] | undefined;
694
+ }>>;
695
+ }, "strip", z.ZodTypeAny, {
696
+ telegram: {
697
+ enabled: boolean;
698
+ allowedUsers: string[];
699
+ };
700
+ }, {
701
+ telegram?: {
702
+ enabled?: boolean | undefined;
703
+ allowedUsers?: string[] | undefined;
704
+ } | undefined;
705
+ }>>;
706
+ skills: z.ZodDefault<z.ZodObject<{
707
+ dirs: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
708
+ }, "strip", z.ZodTypeAny, {
709
+ dirs: string[];
710
+ }, {
711
+ dirs?: string[] | undefined;
712
+ }>>;
713
+ server: z.ZodDefault<z.ZodObject<{
714
+ port: z.ZodDefault<z.ZodNumber>;
715
+ host: z.ZodDefault<z.ZodString>;
716
+ }, "strip", z.ZodTypeAny, {
717
+ port: number;
718
+ host: string;
719
+ }, {
720
+ port?: number | undefined;
721
+ host?: string | undefined;
722
+ }>>;
723
+ }, "strip", z.ZodTypeAny, {
724
+ agent: {
725
+ temperature: number;
726
+ maxTurns: number;
727
+ maxTokens?: number | undefined;
728
+ };
729
+ skills: {
730
+ dirs: string[];
731
+ };
732
+ onboarded: boolean;
733
+ workspace: {
734
+ defaultDir?: string | undefined;
735
+ };
736
+ providers: {
737
+ anthropic: {
738
+ model?: string | undefined;
739
+ };
740
+ openai: {
741
+ model?: string | undefined;
742
+ };
743
+ google: {
744
+ model?: string | undefined;
745
+ };
746
+ moonshot: {
747
+ model?: string | undefined;
748
+ };
749
+ grok: {
750
+ model?: string | undefined;
751
+ };
752
+ openrouter: {
753
+ model?: string | undefined;
754
+ };
755
+ minimax: {
756
+ model?: string | undefined;
757
+ };
758
+ default: string;
759
+ ollama: {
760
+ model?: string | undefined;
761
+ };
762
+ };
763
+ spending: {
764
+ enabled: boolean;
765
+ period: "daily" | "weekly" | "monthly";
766
+ maxTokens?: number | undefined;
767
+ maxCostUsd?: number | undefined;
768
+ };
769
+ channels: {
770
+ telegram: {
771
+ enabled: boolean;
772
+ allowedUsers: string[];
773
+ };
774
+ };
775
+ server: {
776
+ port: number;
777
+ host: string;
778
+ };
779
+ }, {
780
+ agent?: {
781
+ temperature?: number | undefined;
782
+ maxTurns?: number | undefined;
783
+ maxTokens?: number | undefined;
784
+ } | undefined;
785
+ skills?: {
786
+ dirs?: string[] | undefined;
787
+ } | undefined;
788
+ onboarded?: boolean | undefined;
789
+ workspace?: {
790
+ defaultDir?: string | undefined;
791
+ } | undefined;
792
+ providers?: {
793
+ anthropic?: {
794
+ model?: string | undefined;
795
+ } | undefined;
796
+ openai?: {
797
+ model?: string | undefined;
798
+ } | undefined;
799
+ google?: {
800
+ model?: string | undefined;
801
+ } | undefined;
802
+ moonshot?: {
803
+ model?: string | undefined;
804
+ } | undefined;
805
+ grok?: {
806
+ model?: string | undefined;
807
+ } | undefined;
808
+ openrouter?: {
809
+ model?: string | undefined;
810
+ } | undefined;
811
+ minimax?: {
812
+ model?: string | undefined;
813
+ } | undefined;
814
+ default?: string | undefined;
815
+ ollama?: {
816
+ model?: string | undefined;
817
+ } | undefined;
818
+ } | undefined;
819
+ spending?: {
820
+ enabled?: boolean | undefined;
821
+ maxTokens?: number | undefined;
822
+ maxCostUsd?: number | undefined;
823
+ period?: "daily" | "weekly" | "monthly" | undefined;
824
+ } | undefined;
825
+ channels?: {
826
+ telegram?: {
827
+ enabled?: boolean | undefined;
828
+ allowedUsers?: string[] | undefined;
829
+ } | undefined;
830
+ } | undefined;
831
+ server?: {
832
+ port?: number | undefined;
833
+ host?: string | undefined;
834
+ } | undefined;
835
+ }>;
836
+ type CortaskConfig = z.infer<typeof cortaskConfigSchema>;
837
+ declare function loadConfig(configPath: string): Promise<CortaskConfig>;
838
+ declare function saveConfig(configPath: string, config: CortaskConfig): Promise<void>;
839
+ declare function getDataDir(): string;
840
+
841
+ interface OnboardingData {
842
+ provider: {
843
+ type: ProviderId;
844
+ apiKey: string;
845
+ };
846
+ workspace: {
847
+ defaultDir: string;
848
+ };
849
+ }
850
+ interface OnboardingStatus {
851
+ completed: boolean;
852
+ hasProvider: boolean;
853
+ hasWorkspace: boolean;
854
+ }
855
+ interface ProviderValidationResult {
856
+ valid: boolean;
857
+ error?: string;
858
+ model?: string;
859
+ }
860
+
861
+ declare function validateProvider(type: ProviderId, apiKey: string): Promise<ProviderValidationResult>;
862
+
863
+ type ChannelType = "whatsapp" | "telegram" | "discord";
864
+ interface Session {
865
+ id: string;
866
+ title: string;
867
+ createdAt: string;
868
+ updatedAt: string;
869
+ parentSessionId?: string;
870
+ depth?: number;
871
+ channel?: ChannelType;
872
+ }
873
+ interface SessionWithMessages extends Session {
874
+ messages: Message[];
875
+ }
876
+ declare class SessionStore {
877
+ private db;
878
+ constructor(dbPath: string);
879
+ private initSchema;
880
+ listSessions(): Session[];
881
+ getSession(id: string): SessionWithMessages | null;
882
+ createSession(id: string, title?: string, parentSessionId?: string, depth?: number, channel?: ChannelType): Session;
883
+ saveMessages(sessionId: string, messages: Message[], channel?: ChannelType): void;
884
+ getMessages(sessionId: string): Message[];
885
+ deleteSession(id: string): void;
886
+ updateTitle(id: string, title: string): void;
887
+ close(): void;
888
+ }
889
+
890
+ /**
891
+ * Run database migrations on a session database.
892
+ * This is separate from SessionStore to allow running migrations at startup
893
+ * before any SessionStore instances are cached.
894
+ */
895
+ declare function migrateSessionDatabase(dbPath: string): void;
896
+ /**
897
+ * Migrate all workspace session databases.
898
+ * @param workspaces Array of workspace objects with rootPath property
899
+ */
900
+ declare function migrateAllWorkspaces(workspaces: Array<{
901
+ rootPath: string;
902
+ }>): void;
903
+
904
+ interface SkillToolInput {
905
+ type: string;
906
+ description?: string;
907
+ enum?: string[];
908
+ required?: boolean;
909
+ }
910
+ interface SkillToolTemplate {
911
+ name: string;
912
+ description: string;
913
+ input: Record<string, SkillToolInput>;
914
+ request: {
915
+ url: string;
916
+ method?: string;
917
+ headers?: Record<string, string>;
918
+ body?: string;
919
+ };
920
+ }
921
+ type SkillInstallKind = "brew" | "npm" | "go" | "uv" | "download" | "winget" | "scoop" | "choco";
922
+ interface SkillInstallSpec {
923
+ id?: string;
924
+ kind: SkillInstallKind;
925
+ label?: string;
926
+ bins?: string[];
927
+ os?: string[];
928
+ formula?: string;
929
+ package?: string;
930
+ module?: string;
931
+ url?: string;
932
+ archive?: string;
933
+ extract?: boolean;
934
+ targetDir?: string;
935
+ }
936
+ interface SkillInstallOption {
937
+ id: string;
938
+ kind: SkillInstallKind;
939
+ label: string;
940
+ }
941
+ interface SkillManifest {
942
+ name: string;
943
+ description: string;
944
+ requires?: {
945
+ env?: string[];
946
+ bins?: string[];
947
+ config?: string[];
948
+ };
949
+ install?: SkillInstallSpec[];
950
+ tools?: SkillToolTemplate[];
951
+ compatibility?: {
952
+ os?: string[];
953
+ };
954
+ always?: boolean;
955
+ metadata?: {
956
+ homepage?: string;
957
+ tags?: string[];
958
+ author?: string;
959
+ gitUrl?: string;
960
+ [key: string]: unknown;
961
+ };
962
+ }
963
+ type SkillSource = "bundled" | "user" | "config-dir" | "git";
964
+ interface SkillEntry {
965
+ manifest: SkillManifest;
966
+ content: string;
967
+ path: string;
968
+ eligible: boolean;
969
+ ineligibleReason?: string;
970
+ source: SkillSource;
971
+ editable: boolean;
972
+ hasCodeTools?: boolean;
973
+ installOptions?: SkillInstallOption[];
974
+ credentialSchema?: CredentialSchema;
975
+ credentialStatus?: Record<string, boolean>;
976
+ }
977
+ interface SkillCodeTool {
978
+ name: string;
979
+ description: string;
980
+ inputSchema: Record<string, unknown>;
981
+ execute: (args: Record<string, unknown>, context: {
982
+ credentialStore: unknown;
983
+ skillName: string;
984
+ }) => Promise<{
985
+ content: string;
986
+ isError?: boolean;
987
+ }>;
988
+ }
989
+ type CredentialAuthType = "api-key" | "basic-auth" | "bearer-token" | "oauth2" | "custom";
990
+ type CredentialFieldType = "text" | "secret" | "url" | "email" | "model-select";
991
+ interface CredentialField {
992
+ key: string;
993
+ label: string;
994
+ type: CredentialFieldType;
995
+ required?: boolean;
996
+ description?: string;
997
+ placeholder?: string;
998
+ pattern?: string;
999
+ minLength?: number;
1000
+ maxLength?: number;
1001
+ }
1002
+ interface OAuth2Config {
1003
+ authorizationUrl: string;
1004
+ tokenUrl: string;
1005
+ scopes?: string[];
1006
+ pkce?: boolean;
1007
+ refreshable?: boolean;
1008
+ }
1009
+ interface CredentialDefinition {
1010
+ id: string;
1011
+ type: CredentialAuthType;
1012
+ name: string;
1013
+ description?: string;
1014
+ fields?: CredentialField[];
1015
+ oauth?: OAuth2Config;
1016
+ storeAs?: string;
1017
+ multiple?: boolean;
1018
+ }
1019
+ interface CredentialSchema {
1020
+ credentials: CredentialDefinition[];
1021
+ }
1022
+
1023
+ declare function clearSkillCache(): void;
1024
+ /**
1025
+ * Load all skills from bundled, user, and config directories.
1026
+ */
1027
+ declare function loadSkills(bundledDir: string | null, userDir: string | null, configDirs: string[], credentialStore: CredentialStore | null): Promise<SkillEntry[]>;
1028
+ /**
1029
+ * Get only eligible skills.
1030
+ */
1031
+ declare function getEligibleSkills(skills: SkillEntry[]): SkillEntry[];
1032
+
1033
+ interface SkillToolRegistry {
1034
+ toolDefs: ToolDefinition[];
1035
+ toolNames: Set<string>;
1036
+ handlers: Map<string, (args: Record<string, unknown>) => Promise<ToolResult>>;
1037
+ }
1038
+ /**
1039
+ * Build tool definitions and handlers from eligible skills.
1040
+ */
1041
+ declare function buildSkillTools(skills: SkillEntry[], credentialStore: CredentialStore | null): Promise<SkillToolRegistry>;
1042
+
1043
+ /**
1044
+ * Install a skill from a git URL into the user skills directory.
1045
+ */
1046
+ declare function installSkillFromGit(gitUrl: string, skillsDir: string): Promise<{
1047
+ name: string;
1048
+ path: string;
1049
+ }>;
1050
+ /**
1051
+ * Remove an installed skill.
1052
+ */
1053
+ declare function removeSkill(skillName: string, skillsDir: string): Promise<void>;
1054
+
1055
+ /**
1056
+ * Get the credential store key for a skill credential field.
1057
+ * Format: skill.{skillName}.{credentialId}.{fieldKey}
1058
+ */
1059
+ declare function getCredentialStorageKey(skillName: string, credentialId: string, fieldKey: string, storeAs?: string): string;
1060
+ /**
1061
+ * Get OAuth2 storage keys for a skill credential.
1062
+ */
1063
+ declare function getOAuth2StorageKeys(skillName: string, credentialId: string): {
1064
+ accessToken: string;
1065
+ refreshToken: string;
1066
+ expiresAt: string;
1067
+ };
1068
+
1069
+ /**
1070
+ * Build the OAuth2 authorization URL for a skill.
1071
+ */
1072
+ declare function buildSkillOAuth2AuthUrl(skillName: string, oauth: OAuth2Config, clientId: string, redirectUri: string, state: string): string;
1073
+ /**
1074
+ * Exchange an OAuth2 authorization code for tokens and store them.
1075
+ */
1076
+ declare function exchangeSkillOAuth2Code(skillName: string, credentialId: string, oauth: OAuth2Config, clientId: string, clientSecret: string, code: string, redirectUri: string, credentialStore: EncryptedCredentialStore): Promise<void>;
1077
+ /**
1078
+ * Revoke OAuth2 tokens for a skill by removing them from the credential store.
1079
+ */
1080
+ declare function revokeSkillOAuth2(skillName: string, credentialId: string, credentialStore: EncryptedCredentialStore): Promise<void>;
1081
+
1082
+ /**
1083
+ * Compute the next run time in milliseconds for a given schedule.
1084
+ * Returns null if the schedule has no future run (e.g. one-shot in the past).
1085
+ */
1086
+ declare function computeNextRunAtMs(schedule: CronSchedule, now?: number): number | null;
1087
+ /**
1088
+ * Validate a cron expression. Returns null if valid, error message if not.
1089
+ */
1090
+ declare function validateCronExpr(expression: string): string | null;
1091
+
1092
+ interface EnabledModel {
1093
+ id: string;
1094
+ provider: string;
1095
+ modelId: string;
1096
+ label: string;
1097
+ inputPricePer1m: number;
1098
+ outputPricePer1m: number;
1099
+ enabledAt: string;
1100
+ }
1101
+ declare class ModelStore {
1102
+ private db;
1103
+ constructor(dbPath: string);
1104
+ private initSchema;
1105
+ list(provider?: string): EnabledModel[];
1106
+ enable(provider: string, modelId: string, label: string, inputPricePer1m: number, outputPricePer1m: number): EnabledModel;
1107
+ disable(provider: string, modelId: string): void;
1108
+ updatePricing(provider: string, modelId: string, inputPricePer1m: number, outputPricePer1m: number): void;
1109
+ getPricing(provider: string, modelId: string): {
1110
+ input: number;
1111
+ output: number;
1112
+ } | null;
1113
+ }
1114
+
1115
+ interface UsageRecord {
1116
+ id: number;
1117
+ provider: string;
1118
+ model: string;
1119
+ inputTokens: number;
1120
+ outputTokens: number;
1121
+ costUsd: number;
1122
+ createdAt: string;
1123
+ }
1124
+ interface UsageSummary {
1125
+ totalInputTokens: number;
1126
+ totalOutputTokens: number;
1127
+ totalTokens: number;
1128
+ totalCostUsd: number;
1129
+ recordCount: number;
1130
+ }
1131
+ declare function estimateCost(inputTokens: number, outputTokens: number, pricing: {
1132
+ input: number;
1133
+ output: number;
1134
+ }): number;
1135
+ declare class UsageStore {
1136
+ private db;
1137
+ private modelStore;
1138
+ constructor(dbPath: string, modelStore: ModelStore);
1139
+ private initSchema;
1140
+ record(provider: string, model: string, inputTokens: number, outputTokens: number): void;
1141
+ getSummary(period: "daily" | "weekly" | "monthly"): UsageSummary;
1142
+ getHistory(days?: number): Array<{
1143
+ date: string;
1144
+ tokens: number;
1145
+ costUsd: number;
1146
+ }>;
1147
+ private periodStart;
1148
+ }
1149
+
1150
+ /**
1151
+ * Hardcoded model definitions with pricing (per 1M tokens in USD).
1152
+ * OpenRouter is excluded — it fetches models from its API.
1153
+ */
1154
+ declare const MODEL_DEFINITIONS: Record<string, ModelInfo[]>;
1155
+ declare function getModelDefinitions(providerId: string): ModelInfo[];
1156
+
1157
+ interface PromptTemplate {
1158
+ id: string;
1159
+ name: string;
1160
+ content: string;
1161
+ category: string;
1162
+ createdAt: string;
1163
+ updatedAt: string;
1164
+ }
1165
+ declare class TemplateStore {
1166
+ private db;
1167
+ constructor(dbPath: string);
1168
+ private initSchema;
1169
+ list(): PromptTemplate[];
1170
+ get(id: string): PromptTemplate | null;
1171
+ create(name: string, content: string, category?: string): PromptTemplate;
1172
+ update(id: string, data: Partial<Pick<PromptTemplate, "name" | "content" | "category">>): PromptTemplate | null;
1173
+ delete(id: string): void;
1174
+ }
1175
+
1176
+ type LogLevel = "info" | "warn" | "error" | "debug";
1177
+ declare class Logger {
1178
+ private logDir;
1179
+ private stream;
1180
+ private currentDate;
1181
+ init(logDir: string): void;
1182
+ private ensureStream;
1183
+ private write;
1184
+ info(message: string, subsystem?: string): void;
1185
+ warn(message: string, subsystem?: string): void;
1186
+ error(message: string, subsystem?: string): void;
1187
+ debug(message: string, subsystem?: string): void;
1188
+ private pruneOldLogs;
1189
+ close(): void;
1190
+ }
1191
+ declare const logger: Logger;
1192
+
1193
+ export { AVAILABLE_PROVIDERS, type AgentRunParams, type AgentRunResult, AgentRunner, type AgentRunnerConfig, type AgentRunnerDeps, type AgentStreamEvent, AnthropicProvider, type Artifact, ArtifactStore, type Attachment, type ChannelType, type ContentPart, type CortaskConfig, type CredentialDefinition, type CredentialSchema, type CredentialStore, type CronDelivery, type CronEvent, type CronJob, type CronJobCreate, type CronJobState, type CronSchedule, CronService, type EmbedParams, type EmbedResult, type EnabledModel, EncryptedCredentialStore, type GenerateTextParams, type GenerateTextResult, GoogleProvider, GrokProvider, type LLMProvider, type LogLevel, MODEL_DEFINITIONS, type Message, MiniMaxProvider, type ModelInfo, ModelStore, MoonshotProvider, OllamaProvider, type OnboardingData, type OnboardingStatus, OpenAICompatibleProvider, OpenAIProvider, OpenRouterProvider, type PermissionRequest, type PromptTemplate, type ProviderId, type ProviderInfo, type ProviderValidationResult, type QuestionnaireQuestion, type QuestionnaireRequest, type QuestionnaireResponse, SUBAGENT_DEFAULTS, type Session, SessionStore, type SessionWithMessages, type SkillCodeTool, type SkillEntry, type SkillManifest, type SkillSource, type SkillToolTemplate, type StreamChunk, type SubagentRunRecord, TemplateStore, type ToolCall, type ToolDefinition, type ToolExecutionContext, type ToolHandler, type ToolResult, type UsageRecord, UsageStore, type UsageSummary, type Workspace, WorkspaceManager, buildSkillOAuth2AuthUrl, buildSkillTools, buildSystemPrompt, builtinTools, cancelChildrenOfSession, cancelSubagentRun, cleanupSubagentRecords, clearSkillCache, completeSubagentRun, computeNextRunAtMs, cortaskConfigSchema, countActiveChildren, createArtifactTool, createBrowserTool, createCronTool, createProvider, createSubagentTool, createSwitchWorkspaceTool, credentialKey, estimateCost, exchangeSkillOAuth2Code, getCredentialStorageKey, getDataDir, getDepthForSession, getEligibleSkills, getModelDefinitions, getOAuth2StorageKeys, getOrCreateSecret, getProviderInfo, getSubagentRun, installSkillFromGit, loadConfig, loadSkills, logger, migrateAllWorkspaces, migrateSessionDatabase, registerSubagentRun, removeSkill, revokeSkillOAuth2, saveConfig, setSubagentRunner, validateCronExpr, validateProvider };