mcp-copilot-cli 1.0.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.
Files changed (79) hide show
  1. package/README.md +207 -0
  2. package/bin/mcp-copilot-cli.mjs +3 -0
  3. package/dist/src/app.d.ts +71 -0
  4. package/dist/src/app.js +303 -0
  5. package/dist/src/app.js.map +1 -0
  6. package/dist/src/cli/doctor.d.ts +2 -0
  7. package/dist/src/cli/doctor.js +99 -0
  8. package/dist/src/cli/doctor.js.map +1 -0
  9. package/dist/src/config/defaults.d.ts +3 -0
  10. package/dist/src/config/defaults.js +4 -0
  11. package/dist/src/config/defaults.js.map +1 -0
  12. package/dist/src/index.d.ts +2 -0
  13. package/dist/src/index.js +98 -0
  14. package/dist/src/index.js.map +1 -0
  15. package/dist/src/mcp/system-status.d.ts +19 -0
  16. package/dist/src/mcp/system-status.js +20 -0
  17. package/dist/src/mcp/system-status.js.map +1 -0
  18. package/dist/src/mcp/task-markdown.d.ts +3 -0
  19. package/dist/src/mcp/task-markdown.js +70 -0
  20. package/dist/src/mcp/task-markdown.js.map +1 -0
  21. package/dist/src/mcp/tool-banners.d.ts +4 -0
  22. package/dist/src/mcp/tool-banners.js +26 -0
  23. package/dist/src/mcp/tool-banners.js.map +1 -0
  24. package/dist/src/mcp/tool-definitions.d.ts +109 -0
  25. package/dist/src/mcp/tool-definitions.js +125 -0
  26. package/dist/src/mcp/tool-definitions.js.map +1 -0
  27. package/dist/src/services/copilot-runtime.d.ts +28 -0
  28. package/dist/src/services/copilot-runtime.js +194 -0
  29. package/dist/src/services/copilot-runtime.js.map +1 -0
  30. package/dist/src/services/output-log.d.ts +7 -0
  31. package/dist/src/services/output-log.js +59 -0
  32. package/dist/src/services/output-log.js.map +1 -0
  33. package/dist/src/services/profile-manager.d.ts +34 -0
  34. package/dist/src/services/profile-manager.js +113 -0
  35. package/dist/src/services/profile-manager.js.map +1 -0
  36. package/dist/src/services/question-registry.d.ts +29 -0
  37. package/dist/src/services/question-registry.js +115 -0
  38. package/dist/src/services/question-registry.js.map +1 -0
  39. package/dist/src/services/spawn-validation.d.ts +9 -0
  40. package/dist/src/services/spawn-validation.js +53 -0
  41. package/dist/src/services/spawn-validation.js.map +1 -0
  42. package/dist/src/services/task-manager.d.ts +34 -0
  43. package/dist/src/services/task-manager.js +107 -0
  44. package/dist/src/services/task-manager.js.map +1 -0
  45. package/dist/src/services/task-persistence.d.ts +20 -0
  46. package/dist/src/services/task-persistence.js +67 -0
  47. package/dist/src/services/task-persistence.js.map +1 -0
  48. package/dist/src/services/task-store.d.ts +12 -0
  49. package/dist/src/services/task-store.js +167 -0
  50. package/dist/src/services/task-store.js.map +1 -0
  51. package/dist/src/services/workspace-isolation.d.ts +13 -0
  52. package/dist/src/services/workspace-isolation.js +74 -0
  53. package/dist/src/services/workspace-isolation.js.map +1 -0
  54. package/dist/src/templates/agent-prompt.d.ts +6 -0
  55. package/dist/src/templates/agent-prompt.js +58 -0
  56. package/dist/src/templates/agent-prompt.js.map +1 -0
  57. package/dist/src/types/task.d.ts +79 -0
  58. package/dist/src/types/task.js +22 -0
  59. package/dist/src/types/task.js.map +1 -0
  60. package/package.json +63 -0
  61. package/src/app.ts +341 -0
  62. package/src/cli/doctor.ts +112 -0
  63. package/src/config/defaults.ts +3 -0
  64. package/src/index.ts +128 -0
  65. package/src/mcp/system-status.ts +41 -0
  66. package/src/mcp/task-markdown.ts +81 -0
  67. package/src/mcp/tool-banners.ts +32 -0
  68. package/src/mcp/tool-definitions.ts +151 -0
  69. package/src/services/copilot-runtime.ts +247 -0
  70. package/src/services/output-log.ts +68 -0
  71. package/src/services/profile-manager.ts +165 -0
  72. package/src/services/question-registry.ts +169 -0
  73. package/src/services/spawn-validation.ts +75 -0
  74. package/src/services/task-manager.ts +144 -0
  75. package/src/services/task-persistence.ts +100 -0
  76. package/src/services/task-store.ts +207 -0
  77. package/src/services/workspace-isolation.ts +100 -0
  78. package/src/templates/agent-prompt.ts +71 -0
  79. package/src/types/task.ts +95 -0
@@ -0,0 +1,28 @@
1
+ import { type CopilotClientOptions } from '@github/copilot-sdk';
2
+ import type { TaskRecord } from '../types/task.js';
3
+ import type { CopilotProfile } from './profile-manager.js';
4
+ import type { ProfileManager } from './profile-manager.js';
5
+ import type { QuestionRegistry } from './question-registry.js';
6
+ import type { TaskManager } from './task-manager.js';
7
+ export interface BuildCopilotClientOptionsInput {
8
+ cwd: string;
9
+ profile: CopilotProfile;
10
+ cliPath?: string | undefined;
11
+ }
12
+ export declare function buildCopilotClientOptions(input: BuildCopilotClientOptionsInput): CopilotClientOptions;
13
+ export declare class CopilotRuntime {
14
+ private readonly clients;
15
+ private readonly taskManager;
16
+ private readonly profileManager;
17
+ private readonly questionRegistry;
18
+ constructor(input: {
19
+ taskManager: TaskManager;
20
+ profileManager: ProfileManager;
21
+ questionRegistry: QuestionRegistry;
22
+ });
23
+ runTask(task: TaskRecord): Promise<void>;
24
+ shutdown(): Promise<void>;
25
+ private bindSessionEvents;
26
+ private getClient;
27
+ private resolveProfile;
28
+ }
@@ -0,0 +1,194 @@
1
+ import { accessSync, constants } from 'node:fs';
2
+ import { delimiter, join } from 'node:path';
3
+ import { CopilotClient, approveAll, } from '@github/copilot-sdk';
4
+ import { DEFAULT_TIMEOUT_MS } from '../config/defaults.js';
5
+ import { buildAgentPrompt } from '../templates/agent-prompt.js';
6
+ import { TaskStatus } from '../types/task.js';
7
+ function canExecute(path) {
8
+ try {
9
+ accessSync(path, constants.X_OK);
10
+ return true;
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ function resolveCopilotCliPath(explicitPath) {
17
+ if (explicitPath && canExecute(explicitPath)) {
18
+ return explicitPath;
19
+ }
20
+ const configuredPath = process.env.COPILOT_CLI_PATH;
21
+ if (configuredPath && canExecute(configuredPath)) {
22
+ return configuredPath;
23
+ }
24
+ for (const segment of (process.env.PATH ?? '').split(delimiter)) {
25
+ if (!segment) {
26
+ continue;
27
+ }
28
+ const candidate = join(segment, 'copilot');
29
+ if (canExecute(candidate)) {
30
+ return candidate;
31
+ }
32
+ }
33
+ return explicitPath ?? configuredPath ?? 'copilot';
34
+ }
35
+ export function buildCopilotClientOptions(input) {
36
+ return {
37
+ cliPath: resolveCopilotCliPath(input.cliPath),
38
+ cliArgs: ['--config-dir', input.profile.configDir],
39
+ cwd: input.cwd,
40
+ useLoggedInUser: true,
41
+ useStdio: false,
42
+ autoStart: true,
43
+ autoRestart: false,
44
+ logLevel: 'error',
45
+ };
46
+ }
47
+ function isRateLimitError(error) {
48
+ const message = error instanceof Error ? error.message : String(error);
49
+ const normalized = message.toLowerCase();
50
+ return (normalized.includes('rate limit') ||
51
+ normalized.includes('too many requests') ||
52
+ normalized.includes('429') ||
53
+ normalized.includes('quota'));
54
+ }
55
+ export class CopilotRuntime {
56
+ clients = new Map();
57
+ taskManager;
58
+ profileManager;
59
+ questionRegistry;
60
+ constructor(input) {
61
+ this.taskManager = input.taskManager;
62
+ this.profileManager = input.profileManager;
63
+ this.questionRegistry = input.questionRegistry;
64
+ }
65
+ async runTask(task) {
66
+ try {
67
+ const profile = this.resolveProfile(task);
68
+ const client = await this.getClient(task.baseCwd ?? task.cwd, profile);
69
+ const prompt = await buildAgentPrompt({
70
+ agentType: task.agentType,
71
+ prompt: task.prompt,
72
+ contextFiles: task.contextFiles,
73
+ });
74
+ const session = task.sessionId
75
+ ? await client.resumeSession(task.sessionId, {
76
+ onPermissionRequest: approveAll,
77
+ onUserInputRequest: (request, invocation) => this.questionRegistry.register({
78
+ taskId: task.id,
79
+ sessionId: invocation.sessionId,
80
+ question: request.question,
81
+ choices: request.choices,
82
+ allowFreeform: request.allowFreeform,
83
+ }),
84
+ streaming: true,
85
+ })
86
+ : await client.createSession({
87
+ model: task.model,
88
+ onPermissionRequest: approveAll,
89
+ onUserInputRequest: (request, invocation) => this.questionRegistry.register({
90
+ taskId: task.id,
91
+ sessionId: invocation.sessionId,
92
+ question: request.question,
93
+ choices: request.choices,
94
+ allowFreeform: request.allowFreeform,
95
+ }),
96
+ streaming: true,
97
+ });
98
+ await this.taskManager.registerExecution(task.id, {
99
+ abort: async () => {
100
+ await session.abort().catch(() => { });
101
+ },
102
+ cleanup: async () => {
103
+ await session.disconnect().catch(() => { });
104
+ },
105
+ });
106
+ await this.taskManager.updateTask(task.id, {
107
+ status: TaskStatus.RUNNING,
108
+ sessionId: session.sessionId,
109
+ profileId: profile.id,
110
+ profileConfigDir: profile.configDir,
111
+ });
112
+ this.bindSessionEvents(task.id, session);
113
+ await this.taskManager.appendOutput(task.id, `[session] profile: ${profile.id} (${profile.configDir})`);
114
+ await session.sendAndWait({ prompt }, task.timeoutMs ?? DEFAULT_TIMEOUT_MS);
115
+ await this.taskManager.updateTask(task.id, {
116
+ status: TaskStatus.COMPLETED,
117
+ endTime: new Date().toISOString(),
118
+ });
119
+ }
120
+ catch (error) {
121
+ if (isRateLimitError(error)) {
122
+ this.profileManager.markFailure('rate_limit');
123
+ await this.taskManager.updateTask(task.id, {
124
+ status: TaskStatus.RATE_LIMITED,
125
+ error: error instanceof Error ? error.message : String(error),
126
+ endTime: new Date().toISOString(),
127
+ });
128
+ }
129
+ else {
130
+ await this.taskManager.updateTask(task.id, {
131
+ status: TaskStatus.FAILED,
132
+ error: error instanceof Error ? error.message : String(error),
133
+ endTime: new Date().toISOString(),
134
+ });
135
+ }
136
+ }
137
+ finally {
138
+ await this.taskManager.clearExecution(task.id);
139
+ }
140
+ }
141
+ async shutdown() {
142
+ await Promise.all([...this.clients.values()].map(async (client) => {
143
+ await client.stop().catch(async () => {
144
+ await client.forceStop().catch(() => { });
145
+ });
146
+ }));
147
+ this.clients.clear();
148
+ }
149
+ bindSessionEvents(taskId, session) {
150
+ session.on('assistant.message', (event) => {
151
+ void this.taskManager.appendOutput(taskId, event.data.content);
152
+ });
153
+ session.on('tool.execution_start', (event) => {
154
+ void this.taskManager.appendOutput(taskId, `[tool] start: ${event.data.toolName}`);
155
+ });
156
+ session.on('tool.execution_complete', (event) => {
157
+ const label = 'toolName' in event.data ? event.data.toolName : event.data.toolCallId;
158
+ void this.taskManager.appendOutput(taskId, `[tool] complete: ${label} success=${String(event.data.success)}`);
159
+ });
160
+ session.on('session.error', (event) => {
161
+ void this.taskManager.appendOutput(taskId, `[error] ${event.data.message}`);
162
+ });
163
+ }
164
+ async getClient(cwd, profile) {
165
+ const key = `${cwd}:${profile.configDir}`;
166
+ const existing = this.clients.get(key);
167
+ if (existing) {
168
+ return existing;
169
+ }
170
+ const client = new CopilotClient(buildCopilotClientOptions({ cwd, profile }));
171
+ await client.start();
172
+ const auth = await client.getAuthStatus();
173
+ if (!auth.isAuthenticated) {
174
+ throw new Error(`Copilot profile "${profile.configDir}" is not authenticated. Run \`copilot login --config-dir ${profile.configDir}\`.`);
175
+ }
176
+ this.clients.set(key, client);
177
+ return client;
178
+ }
179
+ resolveProfile(task) {
180
+ if (task.profileConfigDir && task.profileId) {
181
+ const match = this.profileManager.getProfiles().find((profile) => profile.id === task.profileId);
182
+ if (match) {
183
+ return match;
184
+ }
185
+ return {
186
+ id: task.profileId,
187
+ configDir: task.profileConfigDir,
188
+ failureCount: 0,
189
+ };
190
+ }
191
+ return this.profileManager.getCurrentProfile();
192
+ }
193
+ }
194
+ //# sourceMappingURL=copilot-runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"copilot-runtime.js","sourceRoot":"","sources":["../../../src/services/copilot-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,EACL,aAAa,EACb,UAAU,GAGX,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAEhE,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC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E,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CACb,oBAAoB,OAAO,CAAC,SAAS,4DAA4D,OAAO,CAAC,SAAS,KAAK,CACxH,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9B,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,cAAc,CAAC,IAAgB;QACrC,IAAI,IAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YAC5C,MAAM,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,WAAW,EAAE,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,EAAE,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC;YACjG,IAAI,KAAK,EAAE,CAAC;gBACV,OAAO,KAAK,CAAC;YACf,CAAC;YACD,OAAO;gBACL,EAAE,EAAE,IAAI,CAAC,SAAS;gBAClB,SAAS,EAAE,IAAI,CAAC,gBAAgB;gBAChC,YAAY,EAAE,CAAC;aAChB,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC,cAAc,CAAC,iBAAiB,EAAE,CAAC;IACjD,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ export declare function getOutputDir(cwd: string): string;
2
+ export declare function getOutputPath(cwd: string, taskId: string): string;
3
+ export declare class OutputLogService {
4
+ create(cwd: string, taskId: string): Promise<string>;
5
+ append(cwd: string, taskId: string, line: string): Promise<void>;
6
+ finalize(cwd: string, taskId: string, status: string, error?: string): Promise<void>;
7
+ }
@@ -0,0 +1,59 @@
1
+ import { mkdir, open, readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ const OUTPUT_DIR_NAME = '.super-agents';
4
+ function sanitizeTaskId(taskId) {
5
+ return taskId.replace(/[\/\\:\x00]/g, '_');
6
+ }
7
+ export function getOutputDir(cwd) {
8
+ return join(cwd, OUTPUT_DIR_NAME);
9
+ }
10
+ export function getOutputPath(cwd, taskId) {
11
+ return join(getOutputDir(cwd), `${sanitizeTaskId(taskId)}.output`);
12
+ }
13
+ function timestamp() {
14
+ return new Date().toISOString();
15
+ }
16
+ export class OutputLogService {
17
+ async create(cwd, taskId) {
18
+ await mkdir(getOutputDir(cwd), { recursive: true });
19
+ const outputPath = getOutputPath(cwd, taskId);
20
+ const handle = await open(outputPath, 'a+');
21
+ try {
22
+ const existing = await readFile(outputPath, 'utf8').catch(() => '');
23
+ if (!existing) {
24
+ await handle.writeFile(`# Task: ${taskId}\n# Started: ${timestamp()}\n# Working directory: ${cwd}\n${'─'.repeat(60)}\n`, 'utf8');
25
+ }
26
+ }
27
+ finally {
28
+ await handle.close();
29
+ }
30
+ return outputPath;
31
+ }
32
+ async append(cwd, taskId, line) {
33
+ const outputPath = await this.create(cwd, taskId);
34
+ const handle = await open(outputPath, 'a');
35
+ try {
36
+ await handle.writeFile(`[${timestamp()}] ${line}\n`, 'utf8');
37
+ }
38
+ finally {
39
+ await handle.close();
40
+ }
41
+ }
42
+ async finalize(cwd, taskId, status, error) {
43
+ const outputPath = await this.create(cwd, taskId);
44
+ const handle = await open(outputPath, 'a');
45
+ try {
46
+ const footer = [
47
+ `${'─'.repeat(60)}`,
48
+ `# Completed: ${timestamp()}`,
49
+ `# Status: ${status}`,
50
+ error ? `# Error: ${error}` : null,
51
+ ].filter(Boolean).join('\n');
52
+ await handle.writeFile(`${footer}\n`, 'utf8');
53
+ }
54
+ finally {
55
+ await handle.close();
56
+ }
57
+ }
58
+ }
59
+ //# sourceMappingURL=output-log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output-log.js","sourceRoot":"","sources":["../../../src/services/output-log.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAA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: string;
4
+ configDir: string;
5
+ cooldownUntil?: number | undefined;
6
+ failureCount: number;
7
+ lastFailureReason?: string | undefined;
8
+ }
9
+ export interface ProfileManagerOptions {
10
+ profileDirs?: string[] | undefined;
11
+ cooldownMs?: number | undefined;
12
+ now?: (() => number) | undefined;
13
+ persistedProfiles?: PersistedProfileState[] | undefined;
14
+ }
15
+ export interface ProfileRotationResult {
16
+ success: boolean;
17
+ allExhausted?: boolean | undefined;
18
+ currentProfile?: CopilotProfile | undefined;
19
+ }
20
+ export declare class ProfileManager {
21
+ private readonly cooldownMs;
22
+ private readonly now;
23
+ private readonly profiles;
24
+ private currentIndex;
25
+ constructor(options?: ProfileManagerOptions);
26
+ static fromEnvironment(now?: () => number): ProfileManager;
27
+ hydrate(persistedProfiles: PersistedProfileState[]): void;
28
+ getProfiles(): CopilotProfile[];
29
+ getCurrentProfile(): CopilotProfile;
30
+ markFailure(reason: string): ProfileRotationResult;
31
+ resetExpiredCooldowns(): void;
32
+ toPersistedState(): PersistedProfileState[];
33
+ private findFirstAvailableIndex;
34
+ }
@@ -0,0 +1,113 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ const DEFAULT_COOLDOWN_MS = 60_000;
4
+ function defaultProfileDir() {
5
+ return join(homedir(), '.copilot');
6
+ }
7
+ function dedupeProfileDirs(profileDirs) {
8
+ const seen = new Set();
9
+ const result = [];
10
+ for (const dir of profileDirs) {
11
+ const normalized = dir.trim();
12
+ if (!normalized || seen.has(normalized)) {
13
+ continue;
14
+ }
15
+ seen.add(normalized);
16
+ result.push(normalized);
17
+ }
18
+ return result.length > 0 ? result : [defaultProfileDir()];
19
+ }
20
+ export class ProfileManager {
21
+ cooldownMs;
22
+ now;
23
+ profiles;
24
+ currentIndex = 0;
25
+ constructor(options = {}) {
26
+ this.cooldownMs = options.cooldownMs ?? DEFAULT_COOLDOWN_MS;
27
+ this.now = options.now ?? Date.now;
28
+ const configuredDirs = dedupeProfileDirs(options.profileDirs ?? [defaultProfileDir()]);
29
+ const persistedByDir = new Map((options.persistedProfiles ?? []).map((profile) => [profile.configDir, profile]));
30
+ this.profiles = configuredDirs.map((configDir, index) => {
31
+ const persisted = persistedByDir.get(configDir);
32
+ return {
33
+ id: persisted?.id ?? `profile-${index + 1}`,
34
+ configDir,
35
+ cooldownUntil: persisted?.cooldownUntil,
36
+ failureCount: persisted?.failureCount ?? 0,
37
+ lastFailureReason: persisted?.lastFailureReason,
38
+ };
39
+ });
40
+ this.currentIndex = this.findFirstAvailableIndex();
41
+ }
42
+ static fromEnvironment(now) {
43
+ const raw = process.env.COPILOT_CONFIG_DIRS;
44
+ const dirs = raw
45
+ ? raw.split(',').map((entry) => entry.trim()).filter(Boolean)
46
+ : [defaultProfileDir()];
47
+ return new ProfileManager({ profileDirs: dirs, now });
48
+ }
49
+ hydrate(persistedProfiles) {
50
+ const persistedByDir = new Map(persistedProfiles.map((profile) => [profile.configDir, profile]));
51
+ for (const profile of this.profiles) {
52
+ const persisted = persistedByDir.get(profile.configDir);
53
+ if (!persisted) {
54
+ continue;
55
+ }
56
+ profile.failureCount = persisted.failureCount;
57
+ profile.cooldownUntil = persisted.cooldownUntil;
58
+ profile.lastFailureReason = persisted.lastFailureReason;
59
+ }
60
+ this.resetExpiredCooldowns();
61
+ }
62
+ getProfiles() {
63
+ return this.profiles.map((profile) => ({ ...profile }));
64
+ }
65
+ getCurrentProfile() {
66
+ this.resetExpiredCooldowns();
67
+ return { ...this.profiles[this.currentIndex] };
68
+ }
69
+ markFailure(reason) {
70
+ const current = this.profiles[this.currentIndex];
71
+ if (!current) {
72
+ return { success: false, allExhausted: true };
73
+ }
74
+ current.failureCount += 1;
75
+ current.lastFailureReason = reason;
76
+ current.cooldownUntil = this.now() + this.cooldownMs;
77
+ const nextIndex = this.findFirstAvailableIndex();
78
+ if (nextIndex === -1) {
79
+ return { success: false, allExhausted: true };
80
+ }
81
+ this.currentIndex = nextIndex;
82
+ return {
83
+ success: true,
84
+ currentProfile: this.getCurrentProfile(),
85
+ };
86
+ }
87
+ resetExpiredCooldowns() {
88
+ const now = this.now();
89
+ for (const profile of this.profiles) {
90
+ if (profile.cooldownUntil !== undefined && profile.cooldownUntil <= now) {
91
+ profile.cooldownUntil = undefined;
92
+ }
93
+ }
94
+ const nextIndex = this.findFirstAvailableIndex();
95
+ if (nextIndex !== -1) {
96
+ this.currentIndex = nextIndex;
97
+ }
98
+ }
99
+ toPersistedState() {
100
+ return this.profiles.map((profile) => ({
101
+ id: profile.id,
102
+ configDir: profile.configDir,
103
+ cooldownUntil: profile.cooldownUntil,
104
+ failureCount: profile.failureCount,
105
+ lastFailureReason: profile.lastFailureReason,
106
+ }));
107
+ }
108
+ findFirstAvailableIndex() {
109
+ const now = this.now();
110
+ return this.profiles.findIndex((profile) => profile.cooldownUntil === undefined || profile.cooldownUntil <= now);
111
+ }
112
+ }
113
+ //# sourceMappingURL=profile-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile-manager.js","sourceRoot":"","sources":["../../../src/services/profile-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAyBjC,MAAM,mBAAmB,GAAG,MAAM,CAAC;AAEnC,SAAS,iBAAiB;IACxB,OAAO,IAAI,CAAC,OAAO,EAAE,EAAE,UAAU,CAAC,CAAC;AACrC,CAAC;AAED,SAAS,iBAAiB,CAAC,WAAqB;IAC9C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;YACxC,SAAS;QACX,CAAC;QACD,IAAI,CAAC,G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,uBAAuB,EAAE,CAAC;QACjD,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAChC,CAAC;IACH,CAAC;IAED,gBAAgB;QACd,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;YACrC,EAAE,EAAE,OAAO,CAAC,EAAE;YACd,SAAS,EAAE,OAAO,CAAC,SAAS;YAC5B,aAAa,EAAE,OAAO,CAAC,aAAa;YACpC,YAAY,EAAE,OAAO,CAAC,YAAY;YAClC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;SAC7C,CAAC,CAAC,CAAC;IACN,CAAC;IAEO,uBAAuB;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,IAAI,OAAO,CAAC,aAAa,IAAI,GAAG,CAAC,CAAC;IACnH,CAAC;CACF"}
@@ -0,0 +1,29 @@
1
+ import type { PendingQuestion } from '../types/task.js';
2
+ import type { TaskManager } from './task-manager.js';
3
+ interface RegisterQuestionInput {
4
+ taskId: string;
5
+ sessionId: string;
6
+ question: string;
7
+ choices?: string[] | undefined;
8
+ allowFreeform?: boolean | undefined;
9
+ }
10
+ export declare class QuestionRegistry {
11
+ private readonly taskManager;
12
+ private readonly timeoutMs;
13
+ private readonly pending;
14
+ constructor(taskManager: TaskManager, timeoutMs?: number);
15
+ register(input: RegisterQuestionInput): Promise<{
16
+ answer: string;
17
+ wasFreeform: boolean;
18
+ }>;
19
+ submitAnswer(taskId: string, rawAnswer: string): {
20
+ success: boolean;
21
+ resolvedAnswer?: string | undefined;
22
+ error?: string | undefined;
23
+ };
24
+ hasPendingQuestion(taskId: string): boolean;
25
+ getAllPendingQuestions(): Map<string, PendingQuestion>;
26
+ clear(taskId: string, reason: string): void;
27
+ private parseAnswer;
28
+ }
29
+ export {};
@@ -0,0 +1,115 @@
1
+ import { TaskStatus } from '../types/task.js';
2
+ const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
3
+ export class QuestionRegistry {
4
+ taskManager;
5
+ timeoutMs;
6
+ pending = new Map();
7
+ constructor(taskManager, timeoutMs = DEFAULT_TIMEOUT_MS) {
8
+ this.taskManager = taskManager;
9
+ this.timeoutMs = timeoutMs;
10
+ }
11
+ register(input) {
12
+ this.clear(input.taskId, 'replaced by newer question');
13
+ return new Promise((resolve, reject) => {
14
+ const question = {
15
+ question: input.question,
16
+ choices: input.choices,
17
+ allowFreeform: input.allowFreeform ?? true,
18
+ askedAt: new Date().toISOString(),
19
+ sessionId: input.sessionId,
20
+ };
21
+ const timeout = setTimeout(() => {
22
+ void this.taskManager.updateTask(input.taskId, {
23
+ status: TaskStatus.FAILED,
24
+ error: 'Task failed: user question timed out after 30 minutes',
25
+ pendingQuestion: undefined,
26
+ endTime: new Date().toISOString(),
27
+ });
28
+ reject(new Error('Question timed out'));
29
+ this.pending.delete(input.taskId);
30
+ }, this.timeoutMs);
31
+ timeout.unref();
32
+ this.pending.set(input.taskId, { question, resolve, reject, timeout });
33
+ void this.taskManager.updateTask(input.taskId, {
34
+ status: TaskStatus.WAITING_ANSWER,
35
+ pendingQuestion: question,
36
+ });
37
+ void this.taskManager.appendOutput(input.taskId, `[question] ${input.question}`);
38
+ });
39
+ }
40
+ submitAnswer(taskId, rawAnswer) {
41
+ const binding = this.pending.get(taskId);
42
+ if (!binding) {
43
+ return { success: false, error: 'No pending question for this task' };
44
+ }
45
+ const parsed = this.parseAnswer(rawAnswer, binding.question);
46
+ if (!parsed.success) {
47
+ return parsed;
48
+ }
49
+ clearTimeout(binding.timeout);
50
+ binding.resolve({ answer: parsed.resolvedAnswer, wasFreeform: parsed.wasFreeform });
51
+ this.pending.delete(taskId);
52
+ void this.taskManager.updateTask(taskId, {
53
+ status: TaskStatus.RUNNING,
54
+ pendingQuestion: undefined,
55
+ });
56
+ void this.taskManager.appendOutput(taskId, `[question] Answer submitted: ${parsed.resolvedAnswer}`);
57
+ return parsed;
58
+ }
59
+ hasPendingQuestion(taskId) {
60
+ return this.pending.has(taskId);
61
+ }
62
+ getAllPendingQuestions() {
63
+ return new Map([...this.pending.entries()].map(([taskId, binding]) => [taskId, binding.question]));
64
+ }
65
+ clear(taskId, reason) {
66
+ const binding = this.pending.get(taskId);
67
+ if (!binding) {
68
+ return;
69
+ }
70
+ clearTimeout(binding.timeout);
71
+ binding.reject(new Error(reason));
72
+ this.pending.delete(taskId);
73
+ void this.taskManager.updateTask(taskId, { pendingQuestion: undefined });
74
+ }
75
+ parseAnswer(rawAnswer, question) {
76
+ const answer = rawAnswer.trim();
77
+ if (!answer) {
78
+ return { success: false, error: 'Answer cannot be empty' };
79
+ }
80
+ if (question.choices && /^\d+$/.test(answer)) {
81
+ const index = Number.parseInt(answer, 10) - 1;
82
+ if (index < 0 || index >= question.choices.length) {
83
+ return { success: false, error: `Invalid choice. Please enter 1-${question.choices.length}.` };
84
+ }
85
+ return {
86
+ success: true,
87
+ resolvedAnswer: question.choices[index],
88
+ wasFreeform: false,
89
+ };
90
+ }
91
+ if (answer.toUpperCase().startsWith('OTHER:') && question.allowFreeform) {
92
+ return {
93
+ success: true,
94
+ resolvedAnswer: answer.slice('OTHER:'.length).trim(),
95
+ wasFreeform: true,
96
+ };
97
+ }
98
+ if (question.choices?.includes(answer)) {
99
+ return {
100
+ success: true,
101
+ resolvedAnswer: answer,
102
+ wasFreeform: false,
103
+ };
104
+ }
105
+ if (question.allowFreeform) {
106
+ return {
107
+ success: true,
108
+ resolvedAnswer: answer,
109
+ wasFreeform: true,
110
+ };
111
+ }
112
+ return { success: false, error: 'Invalid answer' };
113
+ }
114
+ }
115
+ //# sourceMappingURL=question-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"question-registry.js","sourceRoot":"","sources":["../../../src/services/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B,EAAE,CAAC;IACrD,CAAC;CACF"}
@@ -0,0 +1,9 @@
1
+ import type { ContextFile } from '../types/task.js';
2
+ import type { SpawnAgentInput } from '../mcp/tool-definitions.js';
3
+ export interface ValidateSpawnAgentInputArgs {
4
+ input: SpawnAgentInput;
5
+ baseCwd: string;
6
+ }
7
+ export declare function validateSpawnAgentInput(args: ValidateSpawnAgentInputArgs): Promise<{
8
+ contextFiles: ContextFile[] | undefined;
9
+ }>;