@celljs/ta-cloud-handoff 0.0.0-stage → 4.37.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.
package/host/index.mjs ADDED
@@ -0,0 +1,1362 @@
1
+ // web-src/handoff-auto.ts
2
+ import { isAbsolute } from "node:path";
3
+
4
+ // web-src/handoff-protocol.ts
5
+ var NAME = "@celljs/ta-cloud-handoff";
6
+ var BOOK_KEY = "book";
7
+ var SETTINGS_KEY = "settings";
8
+ var HandoffSettingsUtil;
9
+ ((HandoffSettingsUtil) => {
10
+ HandoffSettingsUtil.AUTO_MINUTES = 15;
11
+ HandoffSettingsUtil.AUTO_PERCENT = 10;
12
+ HandoffSettingsUtil.PERCENTS = [10, 20, 30];
13
+ function of(stored) {
14
+ const value = stored && typeof stored === "object" ? stored : {};
15
+ return {
16
+ sleep: value.sleep !== false,
17
+ battery: value.battery !== false,
18
+ threshold: typeof value.threshold === "number" && HandoffSettingsUtil.PERCENTS.includes(value.threshold) ? value.threshold : "auto",
19
+ bringBack: value.bringBack !== false
20
+ };
21
+ }
22
+ HandoffSettingsUtil.of = of;
23
+ function low(battery, settings) {
24
+ if (!battery || battery.plugged) {
25
+ return false;
26
+ }
27
+ if (settings.threshold !== "auto") {
28
+ return battery.percent <= settings.threshold;
29
+ }
30
+ return battery.minutesLeft !== undefined ? battery.minutesLeft <= HandoffSettingsUtil.AUTO_MINUTES : battery.percent <= HandoffSettingsUtil.AUTO_PERCENT;
31
+ }
32
+ HandoffSettingsUtil.low = low;
33
+ })(HandoffSettingsUtil ||= {});
34
+ var LATER_TOOL = "later_on_computer";
35
+ var LATER_ENTRY = "ta-cloud-handoff-later";
36
+ var NOTE_ENTRY = "ta-cloud-handoff";
37
+
38
+ // web-src/handoff-auto.ts
39
+ var RETRY_MS = 10 * 60000;
40
+ var BACK_MS = 60000;
41
+ var WARM_MS = 30 * 60000;
42
+
43
+ class HandoffAuto {
44
+ host;
45
+ handoffs;
46
+ options;
47
+ failed = new Map;
48
+ warmed = new Map;
49
+ battery;
50
+ moving;
51
+ timer;
52
+ stops = [];
53
+ constructor(host, handoffs, options = {}) {
54
+ this.host = host;
55
+ this.handoffs = handoffs;
56
+ this.options = options;
57
+ }
58
+ begin() {
59
+ if (this.host.power) {
60
+ this.stops.push(this.host.power.onEvent((event) => this.onPower(event)));
61
+ }
62
+ this.stops.push(this.host.onSessionEvent((event) => {
63
+ if (event.type === "turn_start" && !event.group && isAbsolute(event.cwd)) {
64
+ this.warm(event.cwd);
65
+ }
66
+ }));
67
+ this.scheduleBack(0);
68
+ }
69
+ dispose() {
70
+ for (const stop of this.stops.splice(0)) {
71
+ stop();
72
+ }
73
+ clearTimeout(this.timer);
74
+ }
75
+ async settings() {
76
+ return HandoffSettingsUtil.of(await this.host.getExtensionData(NAME, SETTINGS_KEY).catch(() => {
77
+ return;
78
+ }));
79
+ }
80
+ async power() {
81
+ const battery = await this.host.power?.battery().catch(() => {
82
+ return;
83
+ }) ?? undefined;
84
+ return { ...battery ? { battery } : {}, low: HandoffSettingsUtil.low(battery, await this.settings()) };
85
+ }
86
+ async onPower(event) {
87
+ const settings = await this.settings();
88
+ if (event.type === "sleep") {
89
+ if (settings.sleep) {
90
+ await this.moveRunning("sleep");
91
+ }
92
+ return;
93
+ }
94
+ if (event.type === "battery") {
95
+ this.battery = event.battery;
96
+ }
97
+ if (settings.battery && HandoffSettingsUtil.low(this.battery, settings)) {
98
+ await this.moveRunning("battery");
99
+ } else if (settings.bringBack) {
100
+ this.scheduleBack(0);
101
+ }
102
+ }
103
+ moveRunning(why) {
104
+ this.moving ??= this.move(why).finally(() => {
105
+ this.moving = undefined;
106
+ });
107
+ return this.moving;
108
+ }
109
+ async move(why) {
110
+ const { workspaces } = await this.handoffs.list();
111
+ if (!workspaces.length) {
112
+ return;
113
+ }
114
+ const now = this.now();
115
+ const running = (await this.host.listSessions()).filter((session) => session.isStreaming && session.sessionFile && !session.group && isAbsolute(session.cwd) && now - (this.failed.get(session.sessionFile) ?? -Infinity) >= (this.options.retryMs ?? RETRY_MS));
116
+ await Promise.all(running.map((session) => this.handoffs.handOff(session.sessionFile, undefined, true, why).then(() => this.failed.delete(session.sessionFile), () => this.failed.set(session.sessionFile, this.now()))));
117
+ }
118
+ scheduleBack(ms) {
119
+ clearTimeout(this.timer);
120
+ this.timer = setTimeout(() => void this.bringBack(), ms);
121
+ this.timer.unref?.();
122
+ }
123
+ async bringBack() {
124
+ this.timer = undefined;
125
+ const settings = await this.settings();
126
+ if (!settings.bringBack) {
127
+ return;
128
+ }
129
+ const away = (await this.away()).filter((handoff) => handoff.auto);
130
+ if (!away.length) {
131
+ return;
132
+ }
133
+ if (!HandoffSettingsUtil.low(this.battery, settings)) {
134
+ for (const handoff of away) {
135
+ if (handoff.state === "cloud" && await this.handoffs.idleThere(handoff.id).catch(() => false)) {
136
+ await this.handoffs.takeBack(handoff.id).catch(() => {
137
+ return;
138
+ });
139
+ }
140
+ }
141
+ }
142
+ if ((await this.away()).some((handoff) => handoff.auto)) {
143
+ this.scheduleBack(this.options.backMs ?? BACK_MS);
144
+ }
145
+ }
146
+ async away() {
147
+ return (await this.handoffs.list().catch(() => {
148
+ return;
149
+ }))?.handoffs ?? [];
150
+ }
151
+ async warm(cwd) {
152
+ const now = this.now();
153
+ if (now - (this.warmed.get(cwd) ?? -Infinity) < (this.options.warmMs ?? WARM_MS)) {
154
+ return;
155
+ }
156
+ this.warmed.set(cwd, now);
157
+ const settings = await this.settings();
158
+ if (!settings.sleep && !settings.battery) {
159
+ return;
160
+ }
161
+ if (!(await this.handoffs.list().catch(() => ({ workspaces: [] }))).workspaces.length) {
162
+ return;
163
+ }
164
+ await this.handoffs.warm(cwd).catch(() => {
165
+ return;
166
+ });
167
+ }
168
+ now() {
169
+ return this.options.now?.() ?? Date.now();
170
+ }
171
+ }
172
+
173
+ // web-src/handoff-service.ts
174
+ import { randomUUID as randomUUID2 } from "node:crypto";
175
+ import { appendFile as appendFile2, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
176
+ import { tmpdir } from "node:os";
177
+ import { basename, dirname, isAbsolute as isAbsolute2, join, posix, relative, sep } from "node:path";
178
+
179
+ // ../ta-protocol/esm/common/message-protocol.js
180
+ var TaMessageContext;
181
+ (function(TaMessageContext2) {
182
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
183
+ function wrap(context, message) {
184
+ return `<context>
185
+ ${context}
186
+ </context>
187
+ ${message}`;
188
+ }
189
+ TaMessageContext2.wrap = wrap;
190
+ function strip(message) {
191
+ return message.replace(BLOCK, "");
192
+ }
193
+ TaMessageContext2.strip = strip;
194
+ function read(message) {
195
+ var _a;
196
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
197
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
198
+ }
199
+ TaMessageContext2.read = read;
200
+ })(TaMessageContext || (TaMessageContext = {}));
201
+ var TaMessageSource;
202
+ (function(TaMessageSource2) {
203
+ TaMessageSource2.DOUBLE = "ta:double";
204
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
205
+ function mark(message, from, detail) {
206
+ return marked(message, line(from, detail));
207
+ }
208
+ TaMessageSource2.mark = mark;
209
+ function notice(message, from, detail) {
210
+ return marked(message, line(from, detail, true));
211
+ }
212
+ TaMessageSource2.notice = notice;
213
+ function line(from, detail, notice2 = false) {
214
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
215
+ }
216
+ TaMessageSource2.line = line;
217
+ function of(message) {
218
+ const context = TaMessageContext.read(message);
219
+ const match = context === undefined ? null : LINE.exec(context);
220
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
221
+ }
222
+ TaMessageSource2.of = of;
223
+ function isNotice(message) {
224
+ var _a;
225
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
226
+ }
227
+ TaMessageSource2.isNotice = isNotice;
228
+ TaMessageSource2.SECTION = "ta-sources";
229
+ TaMessageSource2.PROMPT = [
230
+ "Who wrote a message: what the user typed or said is theirs. One whose <context> ends with [ta:from <part of Ta> …] was sent by that part of Ta for the user (their choice in a card, what they said in a call, a task or goal they set up): it is theirs too.",
231
+ "One with [ta:notice <part of Ta> …] is not the user's: news or an event of that part of Ta (work that ended elsewhere, a time limit, a permission granted). Weigh it below what the user said:",
232
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
233
+ "- Act on it only as far as what they asked, your role or a limit they set calls for; otherwise take it in and go on, and tell them of it in a line only when they need it (a result they wait for, a failure, a question for them).",
234
+ "- Never quote it as the user's words nor answer it as if they had said it."
235
+ ].join(`
236
+ `);
237
+ function marked(message, source) {
238
+ if (/^[/!]/.test(message) || of(message)) {
239
+ return message;
240
+ }
241
+ const context = TaMessageContext.read(message);
242
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
243
+ ${source}`, TaMessageContext.strip(message));
244
+ }
245
+ })(TaMessageSource || (TaMessageSource = {}));
246
+ var TaImageNote;
247
+ (function(TaImageNote2) {
248
+ const NOTE = /^\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]$|^\[Image converted from [^\]]+ to [^\]]+\.\]$/;
249
+ function strip(text) {
250
+ const lines = text.split(`
251
+ `);
252
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
253
+ if (kept.length === lines.length) {
254
+ return text;
255
+ }
256
+ return kept.join(`
257
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
258
+ }
259
+ TaImageNote2.strip = strip;
260
+ })(TaImageNote || (TaImageNote = {}));
261
+ var TaImageSize;
262
+ (function(TaImageSize2) {
263
+ const JPEG_BYTES = 256 * 1024;
264
+ function type(bytes) {
265
+ const at = (offset, ...values) => values.every((value, index) => bytes[offset + index] === value);
266
+ return at(0, 255, 216, 255) ? "image/jpeg" : at(0, 137, 80, 78, 71) ? "image/png" : at(0, 71, 73, 70, 56) ? "image/gif" : at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80) ? "image/webp" : undefined;
267
+ }
268
+ TaImageSize2.type = type;
269
+ function of(base64) {
270
+ var _a, _b, _c;
271
+ let bytes;
272
+ try {
273
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
274
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
275
+ } catch (_d) {
276
+ return;
277
+ }
278
+ const size = (_c = (_b = (_a = png(bytes)) !== null && _a !== undefined ? _a : gif(bytes)) !== null && _b !== undefined ? _b : webp(bytes)) !== null && _c !== undefined ? _c : jpeg(bytes);
279
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
280
+ }
281
+ TaImageSize2.of = of;
282
+ function u16be(bytes, at) {
283
+ return bytes[at] << 8 | bytes[at + 1];
284
+ }
285
+ function u16le(bytes, at) {
286
+ return bytes[at] | bytes[at + 1] << 8;
287
+ }
288
+ function u24le(bytes, at) {
289
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
290
+ }
291
+ function u32be(bytes, at) {
292
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
293
+ }
294
+ function text(bytes, at, length) {
295
+ return String.fromCharCode(...bytes.subarray(at, at + length));
296
+ }
297
+ function png(bytes) {
298
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
299
+ }
300
+ function gif(bytes) {
301
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
302
+ }
303
+ function webp(bytes) {
304
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
305
+ return;
306
+ }
307
+ switch (text(bytes, 12, 4)) {
308
+ case "VP8 ":
309
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
310
+ case "VP8L": {
311
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
312
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
313
+ }
314
+ case "VP8X":
315
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
316
+ default:
317
+ return;
318
+ }
319
+ }
320
+ function jpeg(bytes) {
321
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
322
+ return;
323
+ }
324
+ let at = 2;
325
+ while (at + 9 < bytes.length) {
326
+ if (bytes[at] !== 255) {
327
+ return;
328
+ }
329
+ const marker = bytes[at + 1];
330
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
331
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
332
+ }
333
+ at += 2 + u16be(bytes, at + 2);
334
+ }
335
+ return;
336
+ }
337
+ })(TaImageSize || (TaImageSize = {}));
338
+ var TaAgentSummary;
339
+ (function(TaAgentSummary2) {
340
+ const START = /^\s*<conversation_history_summary>/;
341
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
342
+ function read(text) {
343
+ if (!START.test(text)) {
344
+ return;
345
+ }
346
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
347
+ }
348
+ TaAgentSummary2.read = read;
349
+ function strip(text) {
350
+ return text.replace(BLOCK, "");
351
+ }
352
+ TaAgentSummary2.strip = strip;
353
+ })(TaAgentSummary || (TaAgentSummary = {}));
354
+ var TaPictureNote;
355
+ (function(TaPictureNote2) {
356
+ TaPictureNote2.OPEN = "<pictures>";
357
+ TaPictureNote2.CLOSE = "</pictures>";
358
+ const BLOCK = /[ \t]*<pictures>([\s\S]*?)(?:<\/pictures>|$)|<p(?:i(?:c(?:t(?:u(?:r(?:es?)?)?)?)?)?)?$/gi;
359
+ const ROW = /(?:^|\s)[-*]?\s*p(\d+)\s*[::]\s*/gi;
360
+ function take(text) {
361
+ const told = new Map;
362
+ if (!/<p/i.test(text)) {
363
+ return { said: text, told };
364
+ }
365
+ const said = text.replace(BLOCK, (_all, body) => {
366
+ const rows = [...(body !== null && body !== undefined ? body : "").matchAll(ROW)];
367
+ rows.forEach((row, index) => {
368
+ var _a;
369
+ var _b, _c;
370
+ const end = (_b = (_a = rows[index + 1]) === null || _a === undefined ? undefined : _a.index) !== null && _b !== undefined ? _b : body === null || body === undefined ? undefined : body.length;
371
+ const what = body === null || body === undefined ? undefined : body.slice(((_c = row.index) !== null && _c !== undefined ? _c : 0) + row[0].length, end).trim();
372
+ if (what) {
373
+ told.set(Number(row[1]), what);
374
+ }
375
+ });
376
+ return "";
377
+ });
378
+ return { said: said === text ? text : said.replace(/\n{3,}/g, `
379
+
380
+ `).trim(), told };
381
+ }
382
+ TaPictureNote2.take = take;
383
+ function strip(text) {
384
+ return take(text).said;
385
+ }
386
+ TaPictureNote2.strip = strip;
387
+ })(TaPictureNote || (TaPictureNote = {}));
388
+ var TaSkillUse;
389
+ (function(TaSkillUse2) {
390
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
391
+ function parse(message) {
392
+ var _a;
393
+ const match = BLOCK.exec(message);
394
+ if (!match) {
395
+ return;
396
+ }
397
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
398
+ }
399
+ TaSkillUse2.parse = parse;
400
+ function command(use) {
401
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
402
+ }
403
+ TaSkillUse2.command = command;
404
+ })(TaSkillUse || (TaSkillUse = {}));
405
+ var TaTaskNote;
406
+ (function(TaTaskNote2) {
407
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
408
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
409
+ function write(note) {
410
+ const attributes = [`id="${quote(note.id)}"`];
411
+ if (note.was !== undefined) {
412
+ attributes.push(`was="${quote(note.was)}"`);
413
+ }
414
+ attributes.push(`title="${quote(note.title)}"`);
415
+ if (note.status !== undefined) {
416
+ attributes.push(`status="${quote(note.status)}"`);
417
+ }
418
+ return `<task_${note.kind} ${attributes.join(" ")}>
419
+ ${note.body}
420
+ </task_${note.kind}>`;
421
+ }
422
+ TaTaskNote2.write = write;
423
+ function parse(text) {
424
+ const match = NOTE.exec(text.trim());
425
+ if (!match) {
426
+ return;
427
+ }
428
+ const attributes = {};
429
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
430
+ attributes[name] = unquote(value);
431
+ }
432
+ if (!attributes.id || attributes.title === undefined) {
433
+ return;
434
+ }
435
+ const { id, title, status, was } = attributes;
436
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
437
+ }
438
+ TaTaskNote2.parse = parse;
439
+ function quote(text) {
440
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
441
+ }
442
+ function unquote(text) {
443
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
444
+ }
445
+ })(TaTaskNote || (TaTaskNote = {}));
446
+ var TaSecretRef;
447
+ (function(TaSecretRef2) {
448
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
449
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
450
+ const KINDS = [
451
+ [/^PHONE(?:_\d+)?$/, "phone"],
452
+ [/^EMAIL(?:_\d+)?$/, "email"],
453
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
454
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
455
+ ];
456
+ function has(text) {
457
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
458
+ }
459
+ TaSecretRef2.has = has;
460
+ function kind(name) {
461
+ var _a;
462
+ var _b;
463
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
464
+ }
465
+ TaSecretRef2.kind = kind;
466
+ function split(text) {
467
+ if (!has(text)) {
468
+ return [{ text }];
469
+ }
470
+ const parts = [];
471
+ let at = 0;
472
+ for (const match of text.matchAll(REF)) {
473
+ if (match.index > at) {
474
+ parts.push({ text: text.slice(at, match.index) });
475
+ }
476
+ parts.push({ secret: match[1], kind: kind(match[1]) });
477
+ at = match.index + match[0].length;
478
+ }
479
+ if (at < text.length) {
480
+ parts.push({ text: text.slice(at) });
481
+ }
482
+ return parts;
483
+ }
484
+ TaSecretRef2.split = split;
485
+ function plain(text, label) {
486
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
487
+ }
488
+ TaSecretRef2.plain = plain;
489
+ })(TaSecretRef || (TaSecretRef = {}));
490
+
491
+ // web-src/handoff-scripts.ts
492
+ var HandoffScripts;
493
+ ((HandoffScripts) => {
494
+ HandoffScripts.MARK = "@@ta";
495
+ function q(value) {
496
+ return `'${value.replace(/'/g, "'\\''")}'`;
497
+ }
498
+ HandoffScripts.q = q;
499
+ function results(output) {
500
+ const lines = output.split(`
501
+ `);
502
+ const at = lines.lastIndexOf(HandoffScripts.MARK);
503
+ const values = {};
504
+ for (const line of at < 0 ? [] : lines.slice(at + 1)) {
505
+ const equals = line.indexOf("=");
506
+ if (equals > 0) {
507
+ values[line.slice(0, equals)] = line.slice(equals + 1);
508
+ }
509
+ }
510
+ return values;
511
+ }
512
+ HandoffScripts.results = results;
513
+ function ref(id, side) {
514
+ return `refs/ta-handoff/${id}/${side}`;
515
+ }
516
+ HandoffScripts.ref = ref;
517
+ const PRELUDE = [
518
+ "set -e",
519
+ "export GIT_AUTHOR_NAME=Ta GIT_AUTHOR_EMAIL=ta@localhost GIT_COMMITTER_NAME=Ta GIT_COMMITTER_EMAIL=ta@localhost",
520
+ 'ta_index() { ta_idx=$(mktemp "${TMPDIR:-/tmp}/ta-handoff.XXXXXX"); ta_real=$(git rev-parse --git-path index); if [ -f "$ta_real" ]; then cp "$ta_real" "$ta_idx"; else rm -f "$ta_idx"; fi; }',
521
+ 'ta_tree() { ta_index; GIT_INDEX_FILE="$ta_idx" git add -A; GIT_INDEX_FILE="$ta_idx" git write-tree; rm -f "$ta_idx"; }',
522
+ 'ta_switch() { ta_index; GIT_INDEX_FILE="$ta_idx" git add -A; GIT_INDEX_FILE="$ta_idx" git read-tree -m -u "$1" "$2"; rm -f "$ta_idx"; }'
523
+ ].join(`
524
+ `);
525
+ function program(...lines) {
526
+ return [PRELUDE, ...lines.filter(Boolean)].join(`
527
+ `);
528
+ }
529
+ function top() {
530
+ return program('git rev-parse --verify -q "HEAD^{commit}" >/dev/null || { echo "The repository has no commit yet." >&2; exit 3; }', "git rev-parse --show-toplevel");
531
+ }
532
+ HandoffScripts.top = top;
533
+ function snapshot(id, side) {
534
+ return program('head=$(git rev-parse --verify "HEAD^{commit}")', "tree=$(ta_tree)", `commit=$(git commit-tree "$tree" -p "$head" -m 'Ta: the work as it was handed over')`, `git update-ref ${q(ref(id, side))} "$commit"`, "branch=$(git symbolic-ref -q --short HEAD || true)", `echo ${HandoffScripts.MARK}`, 'echo "head=$head"', 'echo "tree=$tree"', 'echo "commit=$commit"', 'echo "branch=$branch"');
535
+ }
536
+ HandoffScripts.snapshot = snapshot;
537
+ function bundle(file, refs, not) {
538
+ const args = [...refs.map(q), ...not.length ? ["--not", ...not.map(q)] : []].join(" ");
539
+ return program(`rm -f ${q(file)}`, `git bundle create -q ${q(file)} ${args}`, `echo ${HandoffScripts.MARK}`, `echo "size=$(wc -c < ${q(file)} | tr -d ' ')"`);
540
+ }
541
+ HandoffScripts.bundle = bundle;
542
+ function size(file) {
543
+ return program(`echo ${HandoffScripts.MARK}`, `echo "size=$(wc -c < ${q(file)} | tr -d ' ')"`);
544
+ }
545
+ HandoffScripts.size = size;
546
+ function fetch(file, ref2, into = ref2) {
547
+ return program(`git fetch -q ${q(file)} ${q(`+${ref2}:${into}`)}`, `rm -f ${q(file)}`);
548
+ }
549
+ HandoffScripts.fetch = fetch;
550
+ function head() {
551
+ return program(`echo ${HandoffScripts.MARK}`, 'echo "head=$(git rev-parse --verify "HEAD^{commit}")"');
552
+ }
553
+ HandoffScripts.head = head;
554
+ function prepare(root, source, last, setup) {
555
+ return program(`want=${q(root)}`, `source=${q(source)}`, "pick=", 'for d in "$want" "$HOME/ta-handoff$want"; do', ' if [ -d "$d/.git" ] && [ "$(git -C "$d" config --get ta.handoff.source 2>/dev/null)" = "$source" ]; then pick=$d; break; fi', "done", 'if [ -z "$pick" ]; then', ' if [ ! -e "$want" ] && { mkdir -p "$want" 2>/dev/null || { sudo -n mkdir -p "$want" 2>/dev/null && sudo -n chown "$(id -u):$(id -g)" "$want"; }; }; then pick=$want', ' else pick="$HOME/ta-handoff$want"; fi', ' mkdir -p "$pick"', ' if [ -e "$pick/.git" ]; then echo "$pick holds another repository." >&2; exit 4; fi', ' git init -q "$pick"', ' git -C "$pick" config ta.handoff.source "$source"', "fi", setup.name ? `git -C "$pick" config user.name ${q(setup.name)}` : "", setup.email ? `git -C "$pick" config user.email ${q(setup.email)}` : "", setup.origin ? `git -C "$pick" remote get-url origin >/dev/null 2>&1 || git -C "$pick" remote add origin ${q(setup.origin)}` : "", "has=no", last ? `git -C "$pick" cat-file -e ${q(`${last}^{commit}`)} 2>/dev/null && has=yes || true` : "", `echo ${HandoffScripts.MARK}`, 'echo "root=$pick"', 'echo "has=$has"', 'echo "home=$HOME"', 'echo "agent=${TA_CODING_AGENT_DIR:-$HOME/.ta/agent}"');
556
+ }
557
+ HandoffScripts.prepare = prepare;
558
+ function receive(file, snapshotRef, head2, branch) {
559
+ return program(`git fetch -q ${q(file)} ${q(`+${snapshotRef}:${snapshotRef}`)}`, `rm -f ${q(file)}`, "git reset -q --hard 2>/dev/null || true", "git clean -fdq", branch ? `git checkout -q -f -B ${q(branch)} ${q(head2)}` : `git checkout -q -f --detach ${q(head2)}`, "git clean -fdq", `ta_switch ${q(head2)} ${q(snapshotRef)}`, `echo ${HandoffScripts.MARK}`, 'echo "tree=$(ta_tree)"');
560
+ }
561
+ HandoffScripts.receive = receive;
562
+ function land(from, to, head2) {
563
+ return program(`ta_switch ${q(from)} ${q(to)}`, head2 ? `git reset -q ${q(head2)}` : "", `echo ${HandoffScripts.MARK}`, 'echo "tree=$(ta_tree)"');
564
+ }
565
+ HandoffScripts.land = land;
566
+ function merge(base, here, there) {
567
+ return program(`a=$(git commit-tree ${q(`${here}^{tree}`)} -p ${q(base)} -m here)`, `b=$(git commit-tree ${q(`${there}^{tree}`)} -p ${q(base)} -m there)`, "set +e", 'out=$(git merge-tree --write-tree --name-only --no-messages "$a" "$b")', "code=$?", "set -e", '[ $code -le 1 ] || { echo "$out" >&2; exit $code; }', `echo ${HandoffScripts.MARK}`, 'echo "tree=$(echo "$out" | head -n 1)"', `[ $code -eq 0 ] || echo "conflicts=$(echo "$out" | tail -n +2 | grep -v "^$" | sort -u | tr "
568
+ " " ")"`);
569
+ }
570
+ HandoffScripts.merge = merge;
571
+ function count(from, to) {
572
+ return program(`echo ${HandoffScripts.MARK}`, `echo "count=$(git rev-list --count ${q(`${from}..${to}`)})"`);
573
+ }
574
+ HandoffScripts.count = count;
575
+ function forget(id, sides) {
576
+ return program(...sides.map((side) => `git update-ref -d ${q(ref(id, side))} 2>/dev/null || true`));
577
+ }
578
+ HandoffScripts.forget = forget;
579
+ })(HandoffScripts ||= {});
580
+
581
+ // web-src/handoff-sessions.ts
582
+ import { randomUUID } from "node:crypto";
583
+ var HandoffSessions;
584
+ ((HandoffSessions) => {
585
+ function lines(text) {
586
+ return text.split(`
587
+ `).filter((line) => line.trim());
588
+ }
589
+ HandoffSessions.lines = lines;
590
+ function directory(cwd) {
591
+ return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
592
+ }
593
+ HandoffSessions.directory = directory;
594
+ function relocate(text, cwd) {
595
+ const all = text.split(`
596
+ `);
597
+ try {
598
+ const header = JSON.parse(all[0]);
599
+ if (header.type === "session" && header.cwd !== cwd) {
600
+ all[0] = JSON.stringify({ ...header, cwd });
601
+ }
602
+ } catch {}
603
+ return all.join(`
604
+ `);
605
+ }
606
+ HandoffSessions.relocate = relocate;
607
+ function later(lines2) {
608
+ return lines2.flatMap((line) => {
609
+ try {
610
+ const entry = JSON.parse(line);
611
+ return entry.type === "custom" && entry.customType === LATER_ENTRY && typeof entry.data?.what === "string" ? [entry.data.what] : [];
612
+ } catch {
613
+ return [];
614
+ }
615
+ });
616
+ }
617
+ HandoffSessions.later = later;
618
+ function note(lines2, content, details, display = true, now = Date.now()) {
619
+ let parentId = null;
620
+ for (let at = lines2.length - 1;at >= 0 && parentId === null; at--) {
621
+ try {
622
+ const entry2 = JSON.parse(lines2[at]);
623
+ if (entry2.type !== "session" && typeof entry2.id === "string") {
624
+ parentId = entry2.id;
625
+ }
626
+ } catch {}
627
+ }
628
+ const entry = {
629
+ type: "custom_message",
630
+ id: randomUUID().slice(0, 8),
631
+ parentId,
632
+ timestamp: new Date(now).toISOString(),
633
+ customType: NOTE_ENTRY,
634
+ content,
635
+ details,
636
+ display
637
+ };
638
+ return JSON.stringify(entry);
639
+ }
640
+ HandoffSessions.note = note;
641
+ })(HandoffSessions ||= {});
642
+
643
+ // web-src/handoff-sides.ts
644
+ import { spawn } from "node:child_process";
645
+ import { appendFile, open, writeFile } from "node:fs/promises";
646
+ class HandoffError extends Error {
647
+ code;
648
+ constructor(message, code) {
649
+ super(message);
650
+ this.code = code;
651
+ this.name = "HandoffError";
652
+ }
653
+ }
654
+ function failure(output, code) {
655
+ const said = output.split(`
656
+ `).filter((line) => line.trim() && !line.startsWith(HandoffScripts.MARK)).slice(-6).join(`
657
+ `);
658
+ return new HandoffError(said || `exited with ${code}`, code);
659
+ }
660
+
661
+ class LocalSide {
662
+ env;
663
+ constructor(env = {}) {
664
+ this.env = env;
665
+ }
666
+ run(script, cwd) {
667
+ return new Promise((resolve, reject) => {
668
+ const child = spawn("sh", ["-c", script], { cwd, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", LC_ALL: "C", ...this.env } });
669
+ let output = "";
670
+ let errors = "";
671
+ child.stdout.on("data", (data) => {
672
+ output += data.toString();
673
+ });
674
+ child.stderr.on("data", (data) => {
675
+ errors += data.toString();
676
+ });
677
+ child.on("error", reject);
678
+ child.on("close", (code) => code === 0 ? resolve(output) : reject(failure(`${output}
679
+ ${errors}`, code)));
680
+ });
681
+ }
682
+ async read(path, offset, length) {
683
+ const file = await open(path, "r");
684
+ try {
685
+ const data = new Uint8Array(length);
686
+ const { bytesRead } = await file.read(data, 0, length, offset);
687
+ return data.subarray(0, bytesRead);
688
+ } finally {
689
+ await file.close();
690
+ }
691
+ }
692
+ async write(path, data, append) {
693
+ await (append ? appendFile(path, data) : writeFile(path, data));
694
+ }
695
+ }
696
+ var CLOUD_TIMEOUT_MS = 10 * 60 * 1000;
697
+
698
+ class CloudSide {
699
+ cloud;
700
+ name;
701
+ constructor(cloud, name) {
702
+ this.cloud = cloud;
703
+ this.name = name;
704
+ }
705
+ async run(script, cwd) {
706
+ const result = await this.cloud.run(this.name, script, { cwd, timeoutMs: CLOUD_TIMEOUT_MS });
707
+ if (result.exitCode !== 0) {
708
+ throw failure(result.output, result.exitCode);
709
+ }
710
+ return result.output;
711
+ }
712
+ async read(path, offset, length) {
713
+ const q = HandoffScripts.q;
714
+ const piece = `${path}.ta-piece`;
715
+ await this.run(`tail -c +${offset + 1} ${q(path)} | head -c ${length} > ${q(piece)}`);
716
+ try {
717
+ return await this.cloud.readFile(this.name, piece);
718
+ } finally {
719
+ await this.run(`rm -f ${q(piece)}`).catch(() => {
720
+ return;
721
+ });
722
+ }
723
+ }
724
+ async write(path, data, append) {
725
+ await this.cloud.writeFile(this.name, path, data, { append });
726
+ }
727
+ }
728
+ var HandoffTransfer;
729
+ ((HandoffTransfer) => {
730
+ HandoffTransfer.PIECE = 4 * 1024 * 1024;
731
+ async function copy(from, fromPath, size, to, toPath) {
732
+ let offset = 0;
733
+ do {
734
+ const data = await from.read(fromPath, offset, Math.min(HandoffTransfer.PIECE, Math.max(size - offset, 0)));
735
+ await to.write(toPath, data, offset > 0);
736
+ offset += HandoffTransfer.PIECE;
737
+ } while (offset < size);
738
+ }
739
+ HandoffTransfer.copy = copy;
740
+ })(HandoffTransfer ||= {});
741
+
742
+ // ../ta-protocol/esm/common/language.js
743
+ var TaLanguageUtil;
744
+ (function(TaLanguageUtil2) {
745
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
746
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
747
+ function of(tag) {
748
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
749
+ if (/^zh(\b|-)/.test(said)) {
750
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
751
+ }
752
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
753
+ }
754
+ TaLanguageUtil2.of = of;
755
+ function server(env = typeof process === "undefined" ? {} : process.env) {
756
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
757
+ }
758
+ TaLanguageUtil2.server = server;
759
+ function pick(language, words) {
760
+ return words[of(language)];
761
+ }
762
+ TaLanguageUtil2.pick = pick;
763
+ function say(words) {
764
+ return words[server()];
765
+ }
766
+ TaLanguageUtil2.say = say;
767
+ function chinese(language) {
768
+ return of(language).startsWith("zh");
769
+ }
770
+ TaLanguageUtil2.chinese = chinese;
771
+ function cjk(language) {
772
+ return of(language) !== "en-US";
773
+ }
774
+ TaLanguageUtil2.cjk = cjk;
775
+ function list(language, items) {
776
+ return items.join(cjk(language) ? "、" : ", ");
777
+ }
778
+ TaLanguageUtil2.list = list;
779
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
780
+
781
+ // web-src/server-texts.ts
782
+ var WHY = {
783
+ asked: "as the user asked",
784
+ sleep: "by itself as the user's computer was about to sleep (its lid closed, most likely)",
785
+ battery: "by itself as the battery of the user's computer ran low"
786
+ };
787
+ var HandoffTexts;
788
+ ((HandoffTexts) => {
789
+ function toCloud(options) {
790
+ return [
791
+ `This conversation moved from the user's computer to the cloud workspace ${options.cloud}, ${WHY[options.why ?? "asked"]}, to go on while their computer is away.`,
792
+ options.root === options.cloudRoot ? `- The files of ${options.root} are here at the same path, as they were: commits, changes and new files alike.` : `- The files of ${options.root} of the user's computer are here at ${options.cloudRoot}, as they were: commits, changes and new files alike. Read paths of the conversation so far under ${options.root} as under ${options.cloudRoot}.`,
793
+ "- What git ignores (installed dependencies, builds, .env files) did not come along: install or build again, as the project does, when you need them.",
794
+ options.cut ? "- The last turn was stopped as it moved: a command that ran then was cut off. Check what it did, and run it again if needed." : "",
795
+ `- Leave what only the user's computer can do (its apps, desktop, devices, local network, keychain, signed-in tools): note each with the tool ${LATER_TOOL} (without it, list them at the end of your reply under "Back on the computer"), and go on with the rest.`,
796
+ "- Push, publish or deploy only if the user asked for it in this conversation.",
797
+ options.goOn ? "- Go on with the work where it stopped." : ""
798
+ ].filter(Boolean).join(`
799
+ `);
800
+ }
801
+ HandoffTexts.toCloud = toCloud;
802
+ function back(options) {
803
+ const files = {
804
+ same: "The files are as they were: nothing changed in the cloud.",
805
+ taken: "The files here are now as the cloud left them.",
806
+ merged: "The files here are the cloud's work merged with what changed here meanwhile.",
807
+ conflict: `The files here were left as they were: these were changed both here and in the cloud: ${options.conflicts.join(", ")}. The cloud's work is in the commit ${options.ref}: compare and bring it in.`
808
+ };
809
+ return [
810
+ `This conversation came back from the cloud workspace ${options.cloud} to the user's computer.`,
811
+ `- ${files[options.files] ?? ""}`,
812
+ options.commits ? `- ${options.commits} commit(s) made in the cloud are on the branch here.` : "",
813
+ options.ref && options.files !== "conflict" ? `- HEAD moved here meanwhile: the cloud's commits are kept at ${options.ref}.` : "",
814
+ options.later.length ? `- Left for this computer: ${options.later.map((item) => `
815
+ - ${item}`).join("")}` : "",
816
+ options.goOn ? "- Go on here: do what was left for this computer, and look at the files if they need it." : ""
817
+ ].filter(Boolean).join(`
818
+ `);
819
+ }
820
+ HandoffTexts.back = back;
821
+ function goOn(note) {
822
+ const cloud = note.cloud;
823
+ const head = note.to === "cloud" && note.why === "sleep" ? TaLanguageUtil.say({
824
+ "zh-CN": `电脑要睡眠了,换到云端接着做 · ${cloud}`,
825
+ "zh-TW": `電腦要睡眠了,換到雲端接著做 · ${cloud}`,
826
+ "en-US": `The computer is going to sleep: going on in the cloud · ${cloud}`,
827
+ "ja-JP": `パソコンがスリープするのでクラウドで続ける · ${cloud}`
828
+ }) : note.to === "cloud" && note.why === "battery" ? TaLanguageUtil.say({
829
+ "zh-CN": `电量低,换到云端接着做 · ${cloud}`,
830
+ "zh-TW": `電量低,換到雲端接著做 · ${cloud}`,
831
+ "en-US": `Battery low: going on in the cloud · ${cloud}`,
832
+ "ja-JP": `電池残量が少ないのでクラウドで続ける · ${cloud}`
833
+ }) : note.to === "cloud" ? TaLanguageUtil.say({
834
+ "zh-CN": `换到云端接着做 · ${cloud}`,
835
+ "zh-TW": `換到雲端接著做 · ${cloud}`,
836
+ "en-US": `Going on in the cloud · ${cloud}`,
837
+ "ja-JP": `クラウドで続ける · ${cloud}`
838
+ }) : TaLanguageUtil.say({
839
+ "zh-CN": `从云端 ${cloud} 接回本机`,
840
+ "zh-TW": `從雲端 ${cloud} 接回本機`,
841
+ "en-US": `Back on this computer from ${cloud}`,
842
+ "ja-JP": `クラウド ${cloud} からこのパソコンに戻しました`
843
+ });
844
+ const conflicts = note.conflicts?.length ?? 0;
845
+ const later = note.later?.length ?? 0;
846
+ const more = [
847
+ conflicts ? TaLanguageUtil.say({
848
+ "zh-CN": `${conflicts} 个文件两边都改过`,
849
+ "zh-TW": `${conflicts} 個檔案兩邊都改過`,
850
+ "en-US": `${conflicts} file(s) changed on both sides`,
851
+ "ja-JP": `${conflicts} 個のファイルが両方で変更`
852
+ }) : "",
853
+ later ? TaLanguageUtil.say({
854
+ "zh-CN": `${later} 件事留给本机做`,
855
+ "zh-TW": `${later} 件事留給本機做`,
856
+ "en-US": `${later} step(s) left for this computer`,
857
+ "ja-JP": `${later} 件をこのパソコンで`
858
+ }) : ""
859
+ ].filter(Boolean);
860
+ return [head, ...more].join(" · ");
861
+ }
862
+ HandoffTexts.goOn = goOn;
863
+ function away(cloud) {
864
+ return TaLanguageUtil.say({
865
+ "zh-CN": `这个对话正在云端 ${cloud} 接着做:去那边看,或在对话列表的菜单里点“接回本机”再继续。`,
866
+ "zh-TW": `這個對話正在雲端 ${cloud} 接著做:去那邊看,或在對話列表的選單裡點「接回本機」再繼續。`,
867
+ "en-US": `This conversation goes on in the cloud workspace ${cloud}: follow it there, or bring it back from its menu in the list to go on here.`,
868
+ "ja-JP": `この会話はクラウド ${cloud} で続いています。そちらで見るか、一覧のメニューの「パソコンに戻す」で戻してから続けてください。`
869
+ });
870
+ }
871
+ HandoffTexts.away = away;
872
+ function stayed(reason) {
873
+ return TaLanguageUtil.say({
874
+ "zh-CN": `没能换到云端(${reason}),在本机接着做`,
875
+ "zh-TW": `沒能換到雲端(${reason}),在本機接著做`,
876
+ "en-US": `It did not move to the cloud (${reason}): going on here`,
877
+ "ja-JP": `クラウドへ移せませんでした(${reason})。このパソコンで続けます`
878
+ });
879
+ }
880
+ HandoffTexts.stayed = stayed;
881
+ function failed(reason) {
882
+ return `Moving this conversation to the cloud failed: ${reason}. It stays on this computer; tell the user in a line.`;
883
+ }
884
+ HandoffTexts.failed = failed;
885
+ })(HandoffTexts ||= {});
886
+
887
+ // web-src/handoff-service.ts
888
+ var MAX_BUNDLE_BYTES = 512 * 1024 * 1024;
889
+ var MAX_WARM_BYTES = 2 * 1024 * 1024 * 1024;
890
+ var WARM_REF = "refs/ta-handoff/warm";
891
+ var { q, ref, results } = HandoffScripts;
892
+
893
+ class CloudHandoffs {
894
+ host;
895
+ options;
896
+ local;
897
+ temp;
898
+ afterTurn = new Map;
899
+ busy = new Set;
900
+ warming = new Map;
901
+ book;
902
+ writes = Promise.resolve();
903
+ stop;
904
+ constructor(host, options = {}) {
905
+ this.host = host;
906
+ this.options = options;
907
+ this.local = options.local ?? new LocalSide;
908
+ this.temp = options.temp ?? tmpdir();
909
+ }
910
+ async begin() {
911
+ this.stop = this.host.onSessionEvent((event) => {
912
+ if (event.type === "turn_end" && event.sessionFile && this.afterTurn.has(event.sessionFile)) {
913
+ const file = event.sessionFile;
914
+ const cloud = this.afterTurn.get(file);
915
+ this.afterTurn.delete(file);
916
+ this.handOff(file, cloud, true).catch(async (error) => {
917
+ const open2 = (await this.host.listSessions().catch(() => [])).find((session) => session.sessionFile === file);
918
+ await this.host.prompt(open2?.sessionId ?? event.sessionId, {
919
+ message: TaMessageSource.notice(HandoffTexts.failed(error instanceof Error ? error.message : String(error)), NAME),
920
+ clientMessageId: `${NAME}:failed:${randomUUID2()}`
921
+ }).catch(() => {
922
+ return;
923
+ });
924
+ });
925
+ }
926
+ });
927
+ await this.save((book) => {
928
+ book.handoffs = book.handoffs.flatMap((handoff) => handoff.state === "moving" ? [] : handoff.state === "returning" ? [{ ...handoff, state: "cloud" }] : [handoff]);
929
+ });
930
+ }
931
+ dispose() {
932
+ this.stop?.();
933
+ }
934
+ async list() {
935
+ return { handoffs: (await this.read()).handoffs, workspaces: await this.host.cloud?.list() ?? [] };
936
+ }
937
+ async away(sessionFile) {
938
+ return (await this.read()).handoffs.find((handoff) => handoff.sessionFile === sessionFile);
939
+ }
940
+ async handOffAfterTurn(sessionFile, cloud) {
941
+ const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile);
942
+ if (open2?.isStreaming) {
943
+ await this.workspace(cloud);
944
+ this.afterTurn.set(sessionFile, cloud);
945
+ return;
946
+ }
947
+ return this.handOff(sessionFile, cloud, true);
948
+ }
949
+ async handOff(sessionFile, cloudName, goOn = false, auto) {
950
+ const { cloud, workspace } = await this.workspace(cloudName);
951
+ if (await this.away(sessionFile)) {
952
+ throw new Error("This conversation is in the cloud already.");
953
+ }
954
+ this.claim(sessionFile);
955
+ const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile);
956
+ let handoff;
957
+ try {
958
+ const cwd2 = open2?.cwd ?? await this.host.sessionCwd(sessionFile);
959
+ if (!cwd2 || !isAbsolute2(cwd2)) {
960
+ throw new Error("Only a conversation of a folder of this computer goes to the cloud.");
961
+ }
962
+ handoff = {
963
+ id: randomUUID2().slice(0, 8),
964
+ state: "moving",
965
+ cloud: workspace.name,
966
+ cloudUrl: workspace.url,
967
+ sessionFile,
968
+ cwd: cwd2,
969
+ root: await this.top(cwd2),
970
+ at: Date.now(),
971
+ ...open2?.isStreaming ? { wasRunning: true } : {},
972
+ ...auto ? { auto } : {}
973
+ };
974
+ await this.save((book) => {
975
+ book.handoffs.push(handoff);
976
+ });
977
+ } catch (error) {
978
+ this.busy.delete(sessionFile);
979
+ throw error;
980
+ }
981
+ const { id, root, cwd } = handoff;
982
+ const side = this.side(cloud, workspace.name);
983
+ const bundle = join(this.temp, `ta-handoff-${id}.bundle`);
984
+ const copy = join(this.temp, `ta-handoff-${id}.jsonl`);
985
+ const clone = `${workspace.name}
986
+ ${root}`;
987
+ let stopped = false;
988
+ try {
989
+ await this.warming.get(clone)?.catch(() => {
990
+ return;
991
+ });
992
+ if (open2) {
993
+ stopped = true;
994
+ if (open2.isStreaming) {
995
+ await this.host.abort(open2.sessionId);
996
+ }
997
+ await this.host.closeSession(open2.sessionId);
998
+ }
999
+ const book = await this.read();
1000
+ const snapshot = results(await this.local.run(HandoffScripts.snapshot(id, "local"), root));
1001
+ const last = book.clones[clone];
1002
+ const there = results(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1003
+ const made = results(await this.local.run(HandoffScripts.bundle(bundle, [ref(id, "local")], there.has === "yes" && last ? [last] : []), root));
1004
+ const size = Number(made.size);
1005
+ if (!(size <= MAX_BUNDLE_BYTES)) {
1006
+ throw new Error(`What ${root} would send is ${Math.round(size / 1048576)} MB, more than ${MAX_BUNDLE_BYTES / 1048576} MB at a time.`);
1007
+ }
1008
+ const arrived = posix.join(there.home, ".ta", "handoff", `${id}.bundle`);
1009
+ await side.run(`mkdir -p ${q(posix.dirname(arrived))}`);
1010
+ await HandoffTransfer.copy(this.local, bundle, size, side, arrived);
1011
+ const cloudRoot = there.root;
1012
+ const cloudCwd = posix.join(cloudRoot, relative(root, cwd).split(sep).join("/"));
1013
+ const received = results(await side.run(HandoffScripts.receive(arrived, ref(id, "local"), snapshot.head, snapshot.branch || undefined), cloudRoot));
1014
+ if (received.tree !== snapshot.tree) {
1015
+ throw new Error("The files in the cloud did not come out the same as here, so nothing moved.");
1016
+ }
1017
+ const lines = HandoffSessions.lines(await readFile(sessionFile, "utf8"));
1018
+ const cut = open2?.isStreaming === true;
1019
+ const details = { to: "cloud", cloud: workspace.name, ...auto ? { why: auto } : {} };
1020
+ const going = cut || goOn;
1021
+ const note = HandoffSessions.note(lines, HandoffTexts.toCloud({ cloud: workspace.name, root, cloudRoot, cut, goOn: going, why: auto }), details, !going);
1022
+ const body = new TextEncoder().encode(`${HandoffSessions.relocate(lines.join(`
1023
+ `), cloudCwd)}
1024
+ ${note}
1025
+ `);
1026
+ await writeFile2(copy, body);
1027
+ const cloudSessionFile = posix.join(there.agent, "sessions", HandoffSessions.directory(cloudCwd), basename(sessionFile));
1028
+ await side.run(`mkdir -p ${q(posix.dirname(cloudSessionFile))}`);
1029
+ await HandoffTransfer.copy(this.local, copy, body.length, side, cloudSessionFile);
1030
+ const server = cloud.server(workspace.name);
1031
+ const opened = await server.openSession({ cwd: cloudCwd, sessionFile: cloudSessionFile });
1032
+ if (open2?.model?.includes("/")) {
1033
+ const [provider, ...model] = open2.model.split("/");
1034
+ await server.setModel(opened.sessionId, provider, model.join("/")).catch(() => {
1035
+ return;
1036
+ });
1037
+ }
1038
+ if (going) {
1039
+ await server.prompt(opened.sessionId, {
1040
+ message: TaMessageSource.notice(HandoffTexts.goOn(details), NAME),
1041
+ clientMessageId: `${NAME}:${id}:cloud`
1042
+ });
1043
+ }
1044
+ const moved = {
1045
+ ...handoff,
1046
+ state: "cloud",
1047
+ cloudRoot,
1048
+ cloudCwd,
1049
+ cloudSessionFile,
1050
+ cloudSessionId: opened.sessionId,
1051
+ head: snapshot.head,
1052
+ tree: snapshot.tree,
1053
+ ...snapshot.branch ? { branch: snapshot.branch } : {},
1054
+ lines: lines.length
1055
+ };
1056
+ await this.save((next) => {
1057
+ next.handoffs = next.handoffs.map((other) => other.id === id ? moved : other);
1058
+ next.clones[clone] = snapshot.head;
1059
+ });
1060
+ return moved;
1061
+ } catch (error) {
1062
+ await this.save((book) => {
1063
+ book.handoffs = book.handoffs.filter((other) => other.id !== id);
1064
+ });
1065
+ await this.local.run(HandoffScripts.forget(id, ["local"]), root).catch(() => {
1066
+ return;
1067
+ });
1068
+ if (open2 && stopped) {
1069
+ await this.resumeHere(open2.isStreaming, cwd, sessionFile, error).catch(() => {
1070
+ return;
1071
+ });
1072
+ }
1073
+ throw error;
1074
+ } finally {
1075
+ this.busy.delete(sessionFile);
1076
+ await rm(bundle, { force: true });
1077
+ await rm(copy, { force: true });
1078
+ }
1079
+ }
1080
+ async resumeHere(running, cwd, sessionFile, error) {
1081
+ const opened = await this.host.openSession({ cwd, sessionFile });
1082
+ if (running) {
1083
+ await this.host.prompt(opened.sessionId, {
1084
+ message: TaMessageSource.notice(HandoffTexts.stayed(error instanceof Error ? error.message : String(error)), NAME),
1085
+ clientMessageId: `${NAME}:stayed:${randomUUID2()}`
1086
+ });
1087
+ }
1088
+ }
1089
+ async warm(cwd, cloudName) {
1090
+ const { cloud, workspace } = await this.workspace(cloudName);
1091
+ const root = await this.top(cwd);
1092
+ const key = `${workspace.name}
1093
+ ${root}`;
1094
+ let work = this.warming.get(key);
1095
+ if (!work) {
1096
+ work = this.carryAhead(cloud, workspace.name, root, key).finally(() => this.warming.delete(key));
1097
+ this.warming.set(key, work);
1098
+ }
1099
+ return work;
1100
+ }
1101
+ async carryAhead(cloud, name, root, key) {
1102
+ const book = await this.read();
1103
+ const last = book.clones[key];
1104
+ const head = results(await this.local.run(HandoffScripts.head(), root)).head;
1105
+ if (!head || head === last) {
1106
+ return;
1107
+ }
1108
+ const side = this.side(cloud, name);
1109
+ const there = results(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1110
+ const file = join(this.temp, `ta-handoff-warm-${randomUUID2().slice(0, 8)}.bundle`);
1111
+ try {
1112
+ const made = results(await this.local.run(HandoffScripts.bundle(file, ["HEAD"], there.has === "yes" && last ? [last] : []), root));
1113
+ const size = Number(made.size);
1114
+ if (!(size <= MAX_WARM_BYTES)) {
1115
+ throw new Error(`The history of ${root} is ${Math.round(size / 1048576)} MB, more than ${MAX_WARM_BYTES / 1048576} MB.`);
1116
+ }
1117
+ const arrived = posix.join(there.home, ".ta", "handoff", basename(file));
1118
+ await side.run(`mkdir -p ${q(posix.dirname(arrived))}`);
1119
+ await HandoffTransfer.copy(this.local, file, size, side, arrived);
1120
+ await side.run(HandoffScripts.fetch(arrived, "HEAD", WARM_REF), there.root);
1121
+ await this.save((next) => {
1122
+ next.clones[key] = head;
1123
+ });
1124
+ } finally {
1125
+ await rm(file, { force: true });
1126
+ }
1127
+ }
1128
+ async idleThere(id) {
1129
+ const handoff = (await this.read()).handoffs.find((other) => other.id === id);
1130
+ if (handoff?.state !== "cloud") {
1131
+ return false;
1132
+ }
1133
+ const { cloud } = await this.workspace(handoff.cloud);
1134
+ const there = (await cloud.server(handoff.cloud).listSessions()).find((session) => session.sessionId === handoff.cloudSessionId || session.sessionFile === handoff.cloudSessionFile);
1135
+ return !there?.isStreaming;
1136
+ }
1137
+ async takeBack(id) {
1138
+ const handoff = (await this.read()).handoffs.find((other) => other.id === id);
1139
+ if (handoff?.state !== "cloud" || !handoff.cloudRoot || !handoff.cloudSessionFile || !handoff.head || !handoff.tree) {
1140
+ throw new Error(handoff ? "This conversation is on its way: try again in a moment." : "This conversation is not in the cloud.");
1141
+ }
1142
+ const { cloud } = await this.workspace(handoff.cloud);
1143
+ this.claim(handoff.sessionFile);
1144
+ const side = this.side(cloud, handoff.cloud);
1145
+ const { root, cloudRoot, cloudSessionFile, head, tree } = handoff;
1146
+ const bundle = join(this.temp, `ta-handoff-${id}-back.bundle`);
1147
+ try {
1148
+ await this.save((book) => {
1149
+ book.handoffs = book.handoffs.map((other) => other.id === id ? { ...other, state: "returning" } : other);
1150
+ });
1151
+ const server = cloud.server(handoff.cloud);
1152
+ const there = (await server.listSessions()).find((session) => session.sessionId === handoff.cloudSessionId || session.sessionFile === cloudSessionFile);
1153
+ const cut = there?.isStreaming === true;
1154
+ const cloudFile = there?.sessionFile ?? cloudSessionFile;
1155
+ if (there) {
1156
+ if (cut) {
1157
+ await server.abort(there.sessionId);
1158
+ }
1159
+ await server.closeSession(there.sessionId);
1160
+ }
1161
+ const cloudSnap = results(await side.run(HandoffScripts.snapshot(id, "cloud"), cloudRoot));
1162
+ const result = { sessionFile: handoff.sessionFile, files: "same", later: [] };
1163
+ if (cloudSnap.tree !== tree || cloudSnap.head !== head) {
1164
+ const sent = posix.join(posix.dirname(cloudSessionFile), `.ta-handoff-${id}.bundle`);
1165
+ const made = results(await side.run(HandoffScripts.bundle(sent, [ref(id, "cloud")], [ref(id, "local")]), cloudRoot));
1166
+ await HandoffTransfer.copy(side, sent, Number(made.size), this.local, bundle);
1167
+ await side.run(`rm -f ${q(sent)}`);
1168
+ await this.local.run(HandoffScripts.fetch(bundle, ref(id, "cloud")), root);
1169
+ const here = results(await this.local.run(HandoffScripts.snapshot(id, "here"), root));
1170
+ const moved = cloudSnap.head !== head;
1171
+ const headHere = here.head === head;
1172
+ let target = cloudSnap.tree;
1173
+ if (here.tree !== tree) {
1174
+ const merged = results(await this.local.run(HandoffScripts.merge(ref(id, "local"), ref(id, "here"), ref(id, "cloud")), root));
1175
+ if (merged.conflicts) {
1176
+ result.files = "conflict";
1177
+ result.conflicts = merged.conflicts.split("\t").filter(Boolean);
1178
+ result.ref = ref(id, "cloud");
1179
+ }
1180
+ target = merged.tree;
1181
+ }
1182
+ if (result.files !== "conflict") {
1183
+ const landed = results(await this.local.run(HandoffScripts.land(here.tree, target, moved && headHere ? cloudSnap.head : undefined), root));
1184
+ if (landed.tree !== target) {
1185
+ throw new Error("The files here did not come out as the cloud left them.");
1186
+ }
1187
+ result.files = here.tree === tree ? "taken" : "merged";
1188
+ if (moved && headHere) {
1189
+ result.commits = Number(results(await this.local.run(HandoffScripts.count(head, cloudSnap.head), root)).count) || 0;
1190
+ } else if (moved) {
1191
+ result.ref = ref(id, "cloud");
1192
+ }
1193
+ }
1194
+ }
1195
+ const brought = await this.bringConversation(handoff, side, cloudFile, result, cut);
1196
+ result.sessionFile = brought.sessionFile;
1197
+ await this.save((book) => {
1198
+ book.handoffs = book.handoffs.filter((other) => other.id !== id);
1199
+ book.clones[`${handoff.cloud}
1200
+ ${root}`] = cloudSnap.head;
1201
+ });
1202
+ if (brought.wasOpen || brought.goOn) {
1203
+ const opened = await this.host.openSession({ cwd: handoff.cwd, sessionFile: brought.sessionFile });
1204
+ if (brought.goOn) {
1205
+ await this.host.prompt(opened.sessionId, {
1206
+ message: TaMessageSource.notice(HandoffTexts.goOn(brought.note), NAME),
1207
+ clientMessageId: `${NAME}:${id}:back`
1208
+ });
1209
+ }
1210
+ }
1211
+ await side.run(HandoffScripts.forget(id, ["local", "cloud"]), cloudRoot).catch(() => {
1212
+ return;
1213
+ });
1214
+ await this.local.run(HandoffScripts.forget(id, result.ref ? ["local", "here"] : ["local", "here", "cloud"]), root).catch(() => {
1215
+ return;
1216
+ });
1217
+ return result;
1218
+ } catch (error) {
1219
+ await this.save((book) => {
1220
+ book.handoffs = book.handoffs.map((other) => other.id === id ? { ...other, state: "cloud" } : other);
1221
+ });
1222
+ throw error;
1223
+ } finally {
1224
+ this.busy.delete(handoff.sessionFile);
1225
+ await rm(bundle, { force: true });
1226
+ }
1227
+ }
1228
+ async bringConversation(handoff, side, cloudFile, result, cut) {
1229
+ const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === handoff.sessionFile);
1230
+ if (open2) {
1231
+ await this.host.closeSession(open2.sessionId);
1232
+ }
1233
+ const read = async (file) => {
1234
+ const size = Number(results(await side.run(HandoffScripts.size(file))).size);
1235
+ const copy = join(this.temp, `ta-handoff-${handoff.id}-${basename(file)}`);
1236
+ await HandoffTransfer.copy(side, file, size, this.local, copy);
1237
+ try {
1238
+ return HandoffSessions.lines(await readFile(copy, "utf8"));
1239
+ } finally {
1240
+ await rm(copy, { force: true });
1241
+ }
1242
+ };
1243
+ const said = (await read(handoff.cloudSessionFile)).slice(handoff.lines ?? 0);
1244
+ const other = cloudFile === handoff.cloudSessionFile ? undefined : HandoffSessions.lines(HandoffSessions.relocate((await read(cloudFile)).join(`
1245
+ `), handoff.cwd));
1246
+ result.later = HandoffSessions.later([...said, ...other ?? []]);
1247
+ const before = other ?? [...HandoffSessions.lines(await readFile(handoff.sessionFile, "utf8")), ...said];
1248
+ const goOn = cut || result.later.length > 0 || result.files === "conflict";
1249
+ const details = {
1250
+ to: "back",
1251
+ cloud: handoff.cloud,
1252
+ files: result.files,
1253
+ ...result.conflicts ? { conflicts: result.conflicts } : {},
1254
+ later: result.later
1255
+ };
1256
+ const note = HandoffSessions.note(before, HandoffTexts.back({
1257
+ cloud: handoff.cloud,
1258
+ files: result.files,
1259
+ conflicts: result.conflicts ?? [],
1260
+ ref: result.ref,
1261
+ commits: result.commits ?? 0,
1262
+ later: result.later,
1263
+ goOn
1264
+ }), details, !goOn);
1265
+ if (said.length) {
1266
+ await appendFile2(handoff.sessionFile, `${said.join(`
1267
+ `)}
1268
+ `);
1269
+ }
1270
+ let sessionFile = handoff.sessionFile;
1271
+ if (other === undefined) {
1272
+ await appendFile2(sessionFile, `${note}
1273
+ `);
1274
+ } else {
1275
+ sessionFile = join(dirname(handoff.sessionFile), basename(cloudFile));
1276
+ await writeFile2(sessionFile, `${other.join(`
1277
+ `)}
1278
+ ${note}
1279
+ `);
1280
+ }
1281
+ return { sessionFile, wasOpen: open2 !== undefined, goOn, note: details };
1282
+ }
1283
+ async workspace(name) {
1284
+ const cloud = this.host.cloud;
1285
+ if (!cloud) {
1286
+ throw new Error("This Ta is too old to carry work to the cloud: update it.");
1287
+ }
1288
+ const workspaces = await cloud.list();
1289
+ const workspace = name ? workspaces.find((other) => other.name === name) : workspaces[0];
1290
+ if (!workspace) {
1291
+ throw new Error(name ? `There is no cloud workspace ${name}.` : "Add a cloud workspace first: Settings, Remote hosts, Add a cloud workspace.");
1292
+ }
1293
+ return { cloud, workspace };
1294
+ }
1295
+ side(cloud, name) {
1296
+ return this.options.side?.(cloud, name) ?? new CloudSide(cloud, name);
1297
+ }
1298
+ claim(sessionFile) {
1299
+ if (this.busy.has(sessionFile)) {
1300
+ throw new Error("This conversation is on its way: try again in a moment.");
1301
+ }
1302
+ this.busy.add(sessionFile);
1303
+ }
1304
+ async top(cwd) {
1305
+ try {
1306
+ return (await this.local.run(HandoffScripts.top(), cwd)).trim().split(`
1307
+ `).pop();
1308
+ } catch (error) {
1309
+ throw new Error(`${cwd} is not in a git repository with a commit: only those go to the cloud for now (${error.message}).`);
1310
+ }
1311
+ }
1312
+ async identity(root) {
1313
+ const value = async (args) => (await this.local.run(`git ${args} 2>/dev/null || true`, root)).trim() || undefined;
1314
+ return { name: await value("config user.name"), email: await value("config user.email"), origin: await value("remote get-url origin") };
1315
+ }
1316
+ read() {
1317
+ this.book ??= this.host.getExtensionData(NAME, BOOK_KEY).then((value) => {
1318
+ const book = value ?? {};
1319
+ return {
1320
+ machine: typeof book.machine === "string" ? book.machine : randomUUID2(),
1321
+ handoffs: Array.isArray(book.handoffs) ? book.handoffs : [],
1322
+ clones: book.clones && typeof book.clones === "object" ? book.clones : {}
1323
+ };
1324
+ });
1325
+ return this.book;
1326
+ }
1327
+ save(change) {
1328
+ const write = this.writes.then(async () => {
1329
+ const book = await this.read();
1330
+ change(book);
1331
+ await this.host.setExtensionData(NAME, BOOK_KEY, book);
1332
+ });
1333
+ this.writes = write.catch(() => {
1334
+ return;
1335
+ });
1336
+ return write;
1337
+ }
1338
+ }
1339
+
1340
+ // web-src/host.ts
1341
+ async function activate(host) {
1342
+ const handoffs = new CloudHandoffs(host);
1343
+ await handoffs.begin();
1344
+ const auto = new HandoffAuto(host, handoffs);
1345
+ auto.begin();
1346
+ const service = {
1347
+ list: () => handoffs.list(),
1348
+ handOff: (sessionFile, cloud) => handoffs.handOff(sessionFile, cloud),
1349
+ handOffAfterTurn: (sessionFile, cloud) => handoffs.handOffAfterTurn(sessionFile, cloud),
1350
+ takeBack: (id) => handoffs.takeBack(id),
1351
+ away: (sessionFile) => handoffs.away(sessionFile),
1352
+ power: () => auto.power(),
1353
+ dispose: () => {
1354
+ auto.dispose();
1355
+ handoffs.dispose();
1356
+ }
1357
+ };
1358
+ return service;
1359
+ }
1360
+ export {
1361
+ activate as default
1362
+ };