cli-copilot-worker 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.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -0
  3. package/bin/cli-copilot-worker.mjs +3 -0
  4. package/dist/src/cli.d.ts +2 -0
  5. package/dist/src/cli.js +682 -0
  6. package/dist/src/cli.js.map +1 -0
  7. package/dist/src/core/copilot.d.ts +13 -0
  8. package/dist/src/core/copilot.js +56 -0
  9. package/dist/src/core/copilot.js.map +1 -0
  10. package/dist/src/core/failure-classifier.d.ts +8 -0
  11. package/dist/src/core/failure-classifier.js +148 -0
  12. package/dist/src/core/failure-classifier.js.map +1 -0
  13. package/dist/src/core/ids.d.ts +1 -0
  14. package/dist/src/core/ids.js +11 -0
  15. package/dist/src/core/ids.js.map +1 -0
  16. package/dist/src/core/markdown.d.ts +5 -0
  17. package/dist/src/core/markdown.js +14 -0
  18. package/dist/src/core/markdown.js.map +1 -0
  19. package/dist/src/core/paths.d.ts +18 -0
  20. package/dist/src/core/paths.js +42 -0
  21. package/dist/src/core/paths.js.map +1 -0
  22. package/dist/src/core/profile-faults.d.ts +15 -0
  23. package/dist/src/core/profile-faults.js +110 -0
  24. package/dist/src/core/profile-faults.js.map +1 -0
  25. package/dist/src/core/profile-manager.d.ts +25 -0
  26. package/dist/src/core/profile-manager.js +162 -0
  27. package/dist/src/core/profile-manager.js.map +1 -0
  28. package/dist/src/core/question-registry.d.ts +25 -0
  29. package/dist/src/core/question-registry.js +154 -0
  30. package/dist/src/core/question-registry.js.map +1 -0
  31. package/dist/src/core/store.d.ts +39 -0
  32. package/dist/src/core/store.js +206 -0
  33. package/dist/src/core/store.js.map +1 -0
  34. package/dist/src/core/types.d.ts +152 -0
  35. package/dist/src/core/types.js +2 -0
  36. package/dist/src/core/types.js.map +1 -0
  37. package/dist/src/daemon/client.d.ts +6 -0
  38. package/dist/src/daemon/client.js +117 -0
  39. package/dist/src/daemon/client.js.map +1 -0
  40. package/dist/src/daemon/server.d.ts +1 -0
  41. package/dist/src/daemon/server.js +149 -0
  42. package/dist/src/daemon/server.js.map +1 -0
  43. package/dist/src/daemon/service.d.ts +69 -0
  44. package/dist/src/daemon/service.js +800 -0
  45. package/dist/src/daemon/service.js.map +1 -0
  46. package/dist/src/doctor.d.ts +1 -0
  47. package/dist/src/doctor.js +74 -0
  48. package/dist/src/doctor.js.map +1 -0
  49. package/dist/src/index.d.ts +3 -0
  50. package/dist/src/index.js +4 -0
  51. package/dist/src/index.js.map +1 -0
  52. package/dist/src/output.d.ts +28 -0
  53. package/dist/src/output.js +307 -0
  54. package/dist/src/output.js.map +1 -0
  55. package/package.json +59 -0
  56. package/src/cli.ts +881 -0
  57. package/src/core/copilot.ts +75 -0
  58. package/src/core/failure-classifier.ts +202 -0
  59. package/src/core/ids.ts +11 -0
  60. package/src/core/markdown.ts +19 -0
  61. package/src/core/paths.ts +56 -0
  62. package/src/core/profile-faults.ts +140 -0
  63. package/src/core/profile-manager.ts +220 -0
  64. package/src/core/question-registry.ts +191 -0
  65. package/src/core/store.ts +273 -0
  66. package/src/core/types.ts +211 -0
  67. package/src/daemon/client.ts +137 -0
  68. package/src/daemon/server.ts +167 -0
  69. package/src/daemon/service.ts +968 -0
  70. package/src/doctor.ts +82 -0
  71. package/src/index.ts +3 -0
  72. package/src/output.ts +391 -0
@@ -0,0 +1,162 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ const DEFAULT_PROFILE_COOLDOWNS = {
4
+ auth: 5 * 60_000,
5
+ rate_limit: 15 * 60_000,
6
+ connection: 60_000,
7
+ transient: 30_000,
8
+ fatal: 0,
9
+ };
10
+ function defaultProfileDir() {
11
+ return join(homedir(), '.copilot');
12
+ }
13
+ function dedupeProfileDirs(profileDirs) {
14
+ const seen = new Set();
15
+ const result = [];
16
+ for (const dir of profileDirs) {
17
+ const normalized = dir.trim();
18
+ if (!normalized || seen.has(normalized)) {
19
+ continue;
20
+ }
21
+ seen.add(normalized);
22
+ result.push(normalized);
23
+ }
24
+ return result.length > 0 ? result : [defaultProfileDir()];
25
+ }
26
+ function buildCooldowns(options) {
27
+ const cooldowns = {
28
+ ...DEFAULT_PROFILE_COOLDOWNS,
29
+ };
30
+ if (options?.cooldownMs !== undefined) {
31
+ cooldowns.auth = options.cooldownMs;
32
+ cooldowns.rate_limit = options.cooldownMs;
33
+ cooldowns.connection = options.cooldownMs;
34
+ cooldowns.transient = options.cooldownMs;
35
+ }
36
+ for (const [category, value] of Object.entries(options?.cooldowns ?? {})) {
37
+ if (value !== undefined) {
38
+ cooldowns[category] = value;
39
+ }
40
+ }
41
+ return cooldowns;
42
+ }
43
+ export class ProfileManager {
44
+ cooldowns;
45
+ now;
46
+ profiles;
47
+ currentIndex = 0;
48
+ constructor(options) {
49
+ this.cooldowns = buildCooldowns({
50
+ cooldownMs: options?.cooldownMs,
51
+ cooldowns: options?.cooldowns,
52
+ });
53
+ this.now = options?.now ?? Date.now;
54
+ const configuredDirs = dedupeProfileDirs(options?.profileDirs ?? [defaultProfileDir()]);
55
+ const persistedByDir = new Map((options?.persistedProfiles ?? []).map((profile) => [profile.configDir, profile]));
56
+ this.profiles = configuredDirs.map((configDir, index) => {
57
+ const persisted = persistedByDir.get(configDir);
58
+ return {
59
+ id: persisted?.id ?? `profile-${index + 1}`,
60
+ configDir,
61
+ cooldownUntil: persisted?.cooldownUntil,
62
+ failureCount: persisted?.failureCount ?? 0,
63
+ lastFailureReason: persisted?.lastFailureReason,
64
+ lastFailureCategory: persisted?.lastFailureCategory,
65
+ lastFailureAt: persisted?.lastFailureAt,
66
+ lastSuccessAt: persisted?.lastSuccessAt,
67
+ };
68
+ });
69
+ this.currentIndex = this.findFirstAvailableIndex();
70
+ }
71
+ static fromEnvironment(persistedProfiles) {
72
+ const raw = process.env.COPILOT_CONFIG_DIRS;
73
+ const dirs = raw
74
+ ? raw.split(',').map((entry) => entry.trim()).filter(Boolean)
75
+ : [defaultProfileDir()];
76
+ return new ProfileManager({ profileDirs: dirs, persistedProfiles });
77
+ }
78
+ getCandidateProfiles() {
79
+ this.resetExpiredCooldowns();
80
+ return this.profiles
81
+ .filter((profile) => profile.cooldownUntil === undefined || profile.cooldownUntil <= this.now())
82
+ .map((profile) => ({ ...profile }));
83
+ }
84
+ getCurrentProfile() {
85
+ this.resetExpiredCooldowns();
86
+ const profile = this.profiles[this.currentIndex] ?? this.profiles[0];
87
+ if (!profile) {
88
+ throw new Error('No profiles configured');
89
+ }
90
+ return { ...profile };
91
+ }
92
+ markFailure(profileIdOrReason, category, reason) {
93
+ const usingTypedSignature = reason !== undefined;
94
+ const profile = usingTypedSignature
95
+ ? this.profiles.find((entry) => entry.id === profileIdOrReason)
96
+ : this.profiles[this.currentIndex];
97
+ if (!profile) {
98
+ return;
99
+ }
100
+ const failureCategory = usingTypedSignature ? category : 'transient';
101
+ const failureReason = usingTypedSignature ? reason : profileIdOrReason;
102
+ profile.failureCount += 1;
103
+ profile.lastFailureReason = failureReason;
104
+ profile.lastFailureCategory = failureCategory;
105
+ profile.lastFailureAt = new Date(this.now()).toISOString();
106
+ const cooldownMs = this.getCooldownMs(failureCategory);
107
+ profile.cooldownUntil = cooldownMs > 0 ? this.now() + cooldownMs : undefined;
108
+ if (!usingTypedSignature) {
109
+ const nextIndex = this.findFirstAvailableIndex();
110
+ if (nextIndex !== -1) {
111
+ this.currentIndex = nextIndex;
112
+ }
113
+ }
114
+ }
115
+ markSuccess(profileId) {
116
+ const profile = this.profiles.find((entry) => entry.id === profileId);
117
+ if (!profile) {
118
+ return;
119
+ }
120
+ profile.cooldownUntil = undefined;
121
+ profile.lastSuccessAt = new Date(this.now()).toISOString();
122
+ const nextIndex = this.findFirstAvailableIndex();
123
+ if (nextIndex !== -1) {
124
+ this.currentIndex = nextIndex;
125
+ }
126
+ }
127
+ getCooldownMs(category) {
128
+ return this.cooldowns[category];
129
+ }
130
+ getProfiles() {
131
+ return this.profiles.map((profile) => ({ ...profile }));
132
+ }
133
+ toPersistedState() {
134
+ return this.profiles.map((profile) => ({
135
+ id: profile.id,
136
+ configDir: profile.configDir,
137
+ cooldownUntil: profile.cooldownUntil,
138
+ failureCount: profile.failureCount,
139
+ lastFailureReason: profile.lastFailureReason,
140
+ lastFailureCategory: profile.lastFailureCategory,
141
+ lastFailureAt: profile.lastFailureAt,
142
+ lastSuccessAt: profile.lastSuccessAt,
143
+ }));
144
+ }
145
+ resetExpiredCooldowns() {
146
+ const now = this.now();
147
+ for (const profile of this.profiles) {
148
+ if (profile.cooldownUntil !== undefined && profile.cooldownUntil <= now) {
149
+ profile.cooldownUntil = undefined;
150
+ }
151
+ }
152
+ const nextIndex = this.findFirstAvailableIndex();
153
+ if (nextIndex !== -1) {
154
+ this.currentIndex = nextIndex;
155
+ }
156
+ }
157
+ findFirstAvailableIndex() {
158
+ const now = this.now();
159
+ return this.profiles.findIndex((profile) => profile.cooldownUntil === undefined || profile.cooldownUntil <= now);
160
+ }
161
+ }
162
+ //# sourceMappingURL=profile-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile-manager.js","sourceRoot":"","sources":["../../../src/core/profile-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAQjC,MAAM,yBAAyB,GAA2C;IACxE,IAAI,EAAE,CAAC,GAAG,MAAM;IAChB,UAAU,EAAE,EAAE,GAAG,MAAM;IACvB,UAAU,EAAE,MAAM;IAClB,SAAS,EAAE,MAAM;IACjB,KAAK,EAAE,CAAC;CACT,CAAC;AAEF,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;IAE5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ED,MAAM,SAAS,GAAG,IAAI,CAAC,uBAAuB,EAAE,CAAC;QACjD,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAChC,CAAC;IACH,CAAC;IAEO,uBAAuB;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAC5B,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS,IAAI,OAAO,CAAC,aAAa,IAAI,GAAG,CACjF,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,25 @@
1
+ import type { PersistentStore } from './store.js';
2
+ export declare class QuestionRegistry {
3
+ private readonly store;
4
+ private readonly onEvent?;
5
+ private readonly timeoutMs;
6
+ private readonly pending;
7
+ constructor(store: PersistentStore, onEvent?: ((conversationId: string, event: string, data: Record<string, unknown>) => void) | undefined, timeoutMs?: number);
8
+ register(input: {
9
+ conversationId: string;
10
+ jobId: string;
11
+ sessionId: string;
12
+ question: string;
13
+ choices?: string[] | undefined;
14
+ allowFreeform?: boolean | undefined;
15
+ }): Promise<{
16
+ answer: string;
17
+ wasFreeform: boolean;
18
+ }>;
19
+ submitAnswer(conversationId: string, rawAnswer: string): {
20
+ success: boolean;
21
+ resolvedAnswer?: string;
22
+ error?: string;
23
+ };
24
+ clear(conversationId: string, reason: string): void;
25
+ }
@@ -0,0 +1,154 @@
1
+ function parseAnswer(rawAnswer, question) {
2
+ const answer = rawAnswer.trim();
3
+ if (!answer) {
4
+ return { success: false, error: 'Answer cannot be empty' };
5
+ }
6
+ if (question.choices && /^\d+$/.test(answer)) {
7
+ const index = Number.parseInt(answer, 10) - 1;
8
+ if (index < 0 || index >= question.choices.length) {
9
+ return { success: false, error: `Invalid choice. Please enter 1-${question.choices.length}.` };
10
+ }
11
+ return {
12
+ success: true,
13
+ resolvedAnswer: question.choices[index],
14
+ wasFreeform: false,
15
+ };
16
+ }
17
+ if (question.choices?.some((choice) => choice.toLowerCase() === answer.toLowerCase())) {
18
+ const resolved = question.choices.find((choice) => choice.toLowerCase() === answer.toLowerCase());
19
+ return {
20
+ success: true,
21
+ resolvedAnswer: resolved,
22
+ wasFreeform: false,
23
+ };
24
+ }
25
+ if (answer.toUpperCase().startsWith('OTHER:') && question.allowFreeform) {
26
+ const custom = answer.slice('OTHER:'.length).trim();
27
+ if (!custom) {
28
+ return { success: false, error: 'OTHER: requires text after the colon.' };
29
+ }
30
+ return {
31
+ success: true,
32
+ resolvedAnswer: custom,
33
+ wasFreeform: true,
34
+ };
35
+ }
36
+ if (question.allowFreeform) {
37
+ return {
38
+ success: true,
39
+ resolvedAnswer: answer,
40
+ wasFreeform: true,
41
+ };
42
+ }
43
+ return { success: false, error: 'Invalid answer' };
44
+ }
45
+ export class QuestionRegistry {
46
+ store;
47
+ onEvent;
48
+ timeoutMs;
49
+ pending = new Map();
50
+ constructor(store, onEvent, timeoutMs = 30 * 60 * 1000) {
51
+ this.store = store;
52
+ this.onEvent = onEvent;
53
+ this.timeoutMs = timeoutMs;
54
+ }
55
+ async register(input) {
56
+ this.clear(input.conversationId, 'replaced by a newer question');
57
+ return new Promise((resolve, reject) => {
58
+ const pendingQuestion = {
59
+ question: input.question,
60
+ choices: input.choices,
61
+ allowFreeform: input.allowFreeform ?? true,
62
+ askedAt: new Date().toISOString(),
63
+ sessionId: input.sessionId,
64
+ };
65
+ const timeout = setTimeout(() => {
66
+ void this.store.appendTranscript({
67
+ conversationId: input.conversationId,
68
+ jobId: input.jobId,
69
+ role: 'error',
70
+ content: 'Question timed out after 30 minutes.',
71
+ });
72
+ this.store.updatePendingQuestion(input.conversationId, undefined, 'failed');
73
+ this.store.finalizeJob(input.jobId, 'failed', 'Question timed out after 30 minutes');
74
+ reject(new Error('Question timed out'));
75
+ this.pending.delete(input.conversationId);
76
+ void this.store.persist();
77
+ }, this.timeoutMs);
78
+ timeout.unref();
79
+ this.pending.set(input.conversationId, {
80
+ conversationId: input.conversationId,
81
+ jobId: input.jobId,
82
+ sessionId: input.sessionId,
83
+ question: pendingQuestion,
84
+ timeout,
85
+ resolve,
86
+ reject,
87
+ });
88
+ this.store.updatePendingQuestion(input.conversationId, pendingQuestion, 'waiting_answer');
89
+ this.store.updateJob(input.jobId, { status: 'waiting_answer' });
90
+ void this.store.appendTranscript({
91
+ conversationId: input.conversationId,
92
+ jobId: input.jobId,
93
+ role: 'question',
94
+ content: input.question,
95
+ data: {
96
+ choices: input.choices,
97
+ allowFreeform: input.allowFreeform ?? true,
98
+ },
99
+ });
100
+ this.onEvent?.(input.conversationId, 'question', {
101
+ conversationId: input.conversationId,
102
+ question: input.question,
103
+ choices: input.choices ?? [],
104
+ allowFreeform: input.allowFreeform ?? true,
105
+ });
106
+ void this.store.persist();
107
+ });
108
+ }
109
+ submitAnswer(conversationId, rawAnswer) {
110
+ const binding = this.pending.get(conversationId);
111
+ if (!binding) {
112
+ return { success: false, error: 'No pending question for this conversation' };
113
+ }
114
+ const parsed = parseAnswer(rawAnswer, binding.question);
115
+ if (!parsed.success) {
116
+ return parsed;
117
+ }
118
+ clearTimeout(binding.timeout);
119
+ binding.resolve({
120
+ answer: parsed.resolvedAnswer,
121
+ wasFreeform: parsed.wasFreeform,
122
+ });
123
+ this.pending.delete(conversationId);
124
+ this.store.updatePendingQuestion(conversationId, undefined, 'running');
125
+ this.store.updateJob(binding.jobId, { status: 'running' });
126
+ void this.store.appendTranscript({
127
+ conversationId,
128
+ jobId: binding.jobId,
129
+ role: 'answer',
130
+ content: parsed.resolvedAnswer,
131
+ });
132
+ this.onEvent?.(conversationId, 'answer', {
133
+ conversationId,
134
+ answer: parsed.resolvedAnswer,
135
+ });
136
+ void this.store.persist();
137
+ return {
138
+ success: true,
139
+ resolvedAnswer: parsed.resolvedAnswer,
140
+ };
141
+ }
142
+ clear(conversationId, reason) {
143
+ const binding = this.pending.get(conversationId);
144
+ if (!binding) {
145
+ return;
146
+ }
147
+ clearTimeout(binding.timeout);
148
+ binding.reject(new Error(reason));
149
+ this.pending.delete(conversationId);
150
+ this.store.updatePendingQuestion(conversationId, undefined, 'idle');
151
+ void this.store.persist();
152
+ }
153
+ }
154
+ //# sourceMappingURL=question-registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"question-registry.js","sourceRoot":"","sources":["../../../src/core/question-registry.ts"],"names":[],"mappings":"AAaA,SAAS,WAAW,CAClB,SAAiB,EACjB,QAAyB;IAEzB,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC;IAChC,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,wBAAwB,EAAE,CAAC;IAC7D,CAAC;IAED,IAAI,QAAQ,CAAC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;QAC9C,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;YAClD,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,kCAAkC,QAAQ,CAAC,OAAO,CAAC,MAAM,GAAG,EAAE,CAAC;QACjG,CAAC;QACD,OAAO;YACL,OAAO,EAAE,IAAI;YACb,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAE;YACxC,WAAW,EAAE,KAAK;SACnB,CAAC;IACJ,CAAC;IAED,IAAI,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC;QACtF,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CA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OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;QAClC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;QACpC,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,cAAc,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;QACpE,KAAK,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF"}
@@ -0,0 +1,39 @@
1
+ import type { ConversationRecord, CopilotProfile, JobKind, JobAttemptRecord, JobRecord, PendingQuestion, PersistedProfileState, TranscriptEntry, ConversationStatus, JobStatus } from './types.js';
2
+ export declare class PersistentStore {
3
+ private readonly root;
4
+ private state;
5
+ load(): Promise<void>;
6
+ getProfiles(): PersistedProfileState[];
7
+ setProfiles(profiles: PersistedProfileState[]): void;
8
+ listConversations(): ConversationRecord[];
9
+ getConversation(conversationId: string): ConversationRecord | undefined;
10
+ resolveConversation(conversationIdOrPrefix: string): ConversationRecord | undefined;
11
+ createConversation(input: {
12
+ cwd: string;
13
+ model: string;
14
+ }): ConversationRecord;
15
+ updateConversation(conversationId: string, updates: Partial<ConversationRecord>): ConversationRecord;
16
+ listJobs(): JobRecord[];
17
+ getJob(jobId: string): JobRecord | undefined;
18
+ jobsForConversation(conversationId: string): JobRecord[];
19
+ createJob(input: {
20
+ conversationId: string;
21
+ kind: JobKind;
22
+ inputFilePath: string;
23
+ }): JobRecord;
24
+ createJobAttempt(jobId: string, profile: Pick<CopilotProfile, 'id' | 'configDir'>): JobAttemptRecord;
25
+ finalizeJobAttempt(attempt: JobAttemptRecord, updates: Partial<Omit<JobAttemptRecord, 'profileId' | 'profileConfigDir' | 'startedAt'>>): JobAttemptRecord;
26
+ updateJob(jobId: string, updates: Partial<JobRecord>): JobRecord;
27
+ appendTranscript(input: {
28
+ conversationId: string;
29
+ jobId?: string | undefined;
30
+ role: TranscriptEntry['role'];
31
+ content: string;
32
+ data?: Record<string, unknown> | undefined;
33
+ }): Promise<TranscriptEntry>;
34
+ readTranscript(conversationId: string): Promise<TranscriptEntry[]>;
35
+ persist(): Promise<void>;
36
+ updatePendingQuestion(conversationId: string, pendingQuestion: PendingQuestion | undefined, status: ConversationStatus): void;
37
+ finalizeJob(jobId: string, status: JobStatus, error?: string): JobRecord;
38
+ private normalizeState;
39
+ }
@@ -0,0 +1,206 @@
1
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { existsSync } from 'node:fs';
3
+ import { generateId } from './ids.js';
4
+ import { ensureStateRoot, logPath, transcriptPath, workspaceIdForCwd } from './paths.js';
5
+ const EMPTY_STATE = {
6
+ version: 1,
7
+ conversations: [],
8
+ jobs: [],
9
+ profiles: [],
10
+ };
11
+ function nowIso() {
12
+ return new Date().toISOString();
13
+ }
14
+ export class PersistentStore {
15
+ root = ensureStateRoot();
16
+ state = structuredClone(EMPTY_STATE);
17
+ async load() {
18
+ if (!existsSync(this.root.registryPath)) {
19
+ this.state = structuredClone(EMPTY_STATE);
20
+ await this.persist();
21
+ return;
22
+ }
23
+ const raw = await readFile(this.root.registryPath, 'utf8');
24
+ this.state = this.normalizeState(JSON.parse(raw));
25
+ }
26
+ getProfiles() {
27
+ return [...this.state.profiles];
28
+ }
29
+ setProfiles(profiles) {
30
+ this.state.profiles = profiles;
31
+ }
32
+ listConversations() {
33
+ return [...this.state.conversations].sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
34
+ }
35
+ getConversation(conversationId) {
36
+ const lowered = conversationId.toLowerCase();
37
+ return this.state.conversations.find((conversation) => conversation.id.toLowerCase() === lowered);
38
+ }
39
+ resolveConversation(conversationIdOrPrefix) {
40
+ const exact = this.getConversation(conversationIdOrPrefix);
41
+ if (exact) {
42
+ return exact;
43
+ }
44
+ const lowered = conversationIdOrPrefix.toLowerCase();
45
+ const matches = this.state.conversations.filter((conversation) => conversation.id.toLowerCase().startsWith(lowered));
46
+ return matches.length === 1 ? matches[0] : undefined;
47
+ }
48
+ createConversation(input) {
49
+ const timestamp = nowIso();
50
+ const conversation = {
51
+ id: generateId(),
52
+ sessionId: generateId(),
53
+ workspaceId: workspaceIdForCwd(input.cwd),
54
+ cwd: input.cwd,
55
+ model: input.model,
56
+ status: 'idle',
57
+ createdAt: timestamp,
58
+ updatedAt: timestamp,
59
+ hasStarted: false,
60
+ nextEntryIndex: 1,
61
+ };
62
+ this.state.conversations.push(conversation);
63
+ return conversation;
64
+ }
65
+ updateConversation(conversationId, updates) {
66
+ const conversation = this.getConversation(conversationId);
67
+ if (!conversation) {
68
+ throw new Error(`Conversation not found: ${conversationId}`);
69
+ }
70
+ Object.assign(conversation, updates, { updatedAt: nowIso() });
71
+ return conversation;
72
+ }
73
+ listJobs() {
74
+ return [...this.state.jobs].sort((left, right) => right.startedAt.localeCompare(left.startedAt));
75
+ }
76
+ getJob(jobId) {
77
+ const lowered = jobId.toLowerCase();
78
+ return this.state.jobs.find((job) => job.id.toLowerCase() === lowered);
79
+ }
80
+ jobsForConversation(conversationId) {
81
+ return this.state.jobs
82
+ .filter((job) => job.conversationId === conversationId)
83
+ .sort((left, right) => left.startedAt.localeCompare(right.startedAt));
84
+ }
85
+ createJob(input) {
86
+ const conversation = this.getConversation(input.conversationId);
87
+ if (!conversation) {
88
+ throw new Error(`Conversation not found: ${input.conversationId}`);
89
+ }
90
+ const timestamp = nowIso();
91
+ const turnIndex = this.jobsForConversation(input.conversationId).length + 1;
92
+ const job = {
93
+ id: generateId(),
94
+ conversationId: input.conversationId,
95
+ kind: input.kind,
96
+ status: 'running',
97
+ inputFilePath: input.inputFilePath,
98
+ createdAt: timestamp,
99
+ startedAt: timestamp,
100
+ turnIndex,
101
+ startEntryIndex: conversation.nextEntryIndex,
102
+ attempts: [],
103
+ };
104
+ conversation.lastJobId = job.id;
105
+ conversation.status = 'running';
106
+ conversation.updatedAt = timestamp;
107
+ this.state.jobs.push(job);
108
+ return job;
109
+ }
110
+ createJobAttempt(jobId, profile) {
111
+ const job = this.getJob(jobId);
112
+ if (!job) {
113
+ throw new Error(`Job not found: ${jobId}`);
114
+ }
115
+ const attempt = {
116
+ profileId: profile.id,
117
+ profileConfigDir: profile.configDir,
118
+ startedAt: nowIso(),
119
+ outcome: 'running',
120
+ };
121
+ job.attempts.push(attempt);
122
+ return attempt;
123
+ }
124
+ finalizeJobAttempt(attempt, updates) {
125
+ Object.assign(attempt, updates);
126
+ return attempt;
127
+ }
128
+ updateJob(jobId, updates) {
129
+ const job = this.getJob(jobId);
130
+ if (!job) {
131
+ throw new Error(`Job not found: ${jobId}`);
132
+ }
133
+ Object.assign(job, updates);
134
+ return job;
135
+ }
136
+ async appendTranscript(input) {
137
+ const conversation = this.getConversation(input.conversationId);
138
+ if (!conversation) {
139
+ throw new Error(`Conversation not found: ${input.conversationId}`);
140
+ }
141
+ const entry = {
142
+ index: conversation.nextEntryIndex,
143
+ conversationId: input.conversationId,
144
+ jobId: input.jobId,
145
+ role: input.role,
146
+ content: input.content,
147
+ timestamp: nowIso(),
148
+ data: input.data,
149
+ };
150
+ conversation.nextEntryIndex += 1;
151
+ conversation.updatedAt = entry.timestamp;
152
+ await mkdir(ensureStateRoot().rootDir, { recursive: true });
153
+ await appendFile(transcriptPath(conversation.cwd, conversation.id), `${JSON.stringify(entry)}\n`);
154
+ const logLine = `[${entry.timestamp}] [${entry.role}] ${entry.content}\n`;
155
+ await appendFile(logPath(conversation.cwd, conversation.id), logLine);
156
+ return entry;
157
+ }
158
+ async readTranscript(conversationId) {
159
+ const conversation = this.resolveConversation(conversationId);
160
+ if (!conversation) {
161
+ throw new Error(`Conversation not found: ${conversationId}`);
162
+ }
163
+ const filePath = transcriptPath(conversation.cwd, conversation.id);
164
+ if (!existsSync(filePath)) {
165
+ return [];
166
+ }
167
+ const raw = await readFile(filePath, 'utf8');
168
+ return raw
169
+ .split('\n')
170
+ .map((line) => line.trim())
171
+ .filter(Boolean)
172
+ .map((line) => JSON.parse(line));
173
+ }
174
+ async persist() {
175
+ await writeFile(this.root.registryPath, JSON.stringify(this.state, null, 2));
176
+ }
177
+ updatePendingQuestion(conversationId, pendingQuestion, status) {
178
+ const conversation = this.getConversation(conversationId);
179
+ if (!conversation) {
180
+ throw new Error(`Conversation not found: ${conversationId}`);
181
+ }
182
+ conversation.pendingQuestion = pendingQuestion;
183
+ conversation.status = status;
184
+ conversation.updatedAt = nowIso();
185
+ }
186
+ finalizeJob(jobId, status, error) {
187
+ const job = this.updateJob(jobId, {
188
+ status,
189
+ error,
190
+ endedAt: nowIso(),
191
+ });
192
+ return job;
193
+ }
194
+ normalizeState(state) {
195
+ return {
196
+ ...state,
197
+ conversations: state.conversations ?? [],
198
+ jobs: (state.jobs ?? []).map((job) => ({
199
+ ...job,
200
+ attempts: job.attempts ?? [],
201
+ })),
202
+ profiles: state.profiles ?? [],
203
+ };
204
+ }
205
+ }
206
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/core/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAezF,MAAM,WAAW,GAAc;IAC7B,OAAO,EAAE,CAAC;IACV,aAAa,EAAE,EAAE;IACjB,IAAI,EAAE,EAAE;IACR,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,SAAS,MAAM;IACb,OAAO,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;AAClC,CAAC;AAED,MAAM,OAAO,eAAe;IACT,IAAI,GAAG,eAAe,EAAE,CAAC;IAClC,KAAK,GAAc,eAAe,CAAC,WA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