@hyperwindmill/caretaker-cli 0.34.0 → 0.35.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 (35) hide show
  1. package/dist/cli/index.d.ts.map +1 -1
  2. package/dist/cli/index.js +16 -0
  3. package/dist/cli/orchestrator_demo.d.ts +39 -0
  4. package/dist/cli/orchestrator_demo.d.ts.map +1 -0
  5. package/dist/cli/orchestrator_demo.js +98 -0
  6. package/dist/cli/web/api_access.d.ts.map +1 -1
  7. package/dist/cli/web/api_access.js +1 -1
  8. package/dist/cli/web/openapi.d.ts +5 -0
  9. package/dist/cli/web/openapi.d.ts.map +1 -1
  10. package/dist/cli/web/openapi.js +37 -0
  11. package/dist/cli/web/orchestrator.d.ts +51 -0
  12. package/dist/cli/web/orchestrator.d.ts.map +1 -0
  13. package/dist/cli/web/orchestrator.js +596 -0
  14. package/dist/cli/web/orchestrator_core.d.ts +83 -0
  15. package/dist/cli/web/orchestrator_core.d.ts.map +1 -0
  16. package/dist/cli/web/orchestrator_core.js +219 -0
  17. package/dist/cli/web/save_config.d.ts +8 -0
  18. package/dist/cli/web/save_config.d.ts.map +1 -0
  19. package/dist/cli/web/save_config.js +9 -0
  20. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
  21. package/dist/cli/web/scheduler/task_strategy.js +21 -2
  22. package/dist/cli/web/server.d.ts +3 -0
  23. package/dist/cli/web/server.d.ts.map +1 -1
  24. package/dist/cli/web/server.js +14 -16
  25. package/dist/lib/task_git.d.ts +3 -0
  26. package/dist/lib/task_git.d.ts.map +1 -1
  27. package/dist/lib/task_git.js +29 -0
  28. package/dist/store/orchestrator.d.ts +50 -0
  29. package/dist/store/orchestrator.d.ts.map +1 -0
  30. package/dist/store/orchestrator.js +127 -0
  31. package/dist/webview/standalone.css +159 -1
  32. package/dist/webview/standalone.css.map +2 -2
  33. package/dist/webview/standalone.js +784 -504
  34. package/dist/webview/standalone.js.map +4 -4
  35. package/package.json +3 -3
@@ -0,0 +1,219 @@
1
+ import { decrypt, encrypt } from '../../lib/encryption.js';
2
+ import { sameHost } from './voice_proxy.js';
3
+ export const PROTOCOL_VERSION = 1;
4
+ export const MAX_BODY_BYTES = 1_048_576;
5
+ export const LEDGER_SIZE = 500;
6
+ const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
7
+ function isLoopbackHost(hostname) {
8
+ const h = hostname.toLowerCase();
9
+ return h === '127.0.0.1' || h === 'localhost' || h === '[::1]' || h === '::1';
10
+ }
11
+ /**
12
+ * Validates an orchestrator base URL: `https` anywhere, `http` only on loopback,
13
+ * and never with embedded userinfo. Returns null when valid, or an error string.
14
+ */
15
+ export function validateEndpoint(endpoint) {
16
+ let url;
17
+ try {
18
+ url = new URL(endpoint);
19
+ }
20
+ catch {
21
+ return 'Endpoint must be a valid URL.';
22
+ }
23
+ if (url.username || url.password) {
24
+ return 'Endpoint URL must not contain credentials.';
25
+ }
26
+ if (url.protocol === 'https:')
27
+ return null;
28
+ if (url.protocol === 'http:') {
29
+ return isLoopbackHost(url.hostname)
30
+ ? null
31
+ : 'Only https:// endpoints are allowed (http:// is allowed only for localhost, 127.0.0.1, or [::1]).';
32
+ }
33
+ return 'Endpoint must use https:// (or http:// on loopback).';
34
+ }
35
+ /**
36
+ * Clamps poll interval in seconds to 5..3600, defaulting to 15.
37
+ */
38
+ export function clampPollSeconds(value) {
39
+ const n = typeof value === 'number'
40
+ ? value
41
+ : typeof value === 'string' && value.trim() !== ''
42
+ ? Number(value)
43
+ : NaN;
44
+ if (!Number.isFinite(n))
45
+ return 15;
46
+ return Math.min(3600, Math.max(5, Math.round(n)));
47
+ }
48
+ /**
49
+ * Builds `${endpoint without trailing slashes}/${call}`.
50
+ */
51
+ export function endpointUrl(endpoint, call) {
52
+ return `${endpoint.replace(/\/+$/, '')}/${call}`;
53
+ }
54
+ /**
55
+ * Parses and normalizes an incoming orchestrator message.
56
+ * - `null`: no usable id (drop, not ledgered).
57
+ * - `{ id, error }`: ledger a 400 result.
58
+ * - `RemoteMessage`: `path` rewritten to normalized pathname + query.
59
+ */
60
+ export function parseMessage(raw) {
61
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
62
+ return null;
63
+ const r = raw;
64
+ if (typeof r.id !== 'string' || r.id.length === 0)
65
+ return null;
66
+ const id = r.id;
67
+ if (typeof r.method !== 'string') {
68
+ return { id, error: 'Message method must be a string.' };
69
+ }
70
+ const method = r.method.toUpperCase();
71
+ if (!ALLOWED_METHODS.has(method)) {
72
+ return { id, error: `Unsupported HTTP method: ${method}` };
73
+ }
74
+ if (typeof r.path !== 'string' || !r.path.startsWith('/') || r.path.startsWith('//')) {
75
+ return { id, error: 'Message path must start with a single /.' };
76
+ }
77
+ let normalized;
78
+ try {
79
+ normalized = new URL(r.path, 'http://x');
80
+ }
81
+ catch {
82
+ return { id, error: 'Invalid message path.' };
83
+ }
84
+ if (normalized.origin !== 'http://x' || !normalized.pathname.startsWith('/')) {
85
+ return { id, error: 'Invalid message path.' };
86
+ }
87
+ const msg = {
88
+ id,
89
+ method,
90
+ path: `${normalized.pathname}${normalized.search}`,
91
+ };
92
+ if ('body' in r && r.body !== undefined) {
93
+ msg.body = r.body;
94
+ }
95
+ return msg;
96
+ }
97
+ /**
98
+ * True when the policy requires manual approval for this HTTP method.
99
+ */
100
+ export function needsApproval(policy, method) {
101
+ return policy === 'approve' && method.toUpperCase() !== 'GET';
102
+ }
103
+ /**
104
+ * Boot recovery: every `applying` record becomes `done` with a 500 result
105
+ * and its request body removed.
106
+ */
107
+ export function recoverLedger(records, now) {
108
+ const interruptedBody = encrypt(JSON.stringify({ error: 'Interrupted by a restart; outcome unknown.' }));
109
+ const resolvedAt = now.toISOString();
110
+ return records.map((r) => {
111
+ if (r.state !== 'applying')
112
+ return r;
113
+ const { body: _removed, ...rest } = r;
114
+ return {
115
+ ...rest,
116
+ state: 'done',
117
+ result: { status: 500, body: interruptedBody },
118
+ resolvedAt,
119
+ };
120
+ });
121
+ }
122
+ /**
123
+ * Keeps every record that is not (done && delivered), then the newest
124
+ * done+delivered ones until the total is LEDGER_SIZE. Order preserved.
125
+ */
126
+ export function trimLedger(records) {
127
+ if (records.length <= LEDGER_SIZE)
128
+ return records;
129
+ let pinned = 0;
130
+ let deliveredTotal = 0;
131
+ for (const r of records) {
132
+ if (r.state === 'done' && r.delivered)
133
+ deliveredTotal++;
134
+ else
135
+ pinned++;
136
+ }
137
+ const keepDelivered = Math.max(0, LEDGER_SIZE - pinned);
138
+ let toDrop = Math.max(0, deliveredTotal - keepDelivered);
139
+ if (toDrop === 0)
140
+ return records;
141
+ return records.filter((r) => {
142
+ if (r.state === 'done' && r.delivered && toDrop > 0) {
143
+ toDrop--;
144
+ return false;
145
+ }
146
+ return true;
147
+ });
148
+ }
149
+ /**
150
+ * Applies settings-save rules. A blank token keeps the stored blob unless the
151
+ * endpoint host changed (in which case the token is dropped and `purgeLedger` is true).
152
+ */
153
+ export function mergeConfigSave(saved, input) {
154
+ const endpoint = typeof input.endpoint === 'string' ? input.endpoint.trim() : '';
155
+ if (endpoint !== '') {
156
+ const err = validateEndpoint(endpoint);
157
+ if (err)
158
+ return { error: err };
159
+ }
160
+ const hostChanged = saved.endpoint !== endpoint && !sameHost(saved.endpoint, endpoint);
161
+ const typedToken = typeof input.token === 'string' ? input.token.trim() : '';
162
+ const token = typedToken !== '' ? typedToken : hostChanged ? '' : saved.token;
163
+ const policy = input.policy === 'auto' || input.policy === 'approve' ? input.policy : 'approve';
164
+ return {
165
+ config: {
166
+ enabled: Boolean(input.enabled),
167
+ name: typeof input.name === 'string' ? input.name.trim() : '',
168
+ endpoint,
169
+ token,
170
+ pollSeconds: clampPollSeconds(input.pollSeconds),
171
+ policy,
172
+ instanceId: saved.instanceId,
173
+ },
174
+ purgeLedger: hostChanged,
175
+ };
176
+ }
177
+ function maskSecrets(value) {
178
+ if (Array.isArray(value)) {
179
+ return value.map(maskSecrets);
180
+ }
181
+ if (value && typeof value === 'object') {
182
+ const out = {};
183
+ for (const [k, v] of Object.entries(value)) {
184
+ out[k] = k === 'repositoryToken' ? '••••' : maskSecrets(v);
185
+ }
186
+ return out;
187
+ }
188
+ return value;
189
+ }
190
+ /**
191
+ * Returns ledger records as view summaries (newest first).
192
+ * Request body is included only for `pending` records, with `repositoryToken` masked.
193
+ */
194
+ export function summarizeLedger(records) {
195
+ const out = [];
196
+ for (let i = records.length - 1; i >= 0; i--) {
197
+ const r = records[i];
198
+ const summary = {
199
+ id: r.id,
200
+ method: r.method,
201
+ path: r.path,
202
+ receivedAt: r.receivedAt,
203
+ state: r.state,
204
+ ...(r.result ? { status: r.result.status } : {}),
205
+ ...(r.resolvedAt ? { resolvedAt: r.resolvedAt } : {}),
206
+ delivered: r.delivered,
207
+ };
208
+ if (r.state === 'pending' && r.body !== undefined) {
209
+ try {
210
+ summary.body = maskSecrets(JSON.parse(decrypt(r.body)));
211
+ }
212
+ catch {
213
+ // Ignore unreadable body
214
+ }
215
+ }
216
+ out.push(summary);
217
+ }
218
+ return out;
219
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Keeps any project present on disk and absent from an incoming settings save,
3
+ * appended after the incoming list so incoming edits win.
4
+ */
5
+ export declare function keepMissingProjects<T extends {
6
+ id: string;
7
+ }>(onDisk: T[], incoming: T[]): T[];
8
+ //# sourceMappingURL=save_config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"save_config.d.ts","sourceRoot":"","sources":["../../../src/cli/web/save_config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,SAAS;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,EAAE,MAAM,EAAE,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,CAI7F"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Keeps any project present on disk and absent from an incoming settings save,
3
+ * appended after the incoming list so incoming edits win.
4
+ */
5
+ export function keepMissingProjects(onDisk, incoming) {
6
+ const incomingIds = new Set(incoming.map((p) => p.id));
7
+ const missing = onDisk.filter((p) => !incomingIds.has(p.id));
8
+ return [...incoming, ...missing];
9
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"task_strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_strategy.ts"],"names":[],"mappings":"AA8HA,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAidnE"}
1
+ {"version":3,"file":"task_strategy.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/task_strategy.ts"],"names":[],"mappings":"AA8HA,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAkenE"}
@@ -3,7 +3,7 @@ import * as harness from '../../../harness/index.js';
3
3
  import { loadAgents, loadConfig } from '../../../store/json.js';
4
4
  import { getTaskById, saveTask, addTaskMessage, runQuery } from '../../../store/db.js';
5
5
  import { runningTasks, runningTaskControllers, syncingProjects } from './locks.js';
6
- import { isGitRepo, ensureWorktree, agentDirIn, commitWip, finalizeDone, runBootstrap, gitCommonDir, syncProjectRepo, projectWorkingDir, pushBranch } from '../../../lib/task_git.js';
6
+ import { isGitRepo, ensureWorktree, BranchDivergedError, agentDirIn, commitWip, finalizeDone, runBootstrap, gitCommonDir, syncProjectRepo, projectWorkingDir, pushBranch } from '../../../lib/task_git.js';
7
7
  import { runDoneReview, MAX_REVIEW_ROUNDS, reviewTransition, reviewRoundLabel } from './task_review.js';
8
8
  import { openCycle, filterHandoffMessages, resolveCycleOutcome } from './task_cycle.js';
9
9
  import { claudeCodeTaskExtras } from '../../../harness/claude_code_runner.js';
@@ -177,7 +177,26 @@ export async function runTaskHeartbeatTick(now) {
177
177
  mountRoot = task.worktreePath;
178
178
  }
179
179
  else if (await isGitRepo(baseWorkingDir)) {
180
- const wt = await ensureWorktree(baseWorkingDir, task.id, task.title, task.branch);
180
+ let wt;
181
+ try {
182
+ wt = await ensureWorktree(baseWorkingDir, task.id, task.title, task.branch);
183
+ }
184
+ catch (wtErr) {
185
+ if (!(wtErr instanceof BranchDivergedError))
186
+ throw wtErr;
187
+ task.status = 'blocked';
188
+ task.blockedReason = wtErr.message;
189
+ task.updatedAt = new Date().toISOString();
190
+ await saveTask(task);
191
+ await addTaskMessage({
192
+ taskId: task.id,
193
+ role: 'assistant',
194
+ messageType: 'block',
195
+ content: `Task branch diverged from the remote — task blocked.\n\n${wtErr.message}`,
196
+ });
197
+ console.error(`[task_heartbeat] Task #${task.id} branch diverged, blocked:`, wtErr.message);
198
+ return;
199
+ }
181
200
  task.branch = wt.branch;
182
201
  task.worktreePath = wt.worktreePath;
183
202
  await saveTask(task);
@@ -1,3 +1,5 @@
1
+ import { Hono } from 'hono';
2
+ import { type ApiListenerOptions } from './api_access.js';
1
3
  import * as harness from '../../harness/index.js';
2
4
  import type { AgentConfig, ProviderConfig } from '../../types.js';
3
5
  import type { ConfirmDecision } from 'webview-ui/bridge';
@@ -34,6 +36,7 @@ export declare class WebSessionController {
34
36
  }>, voiceConversation?: boolean): Promise<void>;
35
37
  abort(): void;
36
38
  }
39
+ export declare function createApp(apiListener: ApiListenerOptions, fetchImpl?: typeof fetch): Hono;
37
40
  export declare function startServer(port: number, host: string, api?: {
38
41
  port?: number;
39
42
  host?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../../src/cli/web/server.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,OAAO,MAAM,wBAAwB,CAAC;AA8ClD,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAgC,MAAM,gBAAgB,CAAC;AAChG,OAAO,KAAK,EAAe,eAAe,EAA0B,MAAM,mBAAmB,CAAC;AAuC9F,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,UAAU,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, mkdirSync } from 'node:fs';
5
5
  import { Hono } from 'hono';
6
6
  import { applyApiListener, registerApiAccess } from './api_access.js';
7
7
  import { registerOpenApi } from './openapi.js';
8
+ import { registerOrchestrator, startOrchestrator } from './orchestrator.js';
9
+ import { keepMissingProjects } from './save_config.js';
8
10
  import { stream } from 'hono/streaming';
9
11
  import { serve } from '@hono/node-server';
10
12
  import { WebSocketServer, WebSocket } from 'ws';
@@ -155,10 +157,8 @@ export class WebSessionController {
155
157
  this.inflight?.abort();
156
158
  }
157
159
  }
158
- export async function startServer(port, host, api = {}) {
160
+ export function createApp(apiListener, fetchImpl) {
159
161
  const app = new Hono();
160
- // Token-authenticated listener for clients outside the browser (api_access.ts).
161
- const apiListener = { webPort: port, host: api.host ?? host, portOverride: api.port };
162
162
  registerApiAccess(app, apiListener);
163
163
  registerOpenApi(app);
164
164
  app.route('/api/fs', fsRouter);
@@ -166,6 +166,7 @@ export async function startServer(port, host, api = {}) {
166
166
  registerVoiceProxy(app);
167
167
  registerVoiceBackend(app);
168
168
  registerVoiceBuiltin(app);
169
+ registerOrchestrator(app, fetchImpl);
169
170
  // Pure-Node static serving with absolute path validation and fallback
170
171
  app.get('/', (c) => {
171
172
  try {
@@ -780,6 +781,12 @@ export async function startServer(port, host, api = {}) {
780
781
  }
781
782
  return c.json({ ok: true, title: task.title, objective: task.objective });
782
783
  });
784
+ return app;
785
+ }
786
+ export async function startServer(port, host, api = {}) {
787
+ // Token-authenticated listener for clients outside the browser (api_access.ts).
788
+ const apiListener = { webPort: port, host: api.host ?? host, portOverride: api.port };
789
+ const app = createApp(apiListener);
783
790
  const nodeServer = serve({
784
791
  fetch: app.fetch,
785
792
  port,
@@ -804,6 +811,7 @@ export async function startServer(port, host, api = {}) {
804
811
  console.log(`\n🚀 Caretaker Server running at http://${host}:${port}\n`);
805
812
  // Start the background scheduler trigger daemon
806
813
  startBackgroundScheduler();
814
+ startOrchestrator(app);
807
815
  // Opt-in: start the managed local speech backend if configured to. Never
808
816
  // awaited — a first run pulls 2.08 GB and must not hang server boot.
809
817
  maybeAutoStartBackend();
@@ -1121,20 +1129,10 @@ export async function startServer(port, host, api = {}) {
1121
1129
  post({ type: 'error', message: idError });
1122
1130
  return;
1123
1131
  }
1124
- // A project that still has tasks must be deleted through DELETE /api/projects/:id
1125
- // (which removes tasks, worktrees and the managed clone) — not silently dropped
1126
- // from a config save. Also blocks id "renames", which arrive as drop+add.
1132
+ // Project deletion goes only through DELETE /api/projects/:id: a stale
1133
+ // settings form copy must not delete a project created over REST.
1127
1134
  const prev = await loadConfig();
1128
- const incomingIds = new Set((msg.config.projects || []).map((p) => p.id));
1129
- for (const old of prev.projects || []) {
1130
- if (incomingIds.has(old.id))
1131
- continue;
1132
- const remaining = (await runQuery(`SELECT * FROM tasks WHERE projectId = '${old.id}'`));
1133
- if (remaining.length > 0) {
1134
- post({ type: 'error', message: `Project "${old.name}" still has ${remaining.length} task(s) — delete it from the Projects panel instead.` });
1135
- return;
1136
- }
1137
- }
1135
+ msg.config.projects = keepMissingProjects(prev.projects || [], msg.config.projects || []);
1138
1136
  // The settings form saves the whole config through here, so this
1139
1137
  // — not POST /api/projects — is the write path that actually
1140
1138
  // needs to enforce the repository-URL rules.
@@ -56,6 +56,9 @@ export declare function syncProjectRepo(project: {
56
56
  */
57
57
  export declare function gitCommonDir(worktreePath: string): Promise<string | null>;
58
58
  export declare function agentDirIn(worktreePath: string, projectWorkingDir: string): Promise<string>;
59
+ export declare class BranchDivergedError extends Error {
60
+ constructor(branch: string);
61
+ }
59
62
  export declare function ensureWorktree(projectWorkingDir: string, taskId: string, title: string, existingBranch?: string | null): Promise<{
60
63
  branch: string;
61
64
  worktreePath: string;
@@ -1 +1 @@
1
- {"version":3,"file":"task_git.d.ts","sourceRoot":"","sources":["../../src/lib/task_git.ts"],"names":[],"mappings":"AA2BA,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAM7D;AAOD,wBAAgB,WAAW,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AG,IAAI,GAC7B,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,CAAA;CAAE,CAAC,CA8B5E;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,GAAG,EAAE,MAAM,EACX,QAAQ,EAAE,MAAM,EAAE,EAClB,eAAe,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,IAAI,CAAC,CAwBf;AAcD,wBAAsB,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAcrF;AAED,wBAAsB,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBtE;AAED,wBAAsB,eAAe,CACnC,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,MAAM,EACb,IAAI,CAAC,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,GAC5D,OAAO,CAAC,IAAI,CAAC,CAMf"}
@@ -242,6 +242,21 @@ export async function agentDirIn(worktreePath, projectWorkingDir) {
242
242
  const rel = relative(repoRoot, projectWorkingDir);
243
243
  return rel ? join(worktreePath, rel) : worktreePath;
244
244
  }
245
+ export class BranchDivergedError extends Error {
246
+ constructor(branch) {
247
+ super(`Task branch "${branch}" diverged from origin/${branch}: it has local commits the remote lacks and the remote has commits the local branch lacks. Reconcile the branch by hand, then unblock the task.`);
248
+ this.name = 'BranchDivergedError';
249
+ }
250
+ }
251
+ async function isAncestor(cwd, a, b) {
252
+ try {
253
+ await git(cwd, ['merge-base', '--is-ancestor', a, b]);
254
+ return true;
255
+ }
256
+ catch {
257
+ return false;
258
+ }
259
+ }
245
260
  export async function ensureWorktree(projectWorkingDir, taskId, title, existingBranch) {
246
261
  const repoRoot = await git(projectWorkingDir, ['rev-parse', '--show-toplevel']);
247
262
  // The persisted branch is authoritative: re-deriving under the new id scheme
@@ -254,6 +269,20 @@ export async function ensureWorktree(projectWorkingDir, taskId, title, existingB
254
269
  catch {
255
270
  // Branch may already exist from a previous run whose path field was lost — reuse it.
256
271
  await git(repoRoot, ['worktree', 'add', worktreePath, branch]);
272
+ // Reused branch: catch up with a remote that moved while the task was finished.
273
+ // No fetch here — syncProjectRepo already refreshed origin/<branch>.
274
+ const remoteRef = `refs/remotes/origin/${branch}`;
275
+ const hasRemote = await git(worktreePath, ['rev-parse', '--verify', '--quiet', remoteRef]).then(() => true, () => false);
276
+ if (hasRemote && !(await isAncestor(worktreePath, remoteRef, 'HEAD'))) {
277
+ if (await isAncestor(worktreePath, 'HEAD', remoteRef)) {
278
+ await git(worktreePath, ['merge', '--ff-only', remoteRef]);
279
+ }
280
+ else {
281
+ // Leave nothing behind: the next attempt must find the path free and the branch unlocked.
282
+ await git(repoRoot, ['worktree', 'remove', '--force', worktreePath]);
283
+ throw new BranchDivergedError(branch);
284
+ }
285
+ }
257
286
  }
258
287
  const rel = relative(repoRoot, projectWorkingDir);
259
288
  const agentWorkingDir = rel ? join(worktreePath, rel) : worktreePath;
@@ -0,0 +1,50 @@
1
+ export type OrchestratorPolicy = 'auto' | 'approve';
2
+ export interface OrchestratorConfig {
3
+ enabled: boolean;
4
+ name: string;
5
+ endpoint: string;
6
+ /** Encrypted blob, or '' when none. */
7
+ token: string;
8
+ pollSeconds: number;
9
+ policy: OrchestratorPolicy;
10
+ instanceId: string;
11
+ }
12
+ export interface LedgerRecord {
13
+ id: string;
14
+ method: string;
15
+ path: string;
16
+ /** encrypt(JSON.stringify(body)); removed when state becomes 'done'. */
17
+ body?: string;
18
+ receivedAt: string;
19
+ state: 'pending' | 'applying' | 'done';
20
+ /** body encrypted the same way; removed on delivery. */
21
+ result?: {
22
+ status: number;
23
+ body?: string;
24
+ };
25
+ resolvedAt?: string;
26
+ delivered: boolean;
27
+ }
28
+ export declare function orchestratorPath(): string;
29
+ export declare function orchestratorLedgerPath(): string;
30
+ /**
31
+ * Loads orchestrator.json with defaults (disabled, '', '', '', 15, 'approve').
32
+ * Generates and persists `instanceId` (randomUUID) when missing.
33
+ * Always returns a fresh object.
34
+ */
35
+ export declare function loadOrchestrator(): Promise<OrchestratorConfig>;
36
+ /**
37
+ * Persists orchestrator.json atomically. Encrypts `token` when it is not
38
+ * already an encrypted blob.
39
+ */
40
+ export declare function saveOrchestrator(c: OrchestratorConfig): Promise<void>;
41
+ /**
42
+ * Loads orchestrator-ledger.json. Unreadable or non-array file returns [].
43
+ * Malformed records are dropped.
44
+ */
45
+ export declare function loadLedger(): Promise<LedgerRecord[]>;
46
+ /**
47
+ * Persists orchestrator-ledger.json atomically.
48
+ */
49
+ export declare function saveLedger(records: LedgerRecord[]): Promise<void>;
50
+ //# sourceMappingURL=orchestrator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/store/orchestrator.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,kBAAkB,GAAG,MAAM,GAAG,SAAS,CAAC;AAEpD,MAAM,WAAW,kBAAkB;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,kBAAkB,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,wEAAwE;IACxE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,SAAS,GAAG,UAAU,GAAG,MAAM,CAAC;IACvC,wDAAwD;IACxD,MAAM,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,wBAAgB,gBAAgB,IAAI,MAAM,CAEzC;AAED,wBAAgB,sBAAsB,IAAI,MAAM,CAE/C;AAqBD;;;;GAIG;AACH,wBAAsB,gBAAgB,IAAI,OAAO,CAAC,kBAAkB,CAAC,CAapE;AAcD;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ3E;AAsBD;;;GAGG;AACH,wBAAsB,UAAU,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,CAQ1D;AAED;;GAEG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAIvE"}
@@ -0,0 +1,127 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync } from 'node:fs';
3
+ import { readFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { dataDir } from './json.js';
6
+ import { encrypt, isEncrypted } from '../lib/encryption.js';
7
+ import { atomicWriteFile } from '../cli/web/scheduler/telegram_window.js';
8
+ export function orchestratorPath() {
9
+ return path.join(dataDir(), 'orchestrator.json');
10
+ }
11
+ export function orchestratorLedgerPath() {
12
+ return path.join(dataDir(), 'orchestrator-ledger.json');
13
+ }
14
+ async function readRaw() {
15
+ try {
16
+ const parsed = JSON.parse(await readFile(orchestratorPath(), 'utf8'));
17
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
18
+ return parsed;
19
+ }
20
+ }
21
+ catch {
22
+ // Missing or unreadable file -> defaults
23
+ }
24
+ return {};
25
+ }
26
+ const hasInstanceId = (raw) => typeof raw.instanceId === 'string' && raw.instanceId.length > 0;
27
+ /** The one in-flight instanceId creation: concurrent first loads (the loop and
28
+ * the settings GET at boot) would otherwise each mint and save their own id. */
29
+ let idCreation = null;
30
+ /**
31
+ * Loads orchestrator.json with defaults (disabled, '', '', '', 15, 'approve').
32
+ * Generates and persists `instanceId` (randomUUID) when missing.
33
+ * Always returns a fresh object.
34
+ */
35
+ export async function loadOrchestrator() {
36
+ let raw = await readRaw();
37
+ if (!hasInstanceId(raw)) {
38
+ idCreation ??= (async () => {
39
+ const again = await readRaw();
40
+ if (!hasInstanceId(again))
41
+ await saveOrchestrator(normalize({ ...again, instanceId: randomUUID() }));
42
+ })().finally(() => {
43
+ idCreation = null;
44
+ });
45
+ await idCreation;
46
+ raw = await readRaw();
47
+ }
48
+ return normalize(raw);
49
+ }
50
+ function normalize(raw) {
51
+ return {
52
+ enabled: typeof raw.enabled === 'boolean' ? raw.enabled : false,
53
+ name: typeof raw.name === 'string' ? raw.name : '',
54
+ endpoint: typeof raw.endpoint === 'string' ? raw.endpoint : '',
55
+ token: typeof raw.token === 'string' ? raw.token : '',
56
+ pollSeconds: typeof raw.pollSeconds === 'number' && Number.isFinite(raw.pollSeconds) ? raw.pollSeconds : 15,
57
+ policy: raw.policy === 'auto' || raw.policy === 'approve' ? raw.policy : 'approve',
58
+ instanceId: hasInstanceId(raw) ? raw.instanceId : '',
59
+ };
60
+ }
61
+ /**
62
+ * Persists orchestrator.json atomically. Encrypts `token` when it is not
63
+ * already an encrypted blob.
64
+ */
65
+ export async function saveOrchestrator(c) {
66
+ const copy = { ...c };
67
+ if (copy.token && !isEncrypted(copy.token)) {
68
+ copy.token = encrypt(copy.token);
69
+ }
70
+ const filePath = orchestratorPath();
71
+ mkdirSync(path.dirname(filePath), { recursive: true });
72
+ await atomicWriteFile(filePath, JSON.stringify(copy, null, 2));
73
+ }
74
+ function isValidLedgerRecord(r) {
75
+ if (!r || typeof r !== 'object' || Array.isArray(r))
76
+ return false;
77
+ const o = r;
78
+ if (typeof o.id !== 'string' || o.id.length === 0)
79
+ return false;
80
+ if (typeof o.method !== 'string')
81
+ return false;
82
+ if (typeof o.path !== 'string')
83
+ return false;
84
+ if (typeof o.receivedAt !== 'string')
85
+ return false;
86
+ if (o.state !== 'pending' && o.state !== 'applying' && o.state !== 'done')
87
+ return false;
88
+ if (typeof o.delivered !== 'boolean')
89
+ return false;
90
+ if (o.body !== undefined && typeof o.body !== 'string')
91
+ return false;
92
+ if (o.resolvedAt !== undefined && typeof o.resolvedAt !== 'string')
93
+ return false;
94
+ if (o.result !== undefined) {
95
+ if (!o.result || typeof o.result !== 'object' || Array.isArray(o.result))
96
+ return false;
97
+ const res = o.result;
98
+ if (typeof res.status !== 'number' || !Number.isFinite(res.status))
99
+ return false;
100
+ if (res.body !== undefined && typeof res.body !== 'string')
101
+ return false;
102
+ }
103
+ return true;
104
+ }
105
+ /**
106
+ * Loads orchestrator-ledger.json. Unreadable or non-array file returns [].
107
+ * Malformed records are dropped.
108
+ */
109
+ export async function loadLedger() {
110
+ try {
111
+ const parsed = JSON.parse(await readFile(orchestratorLedgerPath(), 'utf8'));
112
+ if (!Array.isArray(parsed))
113
+ return [];
114
+ return parsed.filter(isValidLedgerRecord);
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ }
120
+ /**
121
+ * Persists orchestrator-ledger.json atomically.
122
+ */
123
+ export async function saveLedger(records) {
124
+ const filePath = orchestratorLedgerPath();
125
+ mkdirSync(path.dirname(filePath), { recursive: true });
126
+ await atomicWriteFile(filePath, JSON.stringify(records, null, 2));
127
+ }