@hyperwindmill/caretaker-cli 0.19.0 → 0.21.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 (54) hide show
  1. package/dist/cli/mcp.js +5 -5
  2. package/dist/cli/web/mcp_bridge.d.ts +1 -1
  3. package/dist/cli/web/mcp_bridge.d.ts.map +1 -1
  4. package/dist/cli/web/mcp_bridge.js +23 -7
  5. package/dist/cli/web/scheduler/heartbeat.d.ts +2 -2
  6. package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -1
  7. package/dist/cli/web/scheduler/locks.d.ts +6 -0
  8. package/dist/cli/web/scheduler/locks.d.ts.map +1 -1
  9. package/dist/cli/web/scheduler/locks.js +6 -0
  10. package/dist/cli/web/scheduler/strategy.d.ts +3 -3
  11. package/dist/cli/web/scheduler/strategy.d.ts.map +1 -1
  12. package/dist/cli/web/scheduler/task_roles.d.ts +0 -4
  13. package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -1
  14. package/dist/cli/web/scheduler/task_roles.js +12 -2
  15. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
  16. package/dist/cli/web/scheduler/task_strategy.js +86 -4
  17. package/dist/cli/web/scheduler/telegram.d.ts.map +1 -1
  18. package/dist/cli/web/scheduler/telegram.js +4 -1
  19. package/dist/cli/web/server.d.ts.map +1 -1
  20. package/dist/cli/web/server.js +121 -10
  21. package/dist/harness/claude_code_runner.d.ts.map +1 -1
  22. package/dist/harness/claude_code_runner.js +5 -1
  23. package/dist/harness/tools/builtin/email_tools.d.ts +5 -0
  24. package/dist/harness/tools/builtin/email_tools.d.ts.map +1 -0
  25. package/dist/harness/tools/builtin/email_tools.js +182 -0
  26. package/dist/harness/tools/builtin/index.d.ts +2 -1
  27. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  28. package/dist/harness/tools/builtin/index.js +7 -1
  29. package/dist/harness/tools/builtin/task_tools.d.ts.map +1 -1
  30. package/dist/harness/tools/builtin/task_tools.js +48 -6
  31. package/dist/harness/tools/resolve.d.ts.map +1 -1
  32. package/dist/harness/tools/resolve.js +9 -4
  33. package/dist/lib/email.d.ts +132 -0
  34. package/dist/lib/email.d.ts.map +1 -0
  35. package/dist/lib/email.js +306 -0
  36. package/dist/lib/repo_url.d.ts +12 -0
  37. package/dist/lib/repo_url.d.ts.map +1 -0
  38. package/dist/lib/repo_url.js +36 -0
  39. package/dist/lib/task_git.d.ts +53 -1
  40. package/dist/lib/task_git.d.ts.map +1 -1
  41. package/dist/lib/task_git.js +197 -5
  42. package/dist/mcp/builtin_server.d.ts +13 -0
  43. package/dist/mcp/builtin_server.d.ts.map +1 -0
  44. package/dist/mcp/builtin_server.js +65 -0
  45. package/dist/store/json.d.ts +1 -0
  46. package/dist/store/json.d.ts.map +1 -1
  47. package/dist/store/json.js +15 -0
  48. package/dist/tui/agents.js +36 -14
  49. package/dist/webview/standalone.js +1511 -1068
  50. package/dist/webview/standalone.js.map +4 -4
  51. package/package.json +8 -3
  52. package/dist/mcp/task_server.d.ts +0 -9
  53. package/dist/mcp/task_server.d.ts.map +0 -1
  54. package/dist/mcp/task_server.js +0 -48
@@ -0,0 +1,306 @@
1
+ // Email accounts for the agent-facing email tools.
2
+ //
3
+ // An account is a `type: 'email'` entry in the Services collection
4
+ // (`caretaker.json` → `scheduler.tasks`, see store/json.ts). The record holds
5
+ // both halves of a mailbox: IMAP for reading and SMTP for sending, each
6
+ // independently optional — an account with no `smtpHost` cannot send, one with
7
+ // no `imapHost` cannot read. The SMTP credentials default to the IMAP ones —
8
+ // one mailbox, one login, in the common case — and only need their own fields
9
+ // when the provider splits them.
10
+ //
11
+ // This module owns account resolution, the address allowlists, and the two
12
+ // network operations. Everything except sendEmail()/fetchInbox() is pure, which
13
+ // is where the tests live.
14
+ import nodemailer from 'nodemailer';
15
+ import { ImapFlow } from 'imapflow';
16
+ import { simpleParser } from 'mailparser';
17
+ import TurndownService from 'turndown';
18
+ import { loadConfig } from '../store/json.js';
19
+ import { decrypt, isEncrypted } from './encryption.js';
20
+ /**
21
+ * Ceiling on one mail network operation, and the same reasoning as
22
+ * `NET_TIMEOUT_MS` in lib/task_git.ts: an unattended run must not hang forever
23
+ * on a wedged server. The abort also carries `ctx.signal`, so Pause and the
24
+ * task's wall-clock budget reach *inside* an in-flight connection — the loop
25
+ * only checks the signal between turns, and would otherwise sit awaiting this
26
+ * tool call.
27
+ */
28
+ export const NET_TIMEOUT_MS = 60_000;
29
+ /** Arm `close` on abort or timeout; returns the disarm to call in a finally. */
30
+ function armAbort(close, signal) {
31
+ const timer = setTimeout(close, NET_TIMEOUT_MS);
32
+ const onAbort = () => close();
33
+ signal?.addEventListener('abort', onAbort, { once: true });
34
+ return () => {
35
+ clearTimeout(timer);
36
+ signal?.removeEventListener('abort', onAbort);
37
+ };
38
+ }
39
+ /** An account can send only if it has somewhere to send through. */
40
+ export function canSend(a) {
41
+ return !!a.smtpHost;
42
+ }
43
+ /** …and can be read only if it has a mailbox to read. */
44
+ export function canRead(a) {
45
+ return !!a.imapHost;
46
+ }
47
+ function reveal(value) {
48
+ if (!value)
49
+ return '';
50
+ return isEncrypted(value) ? decrypt(value) : value;
51
+ }
52
+ /** Split a comma/newline-separated allowlist into patterns. */
53
+ export function parsePatterns(raw) {
54
+ return (raw ?? '')
55
+ .split(/[,\n;]/)
56
+ .map((p) => p.trim())
57
+ .filter(Boolean);
58
+ }
59
+ /**
60
+ * Does `address` match any of `patterns`? `*` is the only wildcard and matches
61
+ * any run of characters, so `*@example.com` and a bare `*` both work; anything
62
+ * else is compared literally. Case-insensitive.
63
+ *
64
+ * An empty pattern list means "no allowlist configured" and allows everything —
65
+ * the restriction is opt-in, see the design doc.
66
+ */
67
+ export function matchesAllowlist(address, patterns) {
68
+ if (patterns.length === 0)
69
+ return true;
70
+ const addr = address.trim().toLowerCase();
71
+ return patterns.some((pattern) => {
72
+ const rx = new RegExp('^' +
73
+ pattern
74
+ .toLowerCase()
75
+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
76
+ .replace(/\\\*/g, '.*') +
77
+ '$');
78
+ return rx.test(addr);
79
+ });
80
+ }
81
+ /**
82
+ * Pull the bare address out of a recipient string, so a display-name form
83
+ * ("Ada <ada@example.com>") is checked against the allowlist by its address and
84
+ * not by the whole label.
85
+ */
86
+ export function bareAddress(recipient) {
87
+ const angled = recipient.match(/<([^>]*)>/);
88
+ return (angled ? angled[1] : recipient).trim();
89
+ }
90
+ /** Every enabled `email` service, with defaults applied and secrets revealed.
91
+ * Direction is not filtered here — ask canSend()/canRead(). */
92
+ export function emailAccounts(services) {
93
+ return services
94
+ .filter((s) => s.type === 'email' && s.enabled)
95
+ .map((s) => ({
96
+ name: s.name,
97
+ from: (s.smtpFrom || s.imapUser || '').trim(),
98
+ smtpHost: (s.smtpHost ?? '').trim(),
99
+ // ponytail: 587 covers plaintext-or-STARTTLS, which is what smtpSecure
100
+ // false means; a 465 account has to say so via the port anyway.
101
+ smtpPort: s.smtpPort || (s.smtpSecure ? 465 : 587),
102
+ smtpSecure: s.smtpSecure ?? false,
103
+ smtpUser: (s.smtpUser || s.imapUser || '').trim(),
104
+ smtpPassword: reveal(s.smtpPassword || s.imapPassword),
105
+ imapHost: (s.imapHost ?? '').trim(),
106
+ imapPort: s.imapPort || (s.imapSecure === false ? 143 : 993),
107
+ imapSecure: s.imapSecure !== false,
108
+ imapUser: (s.imapUser ?? '').trim(),
109
+ imapPassword: reveal(s.imapPassword),
110
+ allowedRecipients: parsePatterns(s.allowedRecipients),
111
+ allowedSenders: parsePatterns(s.allowedSenders),
112
+ allowedAgents: (s.allowedAgents ?? []).filter(Boolean),
113
+ }));
114
+ }
115
+ /**
116
+ * Narrow a list to the accounts one agent may use. A scoped account is removed
117
+ * outright rather than refused later: the agent never sees a mailbox it cannot
118
+ * touch, so it cannot name it, be tricked into naming it, or report that it
119
+ * exists.
120
+ *
121
+ * `agentId` undefined means the caller has no agent identity, and that only
122
+ * happens for callers that already hold full access to CARETAKER_HOME — the
123
+ * `caretaker-cli mcp` stdio server (whose trust boundary IS local process
124
+ * access) and direct in-process calls. Those see everything. Any new surface
125
+ * that executes these tools on behalf of an agent MUST set `ctx.callerAgent`,
126
+ * or it silently opts out of scoping.
127
+ */
128
+ export function visibleAccounts(accounts, agentId) {
129
+ if (!agentId)
130
+ return accounts;
131
+ return accounts.filter((a) => a.allowedAgents.length === 0 || a.allowedAgents.includes(agentId));
132
+ }
133
+ /** Configured accounts visible to `agentId`, read from the live config. */
134
+ export async function listEmailAccounts(agentId) {
135
+ const config = await loadConfig();
136
+ return visibleAccounts(emailAccounts(config.scheduler?.tasks ?? []), agentId);
137
+ }
138
+ /** Look an account up by service name, case-insensitively. */
139
+ export function findAccount(accounts, name) {
140
+ const wanted = name.trim().toLowerCase();
141
+ return accounts.find((a) => a.name.trim().toLowerCase() === wanted);
142
+ }
143
+ /** Send one plain-text message. Returns the SMTP message id. */
144
+ export async function sendEmail(account, mail, signal) {
145
+ if (signal?.aborted)
146
+ throw new Error('aborted before connecting');
147
+ const transport = nodemailer.createTransport({
148
+ host: account.smtpHost,
149
+ port: account.smtpPort,
150
+ secure: account.smtpSecure,
151
+ // A server with auth disabled (the GreenMail fixture) rejects an AUTH
152
+ // command outright, so omit the credentials rather than send empty ones.
153
+ auth: account.smtpUser ? { user: account.smtpUser, pass: account.smtpPassword } : undefined,
154
+ });
155
+ const disarm = armAbort(() => transport.close(), signal);
156
+ try {
157
+ const info = await transport.sendMail({
158
+ from: account.from,
159
+ to: mail.to,
160
+ cc: mail.cc,
161
+ bcc: mail.bcc,
162
+ subject: mail.subject,
163
+ text: mail.body,
164
+ });
165
+ return info.messageId;
166
+ }
167
+ finally {
168
+ disarm();
169
+ transport.close();
170
+ }
171
+ }
172
+ // ─── Inbound ──────────────────────────────────────────────────────────────
173
+ //
174
+ // There is no `email` scheduler strategy and no stored UID cursor: an inbound
175
+ // workflow is a `heartbeat` service whose prompt tells the agent to call
176
+ // email_fetch, and "already handled" is the IMAP `\Seen` flag — server state,
177
+ // shared with the user's own mail client. Two behaviours on one account are two
178
+ // heartbeats, which is also how a per-subject triage is expressed.
179
+ /** Hard ceiling on messages per call, whatever the caller asks for. */
180
+ export const MAX_FETCH = 50;
181
+ /** How many unread messages we are willing to look at to fill one window.
182
+ * Only matters with a sender allowlist: unlisted mail is skipped and left
183
+ * unread, so without a bound a mailbox full of junk would be re-scanned
184
+ * forever. The scan itself is one cheap ENVELOPE fetch, not a download. */
185
+ export const MAX_SCAN = 200;
186
+ /** Hard ceiling on the body text handed to the model, per message. */
187
+ export const MAX_BODY_CHARS = 8000;
188
+ /** ISO-8601 for whatever the parser or the server gave us; '' when unusable. */
189
+ export function isoDate(value) {
190
+ if (!value)
191
+ return '';
192
+ const d = value instanceof Date ? value : new Date(value);
193
+ return Number.isNaN(d.getTime()) ? '' : d.toISOString();
194
+ }
195
+ export function clampLimit(limit) {
196
+ const n = Math.trunc(Number(limit));
197
+ if (!Number.isFinite(n) || n < 1)
198
+ return 10;
199
+ return Math.min(n, MAX_FETCH);
200
+ }
201
+ export function truncateBody(text) {
202
+ const clean = text.replace(/\r\n/g, '\n').trim();
203
+ if (clean.length <= MAX_BODY_CHARS)
204
+ return { body: clean, truncated: false };
205
+ return { body: clean.slice(0, MAX_BODY_CHARS) + '\n[…truncated]', truncated: true };
206
+ }
207
+ const turndown = new TurndownService();
208
+ /** Best-effort plain text for a message: the text/plain part, else the HTML converted. */
209
+ export function messageText(parsed) {
210
+ if (parsed.text?.trim())
211
+ return parsed.text;
212
+ if (typeof parsed.html === 'string' && parsed.html.trim())
213
+ return turndown.turndown(parsed.html);
214
+ return '';
215
+ }
216
+ /** Read the oldest matching messages from INBOX. */
217
+ export async function fetchInbox(account, opts = {}) {
218
+ const limit = clampLimit(opts.limit);
219
+ const markSeen = opts.markSeen !== false;
220
+ if (opts.signal?.aborted)
221
+ throw new Error('aborted before connecting');
222
+ const client = new ImapFlow({
223
+ host: account.imapHost,
224
+ port: account.imapPort,
225
+ secure: account.imapSecure,
226
+ auth: { user: account.imapUser, pass: account.imapPassword },
227
+ logger: false,
228
+ });
229
+ const disarm = armAbort(() => client.close(), opts.signal);
230
+ try {
231
+ await client.connect();
232
+ }
233
+ catch (err) {
234
+ disarm();
235
+ throw err;
236
+ }
237
+ const lock = await client.getMailboxLock('INBOX');
238
+ try {
239
+ // Only the two criteria every server implements the same way. The sender
240
+ // allowlist is applied below, host-side: IMAP `SEARCH FROM` is substring by
241
+ // spec but not in practice (GreenMail matches whole addresses only and
242
+ // errors on a leading `@`), and `OR` is just as uneven — a filter that
243
+ // silently returns nothing on some servers is worse than no filter.
244
+ const criteria = {};
245
+ if (opts.unreadOnly !== false)
246
+ criteria.seen = false;
247
+ if (opts.subject?.trim())
248
+ criteria.subject = opts.subject.trim();
249
+ const uids = (await client.search(Object.keys(criteria).length ? criteria : { all: true }, {
250
+ uid: true,
251
+ }));
252
+ if (!uids || uids.length === 0)
253
+ return { messages: [], refused: 0 };
254
+ // Oldest first: a queue is processed from the front, never sampled.
255
+ const window = uids.slice(0, MAX_SCAN);
256
+ const scanTruncated = uids.length > window.length;
257
+ // One cheap pass over envelopes decides who is allowed, so mail we may not
258
+ // read is never downloaded.
259
+ const allowed = [];
260
+ let refused = 0;
261
+ for await (const msg of client.fetch(window.join(','), { envelope: true, uid: true }, { uid: true })) {
262
+ const address = msg.envelope?.from?.[0]?.address ?? '';
263
+ if (matchesAllowlist(address, account.allowedSenders)) {
264
+ if (allowed.length < limit)
265
+ allowed.push(msg.uid);
266
+ }
267
+ else {
268
+ refused++;
269
+ }
270
+ if (allowed.length >= limit)
271
+ break;
272
+ }
273
+ const messages = [];
274
+ for (const uid of allowed) {
275
+ const msg = await client.fetchOne(String(uid), { source: true, internalDate: true }, { uid: true });
276
+ if (!msg || !msg.source)
277
+ continue;
278
+ const parsed = await simpleParser(msg.source);
279
+ const { body, truncated } = truncateBody(messageText(parsed));
280
+ messages.push({
281
+ uid,
282
+ from: parsed.from?.text ?? '',
283
+ to: parsed.to?.text ?? '',
284
+ subject: parsed.subject ?? '',
285
+ // The server's INTERNALDATE always exists; a Date header may be absent
286
+ // or malformed, and mailparser then leaves the field undefined. (imapflow
287
+ // types internalDate as string | Date depending on the fetch shape.)
288
+ date: isoDate(parsed.date ?? msg.internalDate),
289
+ body,
290
+ ...(truncated ? { truncated } : {}),
291
+ attachments: (parsed.attachments ?? []).map((a) => a.filename ?? '(unnamed)'),
292
+ });
293
+ }
294
+ // Only what the agent actually received is marked read — a refused message
295
+ // is left untouched for the human.
296
+ if (markSeen && messages.length) {
297
+ await client.messageFlagsAdd(messages.map((m) => m.uid).join(','), ['\\Seen'], { uid: true });
298
+ }
299
+ return { messages, refused, ...(scanTruncated ? { scanTruncated } : {}) };
300
+ }
301
+ finally {
302
+ disarm();
303
+ lock.release();
304
+ await client.logout().catch(() => client.close());
305
+ }
306
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Authoritative validation for a project's `repositoryUrl`.
3
+ *
4
+ * The webview has its own copy of this rule for form feedback, but that one is
5
+ * UX only — every write path into `caretaker.json` must call THIS one, because
6
+ * the client can send any payload it likes over the settings websocket.
7
+ *
8
+ * Returns null when the value is acceptable (empty = unset), otherwise the
9
+ * message to show the user.
10
+ */
11
+ export declare function validateRepositoryUrl(url: string): string | null;
12
+ //# sourceMappingURL=repo_url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repo_url.d.ts","sourceRoot":"","sources":["../../src/lib/repo_url.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAsBhE"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Authoritative validation for a project's `repositoryUrl`.
3
+ *
4
+ * The webview has its own copy of this rule for form feedback, but that one is
5
+ * UX only — every write path into `caretaker.json` must call THIS one, because
6
+ * the client can send any payload it likes over the settings websocket.
7
+ *
8
+ * Returns null when the value is acceptable (empty = unset), otherwise the
9
+ * message to show the user.
10
+ */
11
+ export function validateRepositoryUrl(url) {
12
+ const u = url.trim();
13
+ if (!u)
14
+ return null;
15
+ if (u.startsWith('git@') || u.startsWith('ssh://')) {
16
+ return 'SSH remotes are not supported — use an https:// URL with an access token.';
17
+ }
18
+ if (!u.startsWith('https://'))
19
+ return 'Repository URL must start with https://';
20
+ let parsed;
21
+ try {
22
+ parsed = new URL(u);
23
+ }
24
+ catch {
25
+ return 'Repository URL is not a valid URL.';
26
+ }
27
+ if (!parsed.hostname)
28
+ return 'Repository URL is not a valid URL.';
29
+ // An https prefix alone does NOT keep the secret out of argv and
30
+ // .git/config: `https://user:token@host/repo` puts it in both, which is
31
+ // exactly what the credential-helper design exists to prevent.
32
+ if (parsed.username || parsed.password) {
33
+ return 'Do not put credentials in the repository URL — they would be stored in .git/config and visible in the process list. Use the access token field instead.';
34
+ }
35
+ return null;
36
+ }
@@ -1,4 +1,52 @@
1
1
  export declare function isGitRepo(dir: string): Promise<boolean>;
2
+ export declare function gitAuthArgs(hasToken: boolean): string[];
3
+ export declare function gitAuthEnv(token?: string | null): Record<string, string>;
4
+ export declare function pushBranch(worktreePath: string, branch: string, repo: {
5
+ url: string;
6
+ token?: string | null;
7
+ }): Promise<void>;
8
+ export declare function projectWorkingDir(project: {
9
+ id: number;
10
+ workingDir?: string | null;
11
+ repositoryUrl?: string | null;
12
+ }): string;
13
+ /**
14
+ * The clone directory caretaker owns for this project, or null when the repo
15
+ * lives in a user-chosen `workingDir` (or the project isn't remote-backed).
16
+ * The delete path uses this: anything non-null is caretaker's to remove,
17
+ * anything null must never be touched.
18
+ */
19
+ export declare function managedRepoDir(project: {
20
+ id: number;
21
+ workingDir?: string | null;
22
+ repositoryUrl?: string | null;
23
+ }): string | null;
24
+ export type ProjectRepoStatus = {
25
+ state: 'absent' | 'cloned' | 'broken';
26
+ branch?: string;
27
+ commit?: string;
28
+ };
29
+ export declare function projectRepoStatus(project: {
30
+ id: number;
31
+ workingDir?: string | null;
32
+ repositoryUrl?: string | null;
33
+ }): Promise<ProjectRepoStatus>;
34
+ export type SyncProgress = {
35
+ step: 'clean' | 'clone' | 'pull' | 'done' | 'error';
36
+ message: string;
37
+ status?: ProjectRepoStatus;
38
+ };
39
+ /**
40
+ * Clone-or-pull a remote-backed project's repository. Progress is yielded for
41
+ * the ndjson endpoint; the heartbeat just drains it. Throws on failure —
42
+ * callers turn that into a blocked task / in-band error line.
43
+ */
44
+ export declare function syncProjectRepo(project: {
45
+ id: number;
46
+ workingDir?: string | null;
47
+ repositoryUrl?: string | null;
48
+ repositoryToken?: string | null;
49
+ }): AsyncGenerator<SyncProgress>;
2
50
  /**
3
51
  * Absolute git common dir for a (linked) worktree — the main repo's shared
4
52
  * `.git`, which holds the object store and `worktrees/<id>`. A worktree's own
@@ -23,5 +71,9 @@ export declare function ensureWorktree(projectWorkingDir: string, projectId: num
23
71
  export declare function runBootstrap(cwd: string, commands: string[], dockerContainer?: string): Promise<void>;
24
72
  export declare function commitWip(worktreePath: string, title: string): Promise<boolean>;
25
73
  export declare function finalizeDone(worktreePath: string): Promise<void>;
26
- export declare function discardWorktree(worktreePath: string, title: string): Promise<void>;
74
+ export declare function discardWorktree(worktreePath: string, title: string, push?: {
75
+ branch: string;
76
+ url: string;
77
+ token?: string | null;
78
+ }): Promise<void>;
27
79
  //# sourceMappingURL=task_git.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"task_git.d.ts","sourceRoot":"","sources":["../../src/lib/task_git.ts"],"names":[],"mappings":"AAoBA,wBAAsB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAM7D;AAgBD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAM/E;AAED,wBAAsB,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKj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C;CACjC,GAAG,cAAc,CAAC,YAAY,CAAC,CAqE/B;AAgBD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAM/E;AAED,wBAAsB,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKjG;AAED,wBAAsB,cAAc,CAClC,iBAAiB,EAAE,MAAM,EACzB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,CAAA;CAAE,CAAC,CAe5E;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"}
@@ -1,17 +1,19 @@
1
1
  import { execFile, exec as execCb } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import { rm } from 'node:fs/promises';
4
- import { join, relative, dirname } from 'node:path';
3
+ import { rm, mkdir, readdir, rename } from 'node:fs/promises';
4
+ import { join, relative, dirname, basename } from 'node:path';
5
5
  import { dataDir } from '../store/db.js';
6
6
  import { commandEnv } from '../harness/tools/builtin/shell-env.js';
7
7
  import { execInContainer } from './docker.js';
8
+ import { decrypt, isEncrypted } from './encryption.js';
8
9
  const exec = promisify(execFile);
9
10
  const execShell = promisify(execCb);
10
- async function git(cwd, args) {
11
+ async function git(cwd, args, extraEnv, timeout) {
11
12
  const { stdout } = await exec('git', args, {
12
13
  cwd,
13
- env: commandEnv(),
14
+ env: { ...commandEnv(), ...extraEnv },
14
15
  maxBuffer: 32 * 1024 * 1024,
16
+ timeout,
15
17
  });
16
18
  return stdout.trim();
17
19
  }
@@ -23,6 +25,192 @@ export async function isGitRepo(dir) {
23
25
  return false;
24
26
  }
25
27
  }
28
+ // Inline credential helper: git shells this out and reads username/password
29
+ // from stdout. The token travels only in the child env (CARETAKER_GIT_TOKEN)
30
+ // — never on argv (visible in `ps`), never in .git/config.
31
+ const CRED_HELPER = '!f(){ echo username=x-access-token; echo password=$CARETAKER_GIT_TOKEN; }; f';
32
+ export function gitAuthArgs(hasToken) {
33
+ if (!hasToken)
34
+ return [];
35
+ // First -c clears any configured helpers so ours is the only one consulted —
36
+ // a system helper answering first with stale credentials would shadow the token.
37
+ return ['-c', 'credential.helper=', '-c', `credential.helper=${CRED_HELPER}`];
38
+ }
39
+ export function gitAuthEnv(token) {
40
+ // GIT_TERMINAL_PROMPT=0: the scheduler must never hang on an interactive
41
+ // username/password prompt — fail fast with a real error instead.
42
+ const env = { GIT_TERMINAL_PROMPT: '0' };
43
+ if (token)
44
+ env.CARETAKER_GIT_TOKEN = isEncrypted(token) ? decrypt(token) : token;
45
+ return env;
46
+ }
47
+ // Network ops only: a hung TCP connection would hold syncingProjects and the
48
+ // task lock until the OS timeout. Local git commands stay unbounded on purpose
49
+ // (a worktree add on a huge repo is slow but legitimate).
50
+ const NET_TIMEOUT_MS = 120_000;
51
+ /** Network git ops (clone/fetch/pull/push): auth + a readable error carrying
52
+ * git's stderr, which becomes blockedReason / UI copy downstream. */
53
+ async function netGit(cwd, args, token) {
54
+ try {
55
+ return await git(cwd, [...gitAuthArgs(!!token), ...args], gitAuthEnv(token), NET_TIMEOUT_MS);
56
+ }
57
+ catch (err) {
58
+ const e = err;
59
+ const detail = e.killed
60
+ ? `timed out after ${NET_TIMEOUT_MS / 1000}s`
61
+ : (e.stderr || e.message || String(err)).toString().trim();
62
+ throw new Error(`git ${args[0]} failed: ${detail}`);
63
+ }
64
+ }
65
+ /**
66
+ * Last line of defence before a remote URL reaches git. Form and API
67
+ * validation are UX; this is the enforcement point, because a URL git accepts
68
+ * gets written into `.git/config` and passed on argv. Anything that put a
69
+ * credential-bearing URL into the config by another route — a hand-edited
70
+ * `caretaker.json`, a surface whose save path lacks the check, a restored
71
+ * backup — is stopped here rather than leaking the secret.
72
+ */
73
+ function assertCleanRemoteUrl(url) {
74
+ let parsed;
75
+ try {
76
+ parsed = new URL(url);
77
+ }
78
+ catch {
79
+ return; // No scheme: a filesystem path, which cannot carry credentials.
80
+ }
81
+ if (parsed.username || parsed.password) {
82
+ throw new Error('Refusing to use a repository URL with embedded credentials: git would store it in .git/config and expose it in the process list. Remove the credentials from the URL and use the access token field.');
83
+ }
84
+ // Deliberately NOT enforcing https here — that transport policy belongs to
85
+ // config validation (lib/repo_url.ts). A filesystem path is a legitimate
86
+ // remote for a local mirror and for the tests.
87
+ }
88
+ export async function pushBranch(worktreePath, branch, repo) {
89
+ assertCleanRemoteUrl(repo.url);
90
+ // Push to the configured URL, not "origin": correct even when workingDir is a
91
+ // pre-existing local repo whose origin points elsewhere.
92
+ await netGit(worktreePath, ['push', repo.url, `${branch}:${branch}`], repo.token);
93
+ }
94
+ export function projectWorkingDir(project) {
95
+ const dir = (project.workingDir || '').trim();
96
+ if (dir)
97
+ return dir;
98
+ // Remote-backed with no explicit dir: managed clone under the data dir.
99
+ // Resolved at call time (dataDir() follows CARETAKER_HOME), never persisted.
100
+ if ((project.repositoryUrl || '').trim())
101
+ return join(dataDir(), 'repos', String(project.id));
102
+ return '';
103
+ }
104
+ /**
105
+ * The clone directory caretaker owns for this project, or null when the repo
106
+ * lives in a user-chosen `workingDir` (or the project isn't remote-backed).
107
+ * The delete path uses this: anything non-null is caretaker's to remove,
108
+ * anything null must never be touched.
109
+ */
110
+ export function managedRepoDir(project) {
111
+ if ((project.workingDir || '').trim())
112
+ return null;
113
+ return projectWorkingDir(project) || null;
114
+ }
115
+ export async function projectRepoStatus(project) {
116
+ const dest = projectWorkingDir(project);
117
+ if (!dest)
118
+ return { state: 'absent' };
119
+ let entries;
120
+ try {
121
+ entries = await readdir(dest);
122
+ }
123
+ catch {
124
+ return { state: 'absent' };
125
+ }
126
+ if (entries.length === 0)
127
+ return { state: 'absent' };
128
+ if (!(await isGitRepo(dest)))
129
+ return { state: 'broken' };
130
+ try {
131
+ const branch = await git(dest, ['rev-parse', '--abbrev-ref', 'HEAD']);
132
+ const commit = await git(dest, ['rev-parse', '--short', 'HEAD']);
133
+ return { state: 'cloned', branch, commit };
134
+ }
135
+ catch {
136
+ return { state: 'cloned' };
137
+ }
138
+ }
139
+ /**
140
+ * Clone-or-pull a remote-backed project's repository. Progress is yielded for
141
+ * the ndjson endpoint; the heartbeat just drains it. Throws on failure —
142
+ * callers turn that into a blocked task / in-band error line.
143
+ */
144
+ export async function* syncProjectRepo(project) {
145
+ const url = (project.repositoryUrl || '').trim();
146
+ if (!url)
147
+ throw new Error('Project has no repository URL');
148
+ assertCleanRemoteUrl(url);
149
+ const dest = projectWorkingDir(project);
150
+ const token = project.repositoryToken;
151
+ let status = await projectRepoStatus(project);
152
+ if (status.state === 'broken') {
153
+ // Auto-wipe only the managed default path. A user-chosen workingDir that
154
+ // isn't a repo could be anything (Documents, home…) — never delete it.
155
+ if ((project.workingDir || '').trim()) {
156
+ throw new Error(`Directory ${dest} exists but is not a git repository. ` +
157
+ `Refusing to overwrite a user-chosen directory — point the project at an empty or valid path.`);
158
+ }
159
+ yield { step: 'clean', message: `Removing broken checkout at ${dest}` };
160
+ await rm(dest, { recursive: true, force: true });
161
+ status = { state: 'absent' };
162
+ }
163
+ if (status.state === 'absent') {
164
+ const parent = dirname(dest);
165
+ await mkdir(parent, { recursive: true });
166
+ // Sweep temp dirs left by crashed clones (`<name>.cloning-<pid>`).
167
+ for (const entry of await readdir(parent)) {
168
+ if (entry.startsWith(`${basename(dest)}.cloning-`)) {
169
+ yield { step: 'clean', message: `Removing stale temp clone ${entry}` };
170
+ await rm(join(parent, entry), { recursive: true, force: true });
171
+ }
172
+ }
173
+ const tmp = `${dest}.cloning-${process.pid}`;
174
+ yield { step: 'clone', message: `Cloning ${url}` };
175
+ await netGit(parent, ['clone', url, tmp], token);
176
+ // Atomic hand-over: the destination only ever appears as a complete clone.
177
+ await rm(dest, { recursive: true, force: true }); // absent = missing or empty dir
178
+ await rename(tmp, dest);
179
+ }
180
+ else {
181
+ // Realign `origin` to the configured URL before touching the network:
182
+ // fetch/pull talk to whatever origin is, and the credential helper answers
183
+ // for ANY host it's asked about (no host matching). An inherited or
184
+ // pre-existing clone pointing elsewhere would be offered the project's
185
+ // token — confused deputy. `url` already passed assertCleanRemoteUrl.
186
+ const currentOrigin = await git(dest, ['remote', 'get-url', 'origin']).catch(() => null);
187
+ if (currentOrigin !== url) {
188
+ await git(dest, ['remote', currentOrigin === null ? 'add' : 'set-url', 'origin', url]);
189
+ yield { step: 'clean', message: `Realigned origin to ${url}` };
190
+ }
191
+ yield { step: 'pull', message: 'Fetching and fast-forwarding' };
192
+ await netGit(dest, ['fetch', 'origin'], token);
193
+ try {
194
+ await netGit(dest, ['pull', '--ff-only'], token);
195
+ }
196
+ catch (e) {
197
+ // Diverged (upstream force-push, stray local commit, realigned origin):
198
+ // ff-only then fails identically on every retry, so without a self-heal
199
+ // the project is stuck until someone deletes the dir by hand. Only
200
+ // caretaker writes to the MANAGED clone (tasks work in worktrees), so
201
+ // there is no user work to lose. A user-chosen workingDir is never reset
202
+ // — same rule as the `broken` wipe above.
203
+ if ((project.workingDir || '').trim())
204
+ throw e;
205
+ const upstream = await git(dest, ['rev-parse', '--abbrev-ref', '@{upstream}']).catch(() => null);
206
+ if (!upstream)
207
+ throw e;
208
+ yield { step: 'clean', message: `Diverged from ${upstream} — resetting the managed clone` };
209
+ await git(dest, ['reset', '--hard', upstream]);
210
+ }
211
+ }
212
+ yield { step: 'done', message: `Repository ready at ${dest}`, status: await projectRepoStatus(project) };
213
+ }
26
214
  function slug(title) {
27
215
  return (title
28
216
  .toLowerCase()
@@ -150,7 +338,11 @@ export async function finalizeDone(worktreePath) {
150
338
  await git(mainRepo, ['worktree', 'prune']).catch(() => { });
151
339
  }
152
340
  }
153
- export async function discardWorktree(worktreePath, title) {
341
+ export async function discardWorktree(worktreePath, title, push) {
154
342
  await commitWip(worktreePath, title);
343
+ // Push BEFORE removal: a failed push aborts the discard so unpushed work
344
+ // never loses its worktree. Callers surface the error to the user/agent.
345
+ if (push)
346
+ await pushBranch(worktreePath, push.branch, push);
155
347
  await finalizeDone(worktreePath);
156
348
  }
@@ -0,0 +1,13 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import type { Tool } from '../harness/tools/index.js';
3
+ import type { AgentConfig } from '../types.js';
4
+ export declare const TASK_PREFIX = "mcp__task__";
5
+ export declare const EMAIL_PREFIX = "mcp__email__";
6
+ export declare function builtinMcpTools(): Tool[];
7
+ export declare function buildBuiltinMcpServer(info?: {
8
+ name: string;
9
+ version: string;
10
+ }, opts?: {
11
+ callerAgent?: AgentConfig;
12
+ }): Server;
13
+ //# sourceMappingURL=builtin_server.d.ts.map