@celljs/ta-cloud-handoff 4.38.0 → 4.40.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 CHANGED
@@ -4,6 +4,7 @@ import { isAbsolute } from "node:path";
4
4
  // web-src/handoff-protocol.ts
5
5
  var NAME = "@celljs/ta-cloud-handoff";
6
6
  var BOOK_KEY = "book";
7
+ var COPIES_KEY = "copies";
7
8
  var SETTINGS_KEY = "settings";
8
9
  var HandoffSettingsUtil;
9
10
  ((HandoffSettingsUtil) => {
@@ -112,7 +113,7 @@ class HandoffAuto {
112
113
  return;
113
114
  }
114
115
  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
+ const running = (await this.host.listSessions()).filter((session) => session.isStreaming && session.sessionFile && !session.cloud && !session.group && isAbsolute(session.cwd) && now - (this.failed.get(session.sessionFile) ?? -Infinity) >= (this.options.retryMs ?? RETRY_MS));
116
117
  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
  }
118
119
  scheduleBack(ms) {
@@ -171,10 +172,10 @@ class HandoffAuto {
171
172
  }
172
173
 
173
174
  // web-src/handoff-service.ts
174
- import { randomUUID as randomUUID2 } from "node:crypto";
175
- import { appendFile as appendFile2, readFile as readFile2, rm, writeFile as writeFile2 } from "node:fs/promises";
176
- import { tmpdir } from "node:os";
177
- import { basename, dirname, isAbsolute as isAbsolute2, join as join2, posix, relative, sep } from "node:path";
175
+ import { randomUUID as randomUUID3 } from "node:crypto";
176
+ import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
177
+ import { hostname, tmpdir } from "node:os";
178
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join3, posix, relative, sep } from "node:path";
178
179
 
179
180
  // ../ta-protocol/esm/common/message-protocol.js
180
181
  var TaMessageContext;
@@ -488,265 +489,519 @@ var TaSecretRef;
488
489
  TaSecretRef2.plain = plain;
489
490
  })(TaSecretRef || (TaSecretRef = {}));
490
491
 
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}`;
492
+ // web-src/handoff-book.ts
493
+ import { randomUUID } from "node:crypto";
494
+ class HandoffBookStore {
495
+ host;
496
+ book;
497
+ writes = Promise.resolve();
498
+ constructor(host) {
499
+ this.host = host;
515
500
  }
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
- `);
501
+ read() {
502
+ this.book ??= this.host.getExtensionData(NAME, BOOK_KEY).then((value) => {
503
+ const book = value ?? {};
504
+ return {
505
+ machine: typeof book.machine === "string" ? book.machine : randomUUID(),
506
+ handoffs: Array.isArray(book.handoffs) ? book.handoffs : [],
507
+ clones: book.clones && typeof book.clones === "object" ? book.clones : {}
508
+ };
509
+ });
510
+ return this.book;
528
511
  }
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");
512
+ save(change) {
513
+ const write = this.writes.then(async () => {
514
+ const book = await this.read();
515
+ change(book);
516
+ await this.host.setExtensionData(NAME, BOOK_KEY, book);
517
+ });
518
+ this.writes = write.catch(() => {
519
+ return;
520
+ });
521
+ return write;
531
522
  }
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"');
523
+ }
524
+
525
+ // web-src/handoff-copies.ts
526
+ var MAX_COPIES = 50;
527
+
528
+ class HandoffCopiesBook {
529
+ host;
530
+ constructor(host) {
531
+ this.host = host;
535
532
  }
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 ' ')"`);
533
+ async copy(copy) {
534
+ if (!copy || typeof copy.sessionFile !== "string" || typeof copy.computer !== "string" || typeof copy.here !== "string") {
535
+ throw new Error("Pass the session file here, the computer and its session file there.");
536
+ }
537
+ const kept = await this.list();
538
+ const next = {
539
+ copies: [
540
+ ...kept.copies.filter((other) => other.sessionFile !== copy.sessionFile),
541
+ {
542
+ sessionFile: copy.sessionFile,
543
+ computer: copy.computer,
544
+ here: copy.here,
545
+ at: Number(copy.at) || Date.now(),
546
+ ...copy.back ? { back: Number(copy.back) } : {}
547
+ }
548
+ ].slice(-MAX_COPIES)
549
+ };
550
+ await this.host.setExtensionData(NAME, COPIES_KEY, next);
540
551
  }
541
- HandoffScripts.bundle = bundle;
542
- function size(file) {
543
- return program(`echo ${HandoffScripts.MARK}`, `echo "size=$(wc -c < ${q(file)} | tr -d ' ')"`);
552
+ async wentBack(sessionFile) {
553
+ return (await this.list()).copies.find((copy) => copy.sessionFile === sessionFile && copy.back);
544
554
  }
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)}`);
555
+ async list() {
556
+ const value = await this.host.getExtensionData(NAME, COPIES_KEY);
557
+ return { copies: Array.isArray(value?.copies) ? value.copies : [] };
548
558
  }
549
- HandoffScripts.fetch = fetch;
550
- function head() {
551
- return program(`echo ${HandoffScripts.MARK}`, 'echo "head=$(git rev-parse --verify "HEAD^{commit}")"');
559
+ }
560
+
561
+ // ../ta-protocol/esm/common/language.js
562
+ var TaLanguageUtil;
563
+ (function(TaLanguageUtil2) {
564
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
565
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
566
+ function of(tag) {
567
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
568
+ if (/^zh(\b|-)/.test(said)) {
569
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
570
+ }
571
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
552
572
  }
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}"');
573
+ TaLanguageUtil2.of = of;
574
+ function server(env = typeof process === "undefined" ? {} : process.env) {
575
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
556
576
  }
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)"');
577
+ TaLanguageUtil2.server = server;
578
+ function pick(language, words) {
579
+ return words[of(language)];
560
580
  }
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)"');
581
+ TaLanguageUtil2.pick = pick;
582
+ function say(words) {
583
+ return words[server()];
564
584
  }
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
- " " ")"`);
585
+ TaLanguageUtil2.say = say;
586
+ function chinese(language) {
587
+ return of(language).startsWith("zh");
569
588
  }
570
- HandoffScripts.merge = merge;
571
- function count(from, to) {
572
- return program(`echo ${HandoffScripts.MARK}`, `echo "count=$(git rev-list --count ${q(`${from}..${to}`)})"`);
589
+ TaLanguageUtil2.chinese = chinese;
590
+ function cjk(language) {
591
+ return of(language) !== "en-US";
573
592
  }
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`));
593
+ TaLanguageUtil2.cjk = cjk;
594
+ function list(language, items) {
595
+ return items.join(cjk(language) ? "、" : ", ");
577
596
  }
578
- HandoffScripts.forget = forget;
579
- })(HandoffScripts ||= {});
597
+ TaLanguageUtil2.list = list;
598
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
580
599
 
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(`
600
+ // web-src/server-texts.ts
601
+ var WHY = {
602
+ asked: "as the user asked",
603
+ sleep: "by itself as the user's computer was about to sleep (its lid closed, most likely)",
604
+ battery: "by itself as the battery of the user's computer ran low"
605
+ };
606
+ function short(model) {
607
+ return model ? model.slice(model.indexOf("/") + 1) : "";
608
+ }
609
+ var HandoffTexts;
610
+ ((HandoffTexts) => {
611
+ function toCloud(options) {
612
+ return [
613
+ `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.`,
614
+ 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}.`,
615
+ "- What git ignores (installed dependencies, builds, .env files) did not come along: install or build again, as the project does, when you need them.",
616
+ 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." : "",
617
+ `- 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.`,
618
+ options.model ? `- The model of this conversation, ${options.model}, has no key in the cloud: another model the cloud can use goes on with it. Work as before; say so if the work needs that model.` : "",
619
+ "- Push, publish or deploy only if the user asked for it in this conversation.",
620
+ options.goOn ? "- Go on with the work where it stopped." : ""
621
+ ].filter(Boolean).join(`
604
622
  `);
605
623
  }
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
624
+ HandoffTexts.toCloud = toCloud;
625
+ function back(options) {
626
+ const files = {
627
+ same: "The files are as they were: nothing changed in the cloud.",
628
+ taken: "The files here are now as the cloud left them.",
629
+ merged: "The files here are the cloud's work merged with what changed here meanwhile.",
630
+ 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.`
637
631
  };
638
- return JSON.stringify(entry);
632
+ return [
633
+ `This conversation came back from the cloud workspace ${options.cloud} to the user's computer.`,
634
+ `- ${files[options.files] ?? ""}`,
635
+ options.commits ? `- ${options.commits} commit(s) made in the cloud are on the branch here.` : "",
636
+ options.ref && options.files !== "conflict" ? `- HEAD moved here meanwhile: the cloud's commits are kept at ${options.ref}.` : "",
637
+ options.later.length ? `- Left for this computer: ${options.later.map((item) => `
638
+ - ${item}`).join("")}` : "",
639
+ options.goOn ? "- Go on here: do what was left for this computer, and look at the files if they need it." : ""
640
+ ].filter(Boolean).join(`
641
+ `);
639
642
  }
640
- HandoffSessions.note = note;
641
- })(HandoffSessions ||= {});
642
-
643
- // web-src/handoff-setup.ts
644
- import { readFile } from "node:fs/promises";
645
- import { join } from "node:path";
646
- var LOCKS = [
647
- { files: ["bun.lock", "bun.lockb"], step: { tool: "bun", command: "bun install --frozen-lockfile" } },
648
- { files: ["pnpm-lock.yaml"], step: { tool: "pnpm", command: "pnpm install --frozen-lockfile" } },
649
- { files: ["yarn.lock"], step: { tool: "yarn", command: "yarn install --frozen-lockfile" } },
650
- { files: ["package-lock.json"], step: { tool: "npm", command: "npm ci" } },
651
- { files: ["package.json"], step: { tool: "npm", command: "npm install" } }
652
- ];
653
- var OTHERS = [
654
- { file: "uv.lock", step: { tool: "uv", command: "uv sync" } },
655
- { file: "poetry.lock", step: { tool: "poetry", command: "poetry install" } },
656
- { file: "requirements.txt", step: { tool: "python3", command: "python3 -m venv .venv && .venv/bin/pip install -r requirements.txt" } },
657
- { file: "Cargo.lock", step: { tool: "cargo", command: "cargo fetch" } },
658
- { file: "go.sum", step: { tool: "go", command: "go mod download" } },
659
- { file: "Gemfile.lock", step: { tool: "bundle", command: "bundle install" } }
660
- ];
661
- var DEVCONTAINERS = [".devcontainer/devcontainer.json", ".devcontainer.json"];
662
- var DEVCONTAINER_COMMANDS = ["onCreateCommand", "updateContentCommand", "postCreateCommand"];
663
- function q(value) {
664
- return `'${value.replace(/'/g, `'\\''`)}'`;
665
- }
666
- var HandoffSetup;
667
- ((HandoffSetup) => {
668
- function steps(files, devcontainer) {
669
- const own = devcontainerSteps(devcontainer);
670
- if (own.length) {
671
- return own;
672
- }
673
- const steps2 = [];
674
- const lock = LOCKS.find((one) => one.files.some((file) => files.has(file)));
675
- if (lock) {
676
- steps2.push(lock.step);
643
+ HandoffTexts.back = back;
644
+ function goOn(note) {
645
+ const cloud = note.cloud;
646
+ const head = note.to === "cloud" && note.why === "sleep" ? TaLanguageUtil.say({
647
+ "zh-CN": `电脑要睡眠了,换到云端接着做 · ${cloud}`,
648
+ "zh-TW": `電腦要睡眠了,換到雲端接著做 · ${cloud}`,
649
+ "en-US": `The computer is going to sleep: going on in the cloud · ${cloud}`,
650
+ "ja-JP": `パソコンがスリープするのでクラウドで続ける · ${cloud}`
651
+ }) : note.to === "cloud" && note.why === "battery" ? TaLanguageUtil.say({
652
+ "zh-CN": `电量低,换到云端接着做 · ${cloud}`,
653
+ "zh-TW": `電量低,換到雲端接著做 · ${cloud}`,
654
+ "en-US": `Battery low: going on in the cloud · ${cloud}`,
655
+ "ja-JP": `電池残量が少ないのでクラウドで続ける · ${cloud}`
656
+ }) : note.to === "cloud" ? TaLanguageUtil.say({
657
+ "zh-CN": `换到云端接着做 · ${cloud}`,
658
+ "zh-TW": `換到雲端接著做 · ${cloud}`,
659
+ "en-US": `Going on in the cloud · ${cloud}`,
660
+ "ja-JP": `クラウドで続ける · ${cloud}`
661
+ }) : TaLanguageUtil.say({
662
+ "zh-CN": `从云端 ${cloud} 接回本机`,
663
+ "zh-TW": `從雲端 ${cloud} 接回本機`,
664
+ "en-US": `Back on this computer from ${cloud}`,
665
+ "ja-JP": `クラウド ${cloud} からこのパソコンに戻しました`
666
+ });
667
+ const conflicts = note.conflicts?.length ?? 0;
668
+ const later = note.later?.length ?? 0;
669
+ const more = [
670
+ conflicts ? TaLanguageUtil.say({
671
+ "zh-CN": `${conflicts} 个文件两边都改过`,
672
+ "zh-TW": `${conflicts} 個檔案兩邊都改過`,
673
+ "en-US": `${conflicts} file(s) changed on both sides`,
674
+ "ja-JP": `${conflicts} 個のファイルが両方で変更`
675
+ }) : "",
676
+ later ? TaLanguageUtil.say({
677
+ "zh-CN": `${later} 件事留给本机做`,
678
+ "zh-TW": `${later} 件事留給本機做`,
679
+ "en-US": `${later} step(s) left for this computer`,
680
+ "ja-JP": `${later} 件をこのパソコンで`
681
+ }) : "",
682
+ note.model?.to ? TaLanguageUtil.say({
683
+ "zh-CN": `云端用不了 ${short(note.model.from)},换成 ${short(note.model.to)}`,
684
+ "zh-TW": `雲端用不了 ${short(note.model.from)},換成 ${short(note.model.to)}`,
685
+ "en-US": `no key of ${short(note.model.from)} there: going on with ${short(note.model.to)}`,
686
+ "ja-JP": `クラウドでは ${short(note.model.from)} が使えないので ${short(note.model.to)} で続ける`
687
+ }) : ""
688
+ ].filter(Boolean);
689
+ return [head, ...more].join(" · ");
690
+ }
691
+ HandoffTexts.goOn = goOn;
692
+ function noModel(cloud) {
693
+ return TaLanguageUtil.say({
694
+ "zh-CN": `云端 ${cloud} 没有能用的模型:在保险箱里打开模型密钥的“可在我的云端工作区用”,或在那台机器上登录`,
695
+ "zh-TW": `雲端 ${cloud} 沒有能用的模型:在保險箱裡打開模型金鑰的「可在我的雲端工作區用」,或在那台機器上登入`,
696
+ "en-US": `The cloud workspace ${cloud} has no model it can use: let a key of a model go there in the vault, or sign in there`,
697
+ "ja-JP": `クラウド ${cloud} で使えるモデルがありません。金庫でモデルのキーを「クラウドのワークスペースでも使う」にするか、そのマシンでログインしてください`
698
+ });
699
+ }
700
+ HandoffTexts.noModel = noModel;
701
+ function away(cloud) {
702
+ return TaLanguageUtil.say({
703
+ "zh-CN": `这个对话正在云端 ${cloud} 接着做:去那边看,或在对话列表的菜单里点“接回本机”再继续。`,
704
+ "zh-TW": `這個對話正在雲端 ${cloud} 接著做:去那邊看,或在對話列表的選單裡點「接回本機」再繼續。`,
705
+ "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.`,
706
+ "ja-JP": `この会話はクラウド ${cloud} で続いています。そちらで見るか、一覧のメニューの「パソコンに戻す」で戻してから続けてください。`
707
+ });
708
+ }
709
+ HandoffTexts.away = away;
710
+ function locked(error) {
711
+ return /index\.lock|Another git process seems to be running/.test(error instanceof Error ? error.message : String(error));
712
+ }
713
+ HandoffTexts.locked = locked;
714
+ function reason(error) {
715
+ if (locked(error)) {
716
+ return TaLanguageUtil.say({
717
+ "zh-CN": "云端那份代码正被另一个 git 命令占用,过一会儿再试",
718
+ "zh-TW": "雲端那份程式碼正被另一個 git 指令佔用,過一會兒再試",
719
+ "en-US": "another git command held the copy in the cloud: try again in a moment",
720
+ "ja-JP": "クラウドのコピーを別の git コマンドが使用中です。少し待ってからもう一度お試しください"
721
+ });
677
722
  }
678
- for (const other of OTHERS) {
679
- if (files.has(other.file)) {
680
- steps2.push(other.step);
723
+ return error instanceof Error ? error.message : String(error);
724
+ }
725
+ HandoffTexts.reason = reason;
726
+ function sharedHead(cloud) {
727
+ return TaLanguageUtil.say({
728
+ "zh-CN": `这个仓库已有对话在云端 ${cloud} 接着做,而这里之后有了不同的提交:先把那个对话接回本机,再换过去`,
729
+ "zh-TW": `這個倉庫已有對話在雲端 ${cloud} 接著做,而這裡之後有了不同的提交:先把那個對話接回本機,再換過去`,
730
+ "en-US": `Another conversation of this repository goes on in ${cloud}, and the commits here are not those there: bring it back first, then move this one`,
731
+ "ja-JP": `このリポジトリの別の会話がクラウド ${cloud} で続いていて、こちらのコミットが違います。先にそちらを戻してから移してください`
732
+ });
733
+ }
734
+ HandoffTexts.sharedHead = sharedHead;
735
+ function sharedConflict(cloud, paths) {
736
+ const list = paths.slice(0, 3).join(", ") + (paths.length > 3 ? " …" : "");
737
+ return TaLanguageUtil.say({
738
+ "zh-CN": `这个仓库已有对话在云端 ${cloud} 改了同样的文件(${list}):先把那个对话接回本机,再换过去`,
739
+ "zh-TW": `這個倉庫已有對話在雲端 ${cloud} 改了同樣的檔案(${list}):先把那個對話接回本機,再換過去`,
740
+ "en-US": `Another conversation of this repository in ${cloud} changed the same files (${list}): bring it back first, then move this one`,
741
+ "ja-JP": `このリポジトリの別の会話がクラウド ${cloud} で同じファイル(${list})を変更しました。先にそちらを戻してから移してください`
742
+ });
743
+ }
744
+ HandoffTexts.sharedConflict = sharedConflict;
745
+ function wentBack(computer) {
746
+ return TaLanguageUtil.say({
747
+ "zh-CN": `这个对话已接回电脑 ${computer},在那边接着做:在这里说的话不会带回去。`,
748
+ "zh-TW": `這個對話已接回電腦 ${computer},在那邊接著做:在這裡說的話不會帶回去。`,
749
+ "en-US": `This conversation went back to the computer ${computer} and goes on there: what is said here would not reach it.`,
750
+ "ja-JP": `この会話はパソコン ${computer} に戻り、そちらで続いています。ここで書いた内容は戻りません。`
751
+ });
752
+ }
753
+ HandoffTexts.wentBack = wentBack;
754
+ function stayed(reason2) {
755
+ return TaLanguageUtil.say({
756
+ "zh-CN": `没能换到云端(${reason2}),在本机接着做`,
757
+ "zh-TW": `沒能換到雲端(${reason2}),在本機接著做`,
758
+ "en-US": `It did not move to the cloud (${reason2}): going on here`,
759
+ "ja-JP": `クラウドへ移せませんでした(${reason2})。このパソコンで続けます`
760
+ });
761
+ }
762
+ HandoffTexts.stayed = stayed;
763
+ function failed(reason2) {
764
+ return `Moving this conversation to the cloud failed: ${reason2}. It stays on this computer; tell the user in a line.`;
765
+ }
766
+ HandoffTexts.failed = failed;
767
+ })(HandoffTexts ||= {});
768
+
769
+ // web-src/handoff-lanes.ts
770
+ var LOCKED_TRIES = 4;
771
+ var LOCKED_WAIT_MS = 1500;
772
+
773
+ class HandoffLanes {
774
+ lanes = new Map;
775
+ run(key, work) {
776
+ const run = (this.lanes.get(key) ?? Promise.resolve()).catch(() => {
777
+ return;
778
+ }).then(work);
779
+ const settled = run.catch(() => {
780
+ return;
781
+ });
782
+ this.lanes.set(key, settled);
783
+ settled.then(() => this.lanes.get(key) === settled && this.lanes.delete(key));
784
+ return run;
785
+ }
786
+ static async untangled(run) {
787
+ for (let attempt = 1;; attempt++) {
788
+ try {
789
+ return await run();
790
+ } catch (error) {
791
+ if (attempt >= LOCKED_TRIES || !HandoffTexts.locked(error)) {
792
+ throw error;
793
+ }
794
+ await new Promise((resolve) => setTimeout(resolve, LOCKED_WAIT_MS * attempt));
681
795
  }
682
796
  }
683
- return steps2;
684
797
  }
685
- HandoffSetup.steps = steps;
686
- function devcontainerSteps(config) {
687
- if (!config || typeof config !== "object") {
688
- return [];
798
+ }
799
+
800
+ // web-src/handoff-models.ts
801
+ var HandoffModels;
802
+ ((HandoffModels) => {
803
+ async function there(cloud, name, model) {
804
+ const providers = await cloud.providers?.(name).catch(() => {
805
+ return;
806
+ });
807
+ if (!providers) {
808
+ return;
689
809
  }
690
- const steps2 = [];
691
- const add = (value) => {
692
- if (typeof value === "string" && value.trim()) {
693
- steps2.push({ tool: "sh", command: value.trim() });
694
- } else if (Array.isArray(value) && value.length && value.every((part) => typeof part === "string")) {
695
- steps2.push({ tool: value[0], command: value.map(q).join(" ") });
696
- } else if (value && typeof value === "object" && !Array.isArray(value)) {
697
- Object.values(value).forEach(add);
698
- }
699
- };
700
- for (const key of DEVCONTAINER_COMMANDS) {
701
- add(config[key]);
810
+ if (!providers.length) {
811
+ throw new Error(HandoffTexts.noModel(name));
702
812
  }
703
- return steps2;
813
+ const provider = model?.includes("/") ? model.split("/")[0] : undefined;
814
+ return model && provider && !providers.includes(provider) ? model : undefined;
704
815
  }
705
- HandoffSetup.devcontainerSteps = devcontainerSteps;
706
- function jsonc(text) {
707
- const stripped = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, string) => string ?? "").replace(/,(\s*[}\]])/g, "$1");
708
- try {
709
- return JSON.parse(stripped);
710
- } catch {
816
+ HandoffModels.there = there;
817
+ async function use(server, sessionId, model) {
818
+ if (model?.includes("/")) {
819
+ const [provider, ...id] = model.split("/");
820
+ if (await server.setModel(sessionId, provider, id.join("/")).then(() => true, () => false)) {
821
+ return;
822
+ }
823
+ }
824
+ const state = await server.getState(sessionId).catch(() => {
825
+ return;
826
+ });
827
+ const available = (await server.getAvailableModels(sessionId).catch(() => {
828
+ return;
829
+ }))?.models ?? [];
830
+ const now = state?.model && available.find((one) => one.provider === state.model?.provider && one.id === state.model?.id);
831
+ const chosen = now ?? available[0];
832
+ if (!chosen) {
711
833
  return;
712
834
  }
835
+ if (!now) {
836
+ await server.setModel(sessionId, chosen.provider, chosen.id).catch(() => {
837
+ return;
838
+ });
839
+ }
840
+ return `${chosen.provider}/${chosen.id}`;
841
+ }
842
+ HandoffModels.use = use;
843
+ })(HandoffModels ||= {});
844
+
845
+ // web-src/handoff-return.ts
846
+ import { appendFile as appendFile2, readFile, rm, writeFile as writeFile2 } from "node:fs/promises";
847
+ import { basename, dirname, join } from "node:path";
848
+
849
+ // web-src/handoff-scripts.ts
850
+ var HandoffScripts;
851
+ ((HandoffScripts) => {
852
+ HandoffScripts.MARK = "@@ta";
853
+ function q(value) {
854
+ return `'${value.replace(/'/g, "'\\''")}'`;
855
+ }
856
+ HandoffScripts.q = q;
857
+ function results(output) {
858
+ const lines = output.split(`
859
+ `);
860
+ const at = lines.lastIndexOf(HandoffScripts.MARK);
861
+ const values = {};
862
+ for (const line of at < 0 ? [] : lines.slice(at + 1)) {
863
+ const equals = line.indexOf("=");
864
+ if (equals > 0) {
865
+ values[line.slice(0, equals)] = line.slice(equals + 1);
866
+ }
867
+ }
868
+ return values;
869
+ }
870
+ HandoffScripts.results = results;
871
+ function ref(id, side) {
872
+ return `refs/ta-handoff/${id}/${side}`;
873
+ }
874
+ HandoffScripts.ref = ref;
875
+ const PRELUDE = [
876
+ "set -e",
877
+ "export GIT_AUTHOR_NAME=Ta GIT_AUTHOR_EMAIL=ta@localhost GIT_COMMITTER_NAME=Ta GIT_COMMITTER_EMAIL=ta@localhost",
878
+ '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; }',
879
+ 'ta_tree() { ta_index; GIT_INDEX_FILE="$ta_idx" git add -A; GIT_INDEX_FILE="$ta_idx" git write-tree; rm -f "$ta_idx"; }',
880
+ '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"; }'
881
+ ].join(`
882
+ `);
883
+ function program(...lines) {
884
+ return [PRELUDE, ...lines.filter(Boolean)].join(`
885
+ `);
886
+ }
887
+ function top() {
888
+ 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");
889
+ }
890
+ HandoffScripts.top = top;
891
+ function snapshot(id, side) {
892
+ 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"');
893
+ }
894
+ HandoffScripts.snapshot = snapshot;
895
+ function bundle(file, refs, not) {
896
+ const args = [...refs.map(q), ...not.length ? ["--not", ...not.map(q)] : []].join(" ");
897
+ return program(`rm -f ${q(file)}`, `git bundle create -q ${q(file)} ${args}`, `echo ${HandoffScripts.MARK}`, `echo "size=$(wc -c < ${q(file)} | tr -d ' ')"`);
898
+ }
899
+ HandoffScripts.bundle = bundle;
900
+ function size(file) {
901
+ return program(`echo ${HandoffScripts.MARK}`, `echo "size=$(wc -c < ${q(file)} | tr -d ' ')"`);
902
+ }
903
+ HandoffScripts.size = size;
904
+ function fetch(file, ref2, into = ref2) {
905
+ return program(`git fetch -q ${q(file)} ${q(`+${ref2}:${into}`)}`, `rm -f ${q(file)}`);
906
+ }
907
+ HandoffScripts.fetch = fetch;
908
+ function head() {
909
+ return program(`echo ${HandoffScripts.MARK}`, 'echo "head=$(git rev-parse --verify "HEAD^{commit}")"');
910
+ }
911
+ HandoffScripts.head = head;
912
+ function prepare(root, source, last, setup) {
913
+ 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}"');
914
+ }
915
+ HandoffScripts.prepare = prepare;
916
+ function receive(file, snapshotRef, head2, branch) {
917
+ 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)"');
918
+ }
919
+ HandoffScripts.receive = receive;
920
+ function join(file, snapshotRef, base) {
921
+ return program(`git fetch -q ${q(file)} ${q(`+${snapshotRef}:${snapshotRef}`)}`, `rm -f ${q(file)}`, "now=$(ta_tree)", `a=$(git commit-tree ${q(`${snapshotRef}^{tree}`)} -p ${q(base)} -m here)`, `b=$(git commit-tree "$now" -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; }', 'merged=$(echo "$out" | head -n 1)', '[ $code -ne 0 ] || ta_switch "$now" "$merged"', `echo ${HandoffScripts.MARK}`, 'echo "head=$(git rev-parse --verify "HEAD^{commit}")"', 'echo "tree=$(ta_tree)"', `[ $code -eq 0 ] || echo "conflicts=$(echo "$out" | tail -n +2 | grep -v "^$" | sort -u | tr "
922
+ " " ")"`);
923
+ }
924
+ HandoffScripts.join = join;
925
+ function land(from, to, head2) {
926
+ return program(`ta_switch ${q(from)} ${q(to)}`, head2 ? `git reset -q ${q(head2)}` : "", `echo ${HandoffScripts.MARK}`, 'echo "tree=$(ta_tree)"');
927
+ }
928
+ HandoffScripts.land = land;
929
+ function merge(base, here, there) {
930
+ 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 "
931
+ " " ")"`);
932
+ }
933
+ HandoffScripts.merge = merge;
934
+ function count(from, to) {
935
+ return program(`echo ${HandoffScripts.MARK}`, `echo "count=$(git rev-list --count ${q(`${from}..${to}`)})"`);
936
+ }
937
+ HandoffScripts.count = count;
938
+ function forget(id, sides) {
939
+ return program(...sides.map((side) => `git update-ref -d ${q(ref(id, side))} 2>/dev/null || true`));
940
+ }
941
+ HandoffScripts.forget = forget;
942
+ })(HandoffScripts ||= {});
943
+
944
+ // web-src/handoff-sessions.ts
945
+ import { randomUUID as randomUUID2 } from "node:crypto";
946
+ var HandoffSessions;
947
+ ((HandoffSessions) => {
948
+ function lines(text) {
949
+ return text.split(`
950
+ `).filter((line) => line.trim());
951
+ }
952
+ HandoffSessions.lines = lines;
953
+ function directory(cwd) {
954
+ return `--${cwd.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
713
955
  }
714
- HandoffSetup.jsonc = jsonc;
715
- function script(steps2, inputs) {
716
- if (!steps2.length) {
717
- return "echo 'ta-prepare: nothing to install'";
718
- }
719
- const plan = steps2.map((step) => step.command).join(`
956
+ HandoffSessions.directory = directory;
957
+ function relocate(text, cwd) {
958
+ const all = text.split(`
720
959
  `);
721
- return [
722
- "fail=0",
723
- 'stamp="$(git rev-parse --git-dir 2>/dev/null || echo .git)/ta-handoff/prepared"',
724
- `sum=$( { printf '%s\\n' ${q(plan)}; cat ${inputs.map(q).join(" ")} 2>/dev/null; } | git hash-object --stdin)`,
725
- 'if [ -f "$stamp" ] && [ "$(cat "$stamp")" = "$sum" ]; then echo "ta-prepare: up to date"; exit 0; fi',
726
- ...steps2.map((step) => `if command -v ${q(step.tool)} >/dev/null 2>&1; then echo ${q(`ta-prepare: ${step.command}`)}; sh -c ${q(step.command)} || fail=1; else echo ${q(`ta-prepare: skipped, there is no ${step.tool}: ${step.command}`)}; fi`),
727
- 'if [ "$fail" = 0 ]; then mkdir -p "$(dirname "$stamp")" && printf %s "$sum" > "$stamp"; fi',
728
- 'exit "$fail"'
729
- ].join(`
960
+ try {
961
+ const header = JSON.parse(all[0]);
962
+ if (header.type === "session" && header.cwd !== cwd) {
963
+ all[0] = JSON.stringify({ ...header, cwd });
964
+ }
965
+ } catch {}
966
+ return all.join(`
730
967
  `);
731
968
  }
732
- HandoffSetup.script = script;
733
- async function of(root) {
734
- const names = [...new Set([...LOCKS.flatMap((one) => one.files), ...OTHERS.map((one) => one.file), ...DEVCONTAINERS])];
735
- const found = new Map;
736
- await Promise.all(names.map(async (name) => {
737
- const text = await readFile(join(root, name), "utf8").catch(() => {
738
- return;
739
- });
740
- if (text !== undefined) {
741
- found.set(name, text);
969
+ HandoffSessions.relocate = relocate;
970
+ function later(lines2) {
971
+ return lines2.flatMap((line) => {
972
+ try {
973
+ const entry = JSON.parse(line);
974
+ return entry.type === "custom" && entry.customType === LATER_ENTRY && typeof entry.data?.what === "string" ? [entry.data.what] : [];
975
+ } catch {
976
+ return [];
742
977
  }
743
- }));
744
- const devcontainer = DEVCONTAINERS.map((name) => found.get(name)).find((text) => text !== undefined);
745
- const files = new Set(found.keys());
746
- return script(steps(files, devcontainer === undefined ? undefined : jsonc(devcontainer)), [...files].sort());
978
+ });
747
979
  }
748
- HandoffSetup.of = of;
749
- })(HandoffSetup ||= {});
980
+ HandoffSessions.later = later;
981
+ function note(lines2, content, details, display = true, now = Date.now()) {
982
+ let parentId = null;
983
+ for (let at = lines2.length - 1;at >= 0 && parentId === null; at--) {
984
+ try {
985
+ const entry2 = JSON.parse(lines2[at]);
986
+ if (entry2.type !== "session" && typeof entry2.id === "string") {
987
+ parentId = entry2.id;
988
+ }
989
+ } catch {}
990
+ }
991
+ const entry = {
992
+ type: "custom_message",
993
+ id: randomUUID2().slice(0, 8),
994
+ parentId,
995
+ timestamp: new Date(now).toISOString(),
996
+ customType: NOTE_ENTRY,
997
+ content,
998
+ details,
999
+ display
1000
+ };
1001
+ return JSON.stringify(entry);
1002
+ }
1003
+ HandoffSessions.note = note;
1004
+ })(HandoffSessions ||= {});
750
1005
 
751
1006
  // web-src/handoff-sides.ts
752
1007
  import { spawn } from "node:child_process";
@@ -818,13 +1073,13 @@ class CloudSide {
818
1073
  return result.output;
819
1074
  }
820
1075
  async read(path, offset, length) {
821
- const q2 = HandoffScripts.q;
1076
+ const q = HandoffScripts.q;
822
1077
  const piece = `${path}.ta-piece`;
823
- await this.run(`tail -c +${offset + 1} ${q2(path)} | head -c ${length} > ${q2(piece)}`);
1078
+ await this.run(`tail -c +${offset + 1} ${q(path)} | head -c ${length} > ${q(piece)}`);
824
1079
  try {
825
1080
  return await this.cloud.readFile(this.name, piece);
826
1081
  } finally {
827
- await this.run(`rm -f ${q2(piece)}`).catch(() => {
1082
+ await this.run(`rm -f ${q(piece)}`).catch(() => {
828
1083
  return;
829
1084
  });
830
1085
  }
@@ -847,175 +1102,183 @@ var HandoffTransfer;
847
1102
  HandoffTransfer.copy = copy;
848
1103
  })(HandoffTransfer ||= {});
849
1104
 
850
- // ../ta-protocol/esm/common/language.js
851
- var TaLanguageUtil;
852
- (function(TaLanguageUtil2) {
853
- TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
854
- TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
855
- function of(tag) {
856
- const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
857
- if (/^zh(\b|-)/.test(said)) {
858
- return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
1105
+ // web-src/handoff-return.ts
1106
+ var { results } = HandoffScripts;
1107
+ var HandoffReturn;
1108
+ ((HandoffReturn) => {
1109
+ async function conversation({ host, local, temp }, handoff, side, cloudFile, result, cut) {
1110
+ const listed = (await host.listSessions()).filter((session) => session.sessionFile === handoff.sessionFile);
1111
+ const open2 = listed.find((session) => !session.cloud);
1112
+ if (open2) {
1113
+ await host.closeSession(open2.sessionId);
859
1114
  }
860
- return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
861
- }
862
- TaLanguageUtil2.of = of;
863
- function server(env = typeof process === "undefined" ? {} : process.env) {
864
- return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
865
- }
866
- TaLanguageUtil2.server = server;
867
- function pick(language, words) {
868
- return words[of(language)];
869
- }
870
- TaLanguageUtil2.pick = pick;
871
- function say(words) {
872
- return words[server()];
873
- }
874
- TaLanguageUtil2.say = say;
875
- function chinese(language) {
876
- return of(language).startsWith("zh");
877
- }
878
- TaLanguageUtil2.chinese = chinese;
879
- function cjk(language) {
880
- return of(language) !== "en-US";
881
- }
882
- TaLanguageUtil2.cjk = cjk;
883
- function list(language, items) {
884
- return items.join(cjk(language) ? "、" : ", ");
885
- }
886
- TaLanguageUtil2.list = list;
887
- })(TaLanguageUtil || (TaLanguageUtil = {}));
888
-
889
- // web-src/server-texts.ts
890
- var WHY = {
891
- asked: "as the user asked",
892
- sleep: "by itself as the user's computer was about to sleep (its lid closed, most likely)",
893
- battery: "by itself as the battery of the user's computer ran low"
894
- };
895
- function short(model) {
896
- return model ? model.slice(model.indexOf("/") + 1) : "";
897
- }
898
- var HandoffTexts;
899
- ((HandoffTexts) => {
900
- function toCloud(options) {
901
- return [
902
- `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.`,
903
- 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}.`,
904
- "- What git ignores (installed dependencies, builds, .env files) did not come along: install or build again, as the project does, when you need them.",
905
- 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." : "",
906
- `- 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.`,
907
- options.model ? `- The model of this conversation, ${options.model}, has no key in the cloud: another model the cloud can use goes on with it. Work as before; say so if the work needs that model.` : "",
908
- "- Push, publish or deploy only if the user asked for it in this conversation.",
909
- options.goOn ? "- Go on with the work where it stopped." : ""
910
- ].filter(Boolean).join(`
911
- `);
912
- }
913
- HandoffTexts.toCloud = toCloud;
914
- function back(options) {
915
- const files = {
916
- same: "The files are as they were: nothing changed in the cloud.",
917
- taken: "The files here are now as the cloud left them.",
918
- merged: "The files here are the cloud's work merged with what changed here meanwhile.",
919
- 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.`
1115
+ const followed = listed.some((session) => session.cloud && session.attached > 0);
1116
+ const read = async (file) => {
1117
+ const size = Number(results(await side.run(HandoffScripts.size(file))).size);
1118
+ const copy = join(temp, `ta-handoff-${handoff.id}-${basename(file)}`);
1119
+ await HandoffTransfer.copy(side, file, size, local, copy);
1120
+ try {
1121
+ return HandoffSessions.lines(await readFile(copy, "utf8"));
1122
+ } finally {
1123
+ await rm(copy, { force: true });
1124
+ }
920
1125
  };
921
- return [
922
- `This conversation came back from the cloud workspace ${options.cloud} to the user's computer.`,
923
- `- ${files[options.files] ?? ""}`,
924
- options.commits ? `- ${options.commits} commit(s) made in the cloud are on the branch here.` : "",
925
- options.ref && options.files !== "conflict" ? `- HEAD moved here meanwhile: the cloud's commits are kept at ${options.ref}.` : "",
926
- options.later.length ? `- Left for this computer: ${options.later.map((item) => `
927
- - ${item}`).join("")}` : "",
928
- options.goOn ? "- Go on here: do what was left for this computer, and look at the files if they need it." : ""
929
- ].filter(Boolean).join(`
1126
+ const said = (await read(handoff.cloudSessionFile)).slice(handoff.lines ?? 0);
1127
+ const other = cloudFile === handoff.cloudSessionFile ? undefined : HandoffSessions.lines(HandoffSessions.relocate((await read(cloudFile)).join(`
1128
+ `), handoff.cwd));
1129
+ result.later = HandoffSessions.later([...said, ...other ?? []]);
1130
+ const before = other ?? [...HandoffSessions.lines(await readFile(handoff.sessionFile, "utf8")), ...said];
1131
+ const goOn = cut || result.later.length > 0 || result.files === "conflict";
1132
+ const details = {
1133
+ to: "back",
1134
+ cloud: handoff.cloud,
1135
+ files: result.files,
1136
+ ...result.conflicts ? { conflicts: result.conflicts } : {},
1137
+ later: result.later
1138
+ };
1139
+ const note = HandoffSessions.note(before, HandoffTexts.back({
1140
+ cloud: handoff.cloud,
1141
+ files: result.files,
1142
+ conflicts: result.conflicts ?? [],
1143
+ ref: result.ref,
1144
+ commits: result.commits ?? 0,
1145
+ later: result.later,
1146
+ goOn
1147
+ }), details, !goOn);
1148
+ if (said.length) {
1149
+ await appendFile2(handoff.sessionFile, `${said.join(`
1150
+ `)}
1151
+ `);
1152
+ }
1153
+ let sessionFile = handoff.sessionFile;
1154
+ if (other === undefined) {
1155
+ await appendFile2(sessionFile, `${note}
1156
+ `);
1157
+ } else {
1158
+ sessionFile = join(dirname(handoff.sessionFile), basename(cloudFile));
1159
+ await writeFile2(sessionFile, `${other.join(`
1160
+ `)}
1161
+ ${note}
930
1162
  `);
1163
+ }
1164
+ return { sessionFile, wasOpen: open2 !== undefined || followed, goOn, note: details };
931
1165
  }
932
- HandoffTexts.back = back;
933
- function goOn(note) {
934
- const cloud = note.cloud;
935
- const head = note.to === "cloud" && note.why === "sleep" ? TaLanguageUtil.say({
936
- "zh-CN": `电脑要睡眠了,换到云端接着做 · ${cloud}`,
937
- "zh-TW": `電腦要睡眠了,換到雲端接著做 · ${cloud}`,
938
- "en-US": `The computer is going to sleep: going on in the cloud · ${cloud}`,
939
- "ja-JP": `パソコンがスリープするのでクラウドで続ける · ${cloud}`
940
- }) : note.to === "cloud" && note.why === "battery" ? TaLanguageUtil.say({
941
- "zh-CN": `电量低,换到云端接着做 · ${cloud}`,
942
- "zh-TW": `電量低,換到雲端接著做 · ${cloud}`,
943
- "en-US": `Battery low: going on in the cloud · ${cloud}`,
944
- "ja-JP": `電池残量が少ないのでクラウドで続ける · ${cloud}`
945
- }) : note.to === "cloud" ? TaLanguageUtil.say({
946
- "zh-CN": `换到云端接着做 · ${cloud}`,
947
- "zh-TW": `換到雲端接著做 · ${cloud}`,
948
- "en-US": `Going on in the cloud · ${cloud}`,
949
- "ja-JP": `クラウドで続ける · ${cloud}`
950
- }) : TaLanguageUtil.say({
951
- "zh-CN": `从云端 ${cloud} 接回本机`,
952
- "zh-TW": `從雲端 ${cloud} 接回本機`,
953
- "en-US": `Back on this computer from ${cloud}`,
954
- "ja-JP": `クラウド ${cloud} からこのパソコンに戻しました`
955
- });
956
- const conflicts = note.conflicts?.length ?? 0;
957
- const later = note.later?.length ?? 0;
958
- const more = [
959
- conflicts ? TaLanguageUtil.say({
960
- "zh-CN": `${conflicts} 个文件两边都改过`,
961
- "zh-TW": `${conflicts} 個檔案兩邊都改過`,
962
- "en-US": `${conflicts} file(s) changed on both sides`,
963
- "ja-JP": `${conflicts} 個のファイルが両方で変更`
964
- }) : "",
965
- later ? TaLanguageUtil.say({
966
- "zh-CN": `${later} 件事留给本机做`,
967
- "zh-TW": `${later} 件事留給本機做`,
968
- "en-US": `${later} step(s) left for this computer`,
969
- "ja-JP": `${later} 件をこのパソコンで`
970
- }) : "",
971
- note.model?.to ? TaLanguageUtil.say({
972
- "zh-CN": `云端用不了 ${short(note.model.from)},换成 ${short(note.model.to)}`,
973
- "zh-TW": `雲端用不了 ${short(note.model.from)},換成 ${short(note.model.to)}`,
974
- "en-US": `no key of ${short(note.model.from)} there: going on with ${short(note.model.to)}`,
975
- "ja-JP": `クラウドでは ${short(note.model.from)} が使えないので ${short(note.model.to)} で続ける`
976
- }) : ""
977
- ].filter(Boolean);
978
- return [head, ...more].join(" · ");
1166
+ HandoffReturn.conversation = conversation;
1167
+ })(HandoffReturn ||= {});
1168
+
1169
+ // web-src/handoff-setup.ts
1170
+ import { readFile as readFile2 } from "node:fs/promises";
1171
+ import { join as join2 } from "node:path";
1172
+ var LOCKS = [
1173
+ { files: ["bun.lock", "bun.lockb"], step: { tool: "bun", command: "bun install --frozen-lockfile" } },
1174
+ { files: ["pnpm-lock.yaml"], step: { tool: "pnpm", command: "pnpm install --frozen-lockfile" } },
1175
+ { files: ["yarn.lock"], step: { tool: "yarn", command: "yarn install --frozen-lockfile" } },
1176
+ { files: ["package-lock.json"], step: { tool: "npm", command: "npm ci" } },
1177
+ { files: ["package.json"], step: { tool: "npm", command: "npm install" } }
1178
+ ];
1179
+ var OTHERS = [
1180
+ { file: "uv.lock", step: { tool: "uv", command: "uv sync" } },
1181
+ { file: "poetry.lock", step: { tool: "poetry", command: "poetry install" } },
1182
+ { file: "requirements.txt", step: { tool: "python3", command: "python3 -m venv .venv && .venv/bin/pip install -r requirements.txt" } },
1183
+ { file: "Cargo.lock", step: { tool: "cargo", command: "cargo fetch" } },
1184
+ { file: "go.sum", step: { tool: "go", command: "go mod download" } },
1185
+ { file: "Gemfile.lock", step: { tool: "bundle", command: "bundle install" } }
1186
+ ];
1187
+ var DEVCONTAINERS = [".devcontainer/devcontainer.json", ".devcontainer.json"];
1188
+ var DEVCONTAINER_COMMANDS = ["onCreateCommand", "updateContentCommand", "postCreateCommand"];
1189
+ function q(value) {
1190
+ return `'${value.replace(/'/g, `'\\''`)}'`;
1191
+ }
1192
+ var HandoffSetup;
1193
+ ((HandoffSetup) => {
1194
+ function steps(files, devcontainer) {
1195
+ const own = devcontainerSteps(devcontainer);
1196
+ if (own.length) {
1197
+ return own;
1198
+ }
1199
+ const steps2 = [];
1200
+ const lock = LOCKS.find((one) => one.files.some((file) => files.has(file)));
1201
+ if (lock) {
1202
+ steps2.push(lock.step);
1203
+ }
1204
+ for (const other of OTHERS) {
1205
+ if (files.has(other.file)) {
1206
+ steps2.push(other.step);
1207
+ }
1208
+ }
1209
+ return steps2;
979
1210
  }
980
- HandoffTexts.goOn = goOn;
981
- function noModel(cloud) {
982
- return TaLanguageUtil.say({
983
- "zh-CN": `云端 ${cloud} 没有能用的模型:在保险箱里打开模型密钥的“可在我的云端工作区用”,或在那台机器上登录`,
984
- "zh-TW": `雲端 ${cloud} 沒有能用的模型:在保險箱裡打開模型金鑰的「可在我的雲端工作區用」,或在那台機器上登入`,
985
- "en-US": `The cloud workspace ${cloud} has no model it can use: let a key of a model go there in the vault, or sign in there`,
986
- "ja-JP": `クラウド ${cloud} で使えるモデルがありません。金庫でモデルのキーを「クラウドのワークスペースでも使う」にするか、そのマシンでログインしてください`
987
- });
1211
+ HandoffSetup.steps = steps;
1212
+ function devcontainerSteps(config) {
1213
+ if (!config || typeof config !== "object") {
1214
+ return [];
1215
+ }
1216
+ const steps2 = [];
1217
+ const add = (value) => {
1218
+ if (typeof value === "string" && value.trim()) {
1219
+ steps2.push({ tool: "sh", command: value.trim() });
1220
+ } else if (Array.isArray(value) && value.length && value.every((part) => typeof part === "string")) {
1221
+ steps2.push({ tool: value[0], command: value.map(q).join(" ") });
1222
+ } else if (value && typeof value === "object" && !Array.isArray(value)) {
1223
+ Object.values(value).forEach(add);
1224
+ }
1225
+ };
1226
+ for (const key of DEVCONTAINER_COMMANDS) {
1227
+ add(config[key]);
1228
+ }
1229
+ return steps2;
988
1230
  }
989
- HandoffTexts.noModel = noModel;
990
- function away(cloud) {
991
- return TaLanguageUtil.say({
992
- "zh-CN": `这个对话正在云端 ${cloud} 接着做:去那边看,或在对话列表的菜单里点“接回本机”再继续。`,
993
- "zh-TW": `這個對話正在雲端 ${cloud} 接著做:去那邊看,或在對話列表的選單裡點「接回本機」再繼續。`,
994
- "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.`,
995
- "ja-JP": `この会話はクラウド ${cloud} で続いています。そちらで見るか、一覧のメニューの「パソコンに戻す」で戻してから続けてください。`
996
- });
1231
+ HandoffSetup.devcontainerSteps = devcontainerSteps;
1232
+ function jsonc(text) {
1233
+ const stripped = text.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, string) => string ?? "").replace(/,(\s*[}\]])/g, "$1");
1234
+ try {
1235
+ return JSON.parse(stripped);
1236
+ } catch {
1237
+ return;
1238
+ }
997
1239
  }
998
- HandoffTexts.away = away;
999
- function stayed(reason) {
1000
- return TaLanguageUtil.say({
1001
- "zh-CN": `没能换到云端(${reason}),在本机接着做`,
1002
- "zh-TW": `沒能換到雲端(${reason}),在本機接著做`,
1003
- "en-US": `It did not move to the cloud (${reason}): going on here`,
1004
- "ja-JP": `クラウドへ移せませんでした(${reason})。このパソコンで続けます`
1005
- });
1240
+ HandoffSetup.jsonc = jsonc;
1241
+ function script(steps2, inputs) {
1242
+ if (!steps2.length) {
1243
+ return "echo 'ta-prepare: nothing to install'";
1244
+ }
1245
+ const plan = steps2.map((step) => step.command).join(`
1246
+ `);
1247
+ return [
1248
+ "fail=0",
1249
+ 'stamp="$(git rev-parse --git-dir 2>/dev/null || echo .git)/ta-handoff/prepared"',
1250
+ `sum=$( { printf '%s\\n' ${q(plan)}; cat ${inputs.map(q).join(" ")} 2>/dev/null; } | git hash-object --stdin)`,
1251
+ 'if [ -f "$stamp" ] && [ "$(cat "$stamp")" = "$sum" ]; then echo "ta-prepare: up to date"; exit 0; fi',
1252
+ ...steps2.map((step) => `if command -v ${q(step.tool)} >/dev/null 2>&1; then echo ${q(`ta-prepare: ${step.command}`)}; sh -c ${q(step.command)} || fail=1; else echo ${q(`ta-prepare: skipped, there is no ${step.tool}: ${step.command}`)}; fi`),
1253
+ 'if [ "$fail" = 0 ]; then mkdir -p "$(dirname "$stamp")" && printf %s "$sum" > "$stamp"; fi',
1254
+ 'exit "$fail"'
1255
+ ].join(`
1256
+ `);
1006
1257
  }
1007
- HandoffTexts.stayed = stayed;
1008
- function failed(reason) {
1009
- return `Moving this conversation to the cloud failed: ${reason}. It stays on this computer; tell the user in a line.`;
1258
+ HandoffSetup.script = script;
1259
+ async function of(root) {
1260
+ const names = [...new Set([...LOCKS.flatMap((one) => one.files), ...OTHERS.map((one) => one.file), ...DEVCONTAINERS])];
1261
+ const found = new Map;
1262
+ await Promise.all(names.map(async (name) => {
1263
+ const text = await readFile2(join2(root, name), "utf8").catch(() => {
1264
+ return;
1265
+ });
1266
+ if (text !== undefined) {
1267
+ found.set(name, text);
1268
+ }
1269
+ }));
1270
+ const devcontainer = DEVCONTAINERS.map((name) => found.get(name)).find((text) => text !== undefined);
1271
+ const files = new Set(found.keys());
1272
+ return script(steps(files, devcontainer === undefined ? undefined : jsonc(devcontainer)), [...files].sort());
1010
1273
  }
1011
- HandoffTexts.failed = failed;
1012
- })(HandoffTexts ||= {});
1274
+ HandoffSetup.of = of;
1275
+ })(HandoffSetup ||= {});
1013
1276
 
1014
1277
  // web-src/handoff-service.ts
1015
1278
  var MAX_BUNDLE_BYTES = 512 * 1024 * 1024;
1016
1279
  var MAX_WARM_BYTES = 2 * 1024 * 1024 * 1024;
1017
1280
  var WARM_REF = "refs/ta-handoff/warm";
1018
- var { q: q2, ref, results } = HandoffScripts;
1281
+ var { q: q2, ref, results: results2 } = HandoffScripts;
1019
1282
 
1020
1283
  class CloudHandoffs {
1021
1284
  host;
@@ -1025,14 +1288,17 @@ class CloudHandoffs {
1025
1288
  afterTurn = new Map;
1026
1289
  busy = new Set;
1027
1290
  warming = new Map;
1291
+ lanes = new HandoffLanes;
1028
1292
  book;
1029
- writes = Promise.resolve();
1293
+ copies;
1030
1294
  stop;
1031
1295
  constructor(host, options = {}) {
1032
1296
  this.host = host;
1033
1297
  this.options = options;
1034
1298
  this.local = options.local ?? new LocalSide;
1035
1299
  this.temp = options.temp ?? tmpdir();
1300
+ this.book = new HandoffBookStore(host);
1301
+ this.copies = new HandoffCopiesBook(host);
1036
1302
  }
1037
1303
  async begin() {
1038
1304
  this.stop = this.host.onSessionEvent((event) => {
@@ -1041,31 +1307,56 @@ class CloudHandoffs {
1041
1307
  const cloud = this.afterTurn.get(file);
1042
1308
  this.afterTurn.delete(file);
1043
1309
  this.handOff(file, cloud, true).catch(async (error) => {
1044
- const open2 = (await this.host.listSessions().catch(() => [])).find((session) => session.sessionFile === file);
1310
+ const open2 = await this.here(file).catch(() => {
1311
+ return;
1312
+ });
1045
1313
  await this.host.prompt(open2?.sessionId ?? event.sessionId, {
1046
- message: TaMessageSource.notice(HandoffTexts.failed(error instanceof Error ? error.message : String(error)), NAME),
1047
- clientMessageId: `${NAME}:failed:${randomUUID2()}`
1314
+ message: TaMessageSource.notice(HandoffTexts.failed(HandoffTexts.reason(error)), NAME),
1315
+ clientMessageId: `${NAME}:failed:${randomUUID3()}`
1048
1316
  }).catch(() => {
1049
1317
  return;
1050
1318
  });
1051
1319
  });
1052
1320
  }
1053
1321
  });
1054
- await this.save((book) => {
1322
+ await this.book.save((book) => {
1055
1323
  book.handoffs = book.handoffs.flatMap((handoff) => handoff.state === "moving" ? [] : handoff.state === "returning" ? [{ ...handoff, state: "cloud" }] : [handoff]);
1056
1324
  });
1325
+ for (const handoff of (await this.book.read()).handoffs) {
1326
+ this.awayOf(handoff)?.there(handoff.cloud, this.remoteOf(handoff));
1327
+ }
1328
+ }
1329
+ awayOf(handoff) {
1330
+ return this.host.cloud?.away?.(handoff.sessionFile, handoff.cwd);
1331
+ }
1332
+ remoteOf(handoff) {
1333
+ return {
1334
+ ...handoff.cloudSessionId ? { sessionId: handoff.cloudSessionId } : {},
1335
+ sessionFile: handoff.cloudSessionFile,
1336
+ cwd: handoff.cloudCwd
1337
+ };
1338
+ }
1339
+ async here(sessionFile) {
1340
+ return (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile && !session.cloud);
1057
1341
  }
1058
1342
  dispose() {
1059
1343
  this.stop?.();
1060
1344
  }
1061
1345
  async list() {
1062
- return { handoffs: (await this.read()).handoffs, workspaces: await this.host.cloud?.list() ?? [] };
1346
+ return { handoffs: (await this.book.read()).handoffs, workspaces: await this.host.cloud?.list() ?? [] };
1347
+ }
1348
+ async reach(cloud, device) {
1349
+ const { cloud: host, workspace } = await this.workspace(cloud);
1350
+ if (!host.reach) {
1351
+ throw new Error("This Ta is too old to give a phone the way to the cloud: update it.");
1352
+ }
1353
+ return host.reach(workspace.name, String(device || "phone").slice(0, 60));
1063
1354
  }
1064
1355
  async away(sessionFile) {
1065
- return (await this.read()).handoffs.find((handoff) => handoff.sessionFile === sessionFile);
1356
+ return (await this.book.read()).handoffs.find((handoff) => handoff.sessionFile === sessionFile);
1066
1357
  }
1067
1358
  async handOffAfterTurn(sessionFile, cloud) {
1068
- const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile);
1359
+ const open2 = await this.here(sessionFile);
1069
1360
  if (open2?.isStreaming) {
1070
1361
  await this.workspace(cloud);
1071
1362
  this.afterTurn.set(sessionFile, cloud);
@@ -1079,15 +1370,16 @@ class CloudHandoffs {
1079
1370
  throw new Error("This conversation is in the cloud already.");
1080
1371
  }
1081
1372
  this.claim(sessionFile);
1082
- const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile);
1083
1373
  let handoff;
1374
+ let open2;
1084
1375
  try {
1376
+ open2 = await this.here(sessionFile);
1085
1377
  const cwd2 = open2?.cwd ?? await this.host.sessionCwd(sessionFile);
1086
1378
  if (!cwd2 || !isAbsolute2(cwd2)) {
1087
1379
  throw new Error("Only a conversation of a folder of this computer goes to the cloud.");
1088
1380
  }
1089
1381
  handoff = {
1090
- id: randomUUID2().slice(0, 8),
1382
+ id: randomUUID3().slice(0, 8),
1091
1383
  state: "moving",
1092
1384
  cloud: workspace.name,
1093
1385
  cloudUrl: workspace.url,
@@ -1098,7 +1390,7 @@ class CloudHandoffs {
1098
1390
  ...open2?.isStreaming ? { wasRunning: true } : {},
1099
1391
  ...auto ? { auto } : {}
1100
1392
  };
1101
- await this.save((book) => {
1393
+ await this.book.save((book) => {
1102
1394
  book.handoffs.push(handoff);
1103
1395
  });
1104
1396
  } catch (error) {
@@ -1107,152 +1399,139 @@ class CloudHandoffs {
1107
1399
  }
1108
1400
  const { id, root, cwd } = handoff;
1109
1401
  const side = this.side(cloud, workspace.name);
1110
- const bundle = join2(this.temp, `ta-handoff-${id}.bundle`);
1111
- const copy = join2(this.temp, `ta-handoff-${id}.jsonl`);
1402
+ const bundle = join3(this.temp, `ta-handoff-${id}.bundle`);
1403
+ const copy = join3(this.temp, `ta-handoff-${id}.jsonl`);
1112
1404
  const clone = `${workspace.name}
1113
1405
  ${root}`;
1114
1406
  let stopped = false;
1407
+ let away;
1115
1408
  try {
1116
- const switched = await this.modelThere(cloud, workspace.name, open2?.model);
1117
- await this.warming.get(clone)?.catch(() => {
1118
- return;
1119
- });
1120
- if (open2) {
1121
- stopped = true;
1122
- if (open2.isStreaming) {
1123
- await this.host.abort(open2.sessionId);
1409
+ const switched = await HandoffModels.there(cloud, workspace.name, open2?.model);
1410
+ return await this.lanes.run(clone, async () => {
1411
+ away = this.awayOf(handoff);
1412
+ if (open2) {
1413
+ stopped = true;
1414
+ if (open2.isStreaming) {
1415
+ await this.host.abort(open2.sessionId);
1416
+ }
1417
+ await this.host.closeSession(open2.sessionId);
1124
1418
  }
1125
- await this.host.closeSession(open2.sessionId);
1126
- }
1127
- const book = await this.read();
1128
- const snapshot = results(await this.local.run(HandoffScripts.snapshot(id, "local"), root));
1129
- const last = book.clones[clone];
1130
- const there = results(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1131
- const made = results(await this.local.run(HandoffScripts.bundle(bundle, [ref(id, "local")], there.has === "yes" && last ? [last] : []), root));
1132
- const size = Number(made.size);
1133
- if (!(size <= MAX_BUNDLE_BYTES)) {
1134
- throw new Error(`What ${root} would send is ${Math.round(size / 1048576)} MB, more than ${MAX_BUNDLE_BYTES / 1048576} MB at a time.`);
1135
- }
1136
- const arrived = posix.join(there.home, ".ta", "handoff", `${id}.bundle`);
1137
- await side.run(`mkdir -p ${q2(posix.dirname(arrived))}`);
1138
- await HandoffTransfer.copy(this.local, bundle, size, side, arrived);
1139
- const cloudRoot = there.root;
1140
- const cloudCwd = posix.join(cloudRoot, relative(root, cwd).split(sep).join("/"));
1141
- const received = results(await side.run(HandoffScripts.receive(arrived, ref(id, "local"), snapshot.head, snapshot.branch || undefined), cloudRoot));
1142
- if (received.tree !== snapshot.tree) {
1143
- throw new Error("The files in the cloud did not come out the same as here, so nothing moved.");
1144
- }
1145
- await cloud.prepare?.(workspace.name, cloudRoot, await HandoffSetup.of(root)).catch(() => {
1146
- return;
1147
- });
1148
- const lines = HandoffSessions.lines(await readFile2(sessionFile, "utf8"));
1149
- const cut = open2?.isStreaming === true;
1150
- const details = { to: "cloud", cloud: workspace.name, ...auto ? { why: auto } : {} };
1151
- const going = cut || goOn;
1152
- if (switched) {
1153
- details.model = { from: switched };
1154
- }
1155
- const note = HandoffSessions.note(lines, HandoffTexts.toCloud({ cloud: workspace.name, root, cloudRoot, cut, goOn: going, why: auto, model: switched }), details, !going);
1156
- const body = new TextEncoder().encode(`${HandoffSessions.relocate(lines.join(`
1419
+ const book = await this.book.read();
1420
+ const sharing = book.handoffs.find((other) => other.id !== id && other.cloud === workspace.name && other.root === root && other.state === "cloud" && other.cloudRoot);
1421
+ const snapshot = results2(await this.local.run(HandoffScripts.snapshot(id, "local"), root));
1422
+ const last = book.clones[clone];
1423
+ const there = results2(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1424
+ const made = results2(await this.local.run(HandoffScripts.bundle(bundle, [ref(id, "local")], there.has === "yes" && last ? [last] : []), root));
1425
+ const size = Number(made.size);
1426
+ if (!(size <= MAX_BUNDLE_BYTES)) {
1427
+ throw new Error(`What ${root} would send is ${Math.round(size / 1048576)} MB, more than ${MAX_BUNDLE_BYTES / 1048576} MB at a time.`);
1428
+ }
1429
+ const arrived = posix.join(there.home, ".ta", "handoff", `${id}.bundle`);
1430
+ await side.run(`mkdir -p ${q2(posix.dirname(arrived))}`);
1431
+ await HandoffTransfer.copy(this.local, bundle, size, side, arrived);
1432
+ const cloudRoot = there.root;
1433
+ const cloudCwd = posix.join(cloudRoot, relative(root, cwd).split(sep).join("/"));
1434
+ if (sharing) {
1435
+ const joined = results2(await HandoffLanes.untangled(() => side.run(HandoffScripts.join(arrived, ref(id, "local"), ref(sharing.id, "local")), cloudRoot)));
1436
+ if (joined.head !== snapshot.head) {
1437
+ throw new Error(HandoffTexts.sharedHead(workspace.name));
1438
+ }
1439
+ if (joined.conflicts) {
1440
+ throw new Error(HandoffTexts.sharedConflict(workspace.name, joined.conflicts.split("\t").filter(Boolean)));
1441
+ }
1442
+ } else {
1443
+ const received = results2(await HandoffLanes.untangled(() => side.run(HandoffScripts.receive(arrived, ref(id, "local"), snapshot.head, snapshot.branch || undefined), cloudRoot)));
1444
+ if (received.tree !== snapshot.tree) {
1445
+ throw new Error("The files in the cloud did not come out the same as here, so nothing moved.");
1446
+ }
1447
+ await cloud.prepare?.(workspace.name, cloudRoot, await HandoffSetup.of(root)).catch(() => {
1448
+ return;
1449
+ });
1450
+ }
1451
+ const lines = HandoffSessions.lines(await readFile3(sessionFile, "utf8"));
1452
+ const cut = open2?.isStreaming === true;
1453
+ const details = { to: "cloud", cloud: workspace.name, ...auto ? { why: auto } : {} };
1454
+ const going = cut || goOn;
1455
+ if (switched) {
1456
+ details.model = { from: switched };
1457
+ }
1458
+ const note = HandoffSessions.note(lines, HandoffTexts.toCloud({ cloud: workspace.name, root, cloudRoot, cut, goOn: going, why: auto, model: switched }), details, !going);
1459
+ const body = new TextEncoder().encode(`${HandoffSessions.relocate(lines.join(`
1157
1460
  `), cloudCwd)}
1158
1461
  ${note}
1159
1462
  `);
1160
- await writeFile2(copy, body);
1161
- const cloudSessionFile = posix.join(there.agent, "sessions", HandoffSessions.directory(cloudCwd), basename(sessionFile));
1162
- await side.run(`mkdir -p ${q2(posix.dirname(cloudSessionFile))}`);
1163
- await HandoffTransfer.copy(this.local, copy, body.length, side, cloudSessionFile);
1164
- const server = cloud.server(workspace.name);
1165
- const opened = await server.openSession({ cwd: cloudCwd, sessionFile: cloudSessionFile });
1166
- const to = await this.useModel(server, opened.sessionId, switched ? undefined : open2?.model);
1167
- if (details.model && to) {
1168
- details.model.to = to;
1169
- }
1170
- if (going) {
1171
- await server.prompt(opened.sessionId, {
1172
- message: TaMessageSource.notice(HandoffTexts.goOn(details), NAME),
1173
- clientMessageId: `${NAME}:${id}:cloud`
1463
+ await writeFile3(copy, body);
1464
+ const cloudSessionFile = posix.join(there.agent, "sessions", HandoffSessions.directory(cloudCwd), basename2(sessionFile));
1465
+ await side.run(`mkdir -p ${q2(posix.dirname(cloudSessionFile))}`);
1466
+ await HandoffTransfer.copy(this.local, copy, body.length, side, cloudSessionFile);
1467
+ const server = cloud.server(workspace.name);
1468
+ const opened = await server.openSession({ cwd: cloudCwd, sessionFile: cloudSessionFile });
1469
+ const to = await HandoffModels.use(server, opened.sessionId, switched ? undefined : open2?.model);
1470
+ if (details.model && to) {
1471
+ details.model.to = to;
1472
+ }
1473
+ away?.there(workspace.name, { sessionId: opened.sessionId, sessionFile: cloudSessionFile, cwd: cloudCwd });
1474
+ await this.tell(cloud, workspace.name, {
1475
+ sessionFile: cloudSessionFile,
1476
+ computer: hostname().replace(/\.local$/, ""),
1477
+ here: sessionFile,
1478
+ at: Date.now()
1174
1479
  });
1175
- }
1176
- const moved = {
1177
- ...handoff,
1178
- state: "cloud",
1179
- cloudRoot,
1180
- cloudCwd,
1181
- cloudSessionFile,
1182
- cloudSessionId: opened.sessionId,
1183
- head: snapshot.head,
1184
- tree: snapshot.tree,
1185
- ...snapshot.branch ? { branch: snapshot.branch } : {},
1186
- lines: lines.length
1187
- };
1188
- await this.save((next) => {
1189
- next.handoffs = next.handoffs.map((other) => other.id === id ? moved : other);
1190
- next.clones[clone] = snapshot.head;
1480
+ if (going) {
1481
+ await server.prompt(opened.sessionId, {
1482
+ message: TaMessageSource.notice(HandoffTexts.goOn(details), NAME),
1483
+ clientMessageId: `${NAME}:${id}:cloud`
1484
+ });
1485
+ }
1486
+ const moved = {
1487
+ ...handoff,
1488
+ state: "cloud",
1489
+ cloudRoot,
1490
+ cloudCwd,
1491
+ cloudSessionFile,
1492
+ cloudSessionId: opened.sessionId,
1493
+ head: snapshot.head,
1494
+ tree: snapshot.tree,
1495
+ ...snapshot.branch ? { branch: snapshot.branch } : {},
1496
+ lines: lines.length
1497
+ };
1498
+ await this.book.save((next) => {
1499
+ next.handoffs = next.handoffs.map((other) => other.id === id ? moved : other);
1500
+ next.clones[clone] = snapshot.head;
1501
+ });
1502
+ return moved;
1191
1503
  });
1192
- return moved;
1193
1504
  } catch (error) {
1194
- await this.save((book) => {
1505
+ await this.book.save((book) => {
1195
1506
  book.handoffs = book.handoffs.filter((other) => other.id !== id);
1196
1507
  });
1197
1508
  await this.local.run(HandoffScripts.forget(id, ["local"]), root).catch(() => {
1198
1509
  return;
1199
1510
  });
1511
+ away?.end();
1200
1512
  if (open2 && stopped) {
1201
1513
  await this.resumeHere(open2.isStreaming, cwd, sessionFile, error).catch(() => {
1202
1514
  return;
1203
1515
  });
1204
1516
  }
1205
- throw error;
1517
+ throw HandoffTexts.locked(error) ? new Error(HandoffTexts.reason(error)) : error;
1206
1518
  } finally {
1207
1519
  this.busy.delete(sessionFile);
1208
- await rm(bundle, { force: true });
1209
- await rm(copy, { force: true });
1210
- }
1211
- }
1212
- async modelThere(cloud, name, model) {
1213
- const providers = await cloud.providers?.(name).catch(() => {
1214
- return;
1215
- });
1216
- if (!providers) {
1217
- return;
1218
- }
1219
- if (!providers.length) {
1220
- throw new Error(HandoffTexts.noModel(name));
1520
+ await rm2(bundle, { force: true });
1521
+ await rm2(copy, { force: true });
1221
1522
  }
1222
- const provider = model?.includes("/") ? model.split("/")[0] : undefined;
1223
- return model && provider && !providers.includes(provider) ? model : undefined;
1224
1523
  }
1225
- async useModel(server, sessionId, model) {
1226
- if (model?.includes("/")) {
1227
- const [provider, ...id] = model.split("/");
1228
- if (await server.setModel(sessionId, provider, id.join("/")).then(() => true, () => false)) {
1229
- return;
1230
- }
1231
- }
1232
- const state = await server.getState(sessionId).catch(() => {
1524
+ async tell(cloud, name, copy) {
1525
+ await cloud.callPackage?.(name, NAME, "copy", [copy]).catch(() => {
1233
1526
  return;
1234
1527
  });
1235
- const available = (await server.getAvailableModels(sessionId).catch(() => {
1236
- return;
1237
- }))?.models ?? [];
1238
- const now = state?.model && available.find((one) => one.provider === state.model?.provider && one.id === state.model?.id);
1239
- const chosen = now ?? available[0];
1240
- if (!chosen) {
1241
- return;
1242
- }
1243
- if (!now) {
1244
- await server.setModel(sessionId, chosen.provider, chosen.id).catch(() => {
1245
- return;
1246
- });
1247
- }
1248
- return `${chosen.provider}/${chosen.id}`;
1249
1528
  }
1250
1529
  async resumeHere(running, cwd, sessionFile, error) {
1251
1530
  const opened = await this.host.openSession({ cwd, sessionFile });
1252
1531
  if (running) {
1253
1532
  await this.host.prompt(opened.sessionId, {
1254
- message: TaMessageSource.notice(HandoffTexts.stayed(error instanceof Error ? error.message : String(error)), NAME),
1255
- clientMessageId: `${NAME}:stayed:${randomUUID2()}`
1533
+ message: TaMessageSource.notice(HandoffTexts.stayed(HandoffTexts.reason(error)), NAME),
1534
+ clientMessageId: `${NAME}:stayed:${randomUUID3()}`
1256
1535
  });
1257
1536
  }
1258
1537
  }
@@ -1263,40 +1542,40 @@ ${note}
1263
1542
  ${root}`;
1264
1543
  let work = this.warming.get(key);
1265
1544
  if (!work) {
1266
- work = this.carryAhead(cloud, workspace.name, root, key).finally(() => this.warming.delete(key));
1545
+ work = this.lanes.run(key, () => this.carryAhead(cloud, workspace.name, root, key)).finally(() => this.warming.delete(key));
1267
1546
  this.warming.set(key, work);
1268
1547
  }
1269
1548
  return work;
1270
1549
  }
1271
1550
  async carryAhead(cloud, name, root, key) {
1272
- const book = await this.read();
1551
+ const book = await this.book.read();
1273
1552
  const last = book.clones[key];
1274
- const head = results(await this.local.run(HandoffScripts.head(), root)).head;
1553
+ const head = results2(await this.local.run(HandoffScripts.head(), root)).head;
1275
1554
  if (!head || head === last) {
1276
1555
  return;
1277
1556
  }
1278
1557
  const side = this.side(cloud, name);
1279
- const there = results(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1280
- const file = join2(this.temp, `ta-handoff-warm-${randomUUID2().slice(0, 8)}.bundle`);
1558
+ const there = results2(await side.run(HandoffScripts.prepare(root, `${book.machine}:${root}`, last, await this.identity(root))));
1559
+ const file = join3(this.temp, `ta-handoff-warm-${randomUUID3().slice(0, 8)}.bundle`);
1281
1560
  try {
1282
- const made = results(await this.local.run(HandoffScripts.bundle(file, ["HEAD"], there.has === "yes" && last ? [last] : []), root));
1561
+ const made = results2(await this.local.run(HandoffScripts.bundle(file, ["HEAD"], there.has === "yes" && last ? [last] : []), root));
1283
1562
  const size = Number(made.size);
1284
1563
  if (!(size <= MAX_WARM_BYTES)) {
1285
1564
  throw new Error(`The history of ${root} is ${Math.round(size / 1048576)} MB, more than ${MAX_WARM_BYTES / 1048576} MB.`);
1286
1565
  }
1287
- const arrived = posix.join(there.home, ".ta", "handoff", basename(file));
1566
+ const arrived = posix.join(there.home, ".ta", "handoff", basename2(file));
1288
1567
  await side.run(`mkdir -p ${q2(posix.dirname(arrived))}`);
1289
1568
  await HandoffTransfer.copy(this.local, file, size, side, arrived);
1290
1569
  await side.run(HandoffScripts.fetch(arrived, "HEAD", WARM_REF), there.root);
1291
- await this.save((next) => {
1570
+ await this.book.save((next) => {
1292
1571
  next.clones[key] = head;
1293
1572
  });
1294
1573
  } finally {
1295
- await rm(file, { force: true });
1574
+ await rm2(file, { force: true });
1296
1575
  }
1297
1576
  }
1298
1577
  async idleThere(id) {
1299
- const handoff = (await this.read()).handoffs.find((other) => other.id === id);
1578
+ const handoff = (await this.book.read()).handoffs.find((other) => other.id === id);
1300
1579
  if (handoff?.state !== "cloud") {
1301
1580
  return false;
1302
1581
  }
@@ -1305,43 +1584,62 @@ ${root}`;
1305
1584
  return !there?.isStreaming;
1306
1585
  }
1307
1586
  async takeBack(id) {
1308
- const handoff = (await this.read()).handoffs.find((other) => other.id === id);
1587
+ const handoff = (await this.book.read()).handoffs.find((other) => other.id === id);
1309
1588
  if (handoff?.state !== "cloud" || !handoff.cloudRoot || !handoff.cloudSessionFile || !handoff.head || !handoff.tree) {
1310
1589
  throw new Error(handoff ? "This conversation is on its way: try again in a moment." : "This conversation is not in the cloud.");
1311
1590
  }
1312
1591
  const { cloud } = await this.workspace(handoff.cloud);
1313
1592
  this.claim(handoff.sessionFile);
1593
+ const { root } = handoff;
1594
+ try {
1595
+ return await this.lanes.run(`${handoff.cloud}
1596
+ ${root}`, () => this.bringBack(cloud, handoff));
1597
+ } finally {
1598
+ this.busy.delete(handoff.sessionFile);
1599
+ }
1600
+ }
1601
+ async bringBack(cloud, handoff) {
1602
+ const { id, root, cloudSessionFile, head, tree } = handoff;
1603
+ const cloudRoot = handoff.cloudRoot;
1314
1604
  const side = this.side(cloud, handoff.cloud);
1315
- const { root, cloudRoot, cloudSessionFile, head, tree } = handoff;
1316
- const bundle = join2(this.temp, `ta-handoff-${id}-back.bundle`);
1605
+ const bundle = join3(this.temp, `ta-handoff-${id}-back.bundle`);
1606
+ const away = this.awayOf(handoff);
1607
+ away?.hold();
1317
1608
  try {
1318
- await this.save((book) => {
1609
+ await this.book.save((book) => {
1319
1610
  book.handoffs = book.handoffs.map((other) => other.id === id ? { ...other, state: "returning" } : other);
1320
1611
  });
1321
1612
  const server = cloud.server(handoff.cloud);
1322
1613
  const there = (await server.listSessions()).find((session) => session.sessionId === handoff.cloudSessionId || session.sessionFile === cloudSessionFile);
1323
1614
  const cut = there?.isStreaming === true;
1324
1615
  const cloudFile = there?.sessionFile ?? cloudSessionFile;
1616
+ await this.tell(cloud, handoff.cloud, {
1617
+ sessionFile: cloudFile,
1618
+ computer: hostname().replace(/\.local$/, ""),
1619
+ here: handoff.sessionFile,
1620
+ at: handoff.at,
1621
+ back: Date.now()
1622
+ });
1325
1623
  if (there) {
1326
1624
  if (cut) {
1327
1625
  await server.abort(there.sessionId);
1328
1626
  }
1329
1627
  await server.closeSession(there.sessionId);
1330
1628
  }
1331
- const cloudSnap = results(await side.run(HandoffScripts.snapshot(id, "cloud"), cloudRoot));
1629
+ const cloudSnap = results2(await side.run(HandoffScripts.snapshot(id, "cloud"), cloudRoot));
1332
1630
  const result = { sessionFile: handoff.sessionFile, files: "same", later: [] };
1333
1631
  if (cloudSnap.tree !== tree || cloudSnap.head !== head) {
1334
1632
  const sent = posix.join(posix.dirname(cloudSessionFile), `.ta-handoff-${id}.bundle`);
1335
- const made = results(await side.run(HandoffScripts.bundle(sent, [ref(id, "cloud")], [ref(id, "local")]), cloudRoot));
1633
+ const made = results2(await side.run(HandoffScripts.bundle(sent, [ref(id, "cloud")], [ref(id, "local")]), cloudRoot));
1336
1634
  await HandoffTransfer.copy(side, sent, Number(made.size), this.local, bundle);
1337
1635
  await side.run(`rm -f ${q2(sent)}`);
1338
1636
  await this.local.run(HandoffScripts.fetch(bundle, ref(id, "cloud")), root);
1339
- const here = results(await this.local.run(HandoffScripts.snapshot(id, "here"), root));
1637
+ const here = results2(await this.local.run(HandoffScripts.snapshot(id, "here"), root));
1340
1638
  const moved = cloudSnap.head !== head;
1341
1639
  const headHere = here.head === head;
1342
1640
  let target = cloudSnap.tree;
1343
1641
  if (here.tree !== tree) {
1344
- const merged = results(await this.local.run(HandoffScripts.merge(ref(id, "local"), ref(id, "here"), ref(id, "cloud")), root));
1642
+ const merged = results2(await this.local.run(HandoffScripts.merge(ref(id, "local"), ref(id, "here"), ref(id, "cloud")), root));
1345
1643
  if (merged.conflicts) {
1346
1644
  result.files = "conflict";
1347
1645
  result.conflicts = merged.conflicts.split("\t").filter(Boolean);
@@ -1350,25 +1648,26 @@ ${root}`;
1350
1648
  target = merged.tree;
1351
1649
  }
1352
1650
  if (result.files !== "conflict") {
1353
- const landed = results(await this.local.run(HandoffScripts.land(here.tree, target, moved && headHere ? cloudSnap.head : undefined), root));
1651
+ const landed = results2(await this.local.run(HandoffScripts.land(here.tree, target, moved && headHere ? cloudSnap.head : undefined), root));
1354
1652
  if (landed.tree !== target) {
1355
1653
  throw new Error("The files here did not come out as the cloud left them.");
1356
1654
  }
1357
1655
  result.files = here.tree === tree ? "taken" : "merged";
1358
1656
  if (moved && headHere) {
1359
- result.commits = Number(results(await this.local.run(HandoffScripts.count(head, cloudSnap.head), root)).count) || 0;
1657
+ result.commits = Number(results2(await this.local.run(HandoffScripts.count(head, cloudSnap.head), root)).count) || 0;
1360
1658
  } else if (moved) {
1361
1659
  result.ref = ref(id, "cloud");
1362
1660
  }
1363
1661
  }
1364
1662
  }
1365
- const brought = await this.bringConversation(handoff, side, cloudFile, result, cut);
1663
+ const brought = await HandoffReturn.conversation({ host: this.host, local: this.local, temp: this.temp }, handoff, side, cloudFile, result, cut);
1366
1664
  result.sessionFile = brought.sessionFile;
1367
- await this.save((book) => {
1665
+ await this.book.save((book) => {
1368
1666
  book.handoffs = book.handoffs.filter((other) => other.id !== id);
1369
1667
  book.clones[`${handoff.cloud}
1370
1668
  ${root}`] = cloudSnap.head;
1371
1669
  });
1670
+ away?.end();
1372
1671
  if (brought.wasOpen || brought.goOn) {
1373
1672
  const opened = await this.host.openSession({ cwd: handoff.cwd, sessionFile: brought.sessionFile });
1374
1673
  if (brought.goOn) {
@@ -1386,69 +1685,20 @@ ${root}`] = cloudSnap.head;
1386
1685
  });
1387
1686
  return result;
1388
1687
  } catch (error) {
1389
- await this.save((book) => {
1688
+ await this.book.save((book) => {
1390
1689
  book.handoffs = book.handoffs.map((other) => other.id === id ? { ...other, state: "cloud" } : other);
1391
1690
  });
1691
+ away?.there(handoff.cloud, this.remoteOf(handoff));
1692
+ await this.tell(cloud, handoff.cloud, {
1693
+ sessionFile: cloudSessionFile,
1694
+ computer: hostname().replace(/\.local$/, ""),
1695
+ here: handoff.sessionFile,
1696
+ at: handoff.at
1697
+ });
1392
1698
  throw error;
1393
1699
  } finally {
1394
- this.busy.delete(handoff.sessionFile);
1395
- await rm(bundle, { force: true });
1396
- }
1397
- }
1398
- async bringConversation(handoff, side, cloudFile, result, cut) {
1399
- const open2 = (await this.host.listSessions()).find((session) => session.sessionFile === handoff.sessionFile);
1400
- if (open2) {
1401
- await this.host.closeSession(open2.sessionId);
1700
+ await rm2(bundle, { force: true });
1402
1701
  }
1403
- const read = async (file) => {
1404
- const size = Number(results(await side.run(HandoffScripts.size(file))).size);
1405
- const copy = join2(this.temp, `ta-handoff-${handoff.id}-${basename(file)}`);
1406
- await HandoffTransfer.copy(side, file, size, this.local, copy);
1407
- try {
1408
- return HandoffSessions.lines(await readFile2(copy, "utf8"));
1409
- } finally {
1410
- await rm(copy, { force: true });
1411
- }
1412
- };
1413
- const said = (await read(handoff.cloudSessionFile)).slice(handoff.lines ?? 0);
1414
- const other = cloudFile === handoff.cloudSessionFile ? undefined : HandoffSessions.lines(HandoffSessions.relocate((await read(cloudFile)).join(`
1415
- `), handoff.cwd));
1416
- result.later = HandoffSessions.later([...said, ...other ?? []]);
1417
- const before = other ?? [...HandoffSessions.lines(await readFile2(handoff.sessionFile, "utf8")), ...said];
1418
- const goOn = cut || result.later.length > 0 || result.files === "conflict";
1419
- const details = {
1420
- to: "back",
1421
- cloud: handoff.cloud,
1422
- files: result.files,
1423
- ...result.conflicts ? { conflicts: result.conflicts } : {},
1424
- later: result.later
1425
- };
1426
- const note = HandoffSessions.note(before, HandoffTexts.back({
1427
- cloud: handoff.cloud,
1428
- files: result.files,
1429
- conflicts: result.conflicts ?? [],
1430
- ref: result.ref,
1431
- commits: result.commits ?? 0,
1432
- later: result.later,
1433
- goOn
1434
- }), details, !goOn);
1435
- if (said.length) {
1436
- await appendFile2(handoff.sessionFile, `${said.join(`
1437
- `)}
1438
- `);
1439
- }
1440
- let sessionFile = handoff.sessionFile;
1441
- if (other === undefined) {
1442
- await appendFile2(sessionFile, `${note}
1443
- `);
1444
- } else {
1445
- sessionFile = join2(dirname(handoff.sessionFile), basename(cloudFile));
1446
- await writeFile2(sessionFile, `${other.join(`
1447
- `)}
1448
- ${note}
1449
- `);
1450
- }
1451
- return { sessionFile, wasOpen: open2 !== undefined, goOn, note: details };
1452
1702
  }
1453
1703
  async workspace(name) {
1454
1704
  const cloud = this.host.cloud;
@@ -1483,28 +1733,6 @@ ${note}
1483
1733
  const value = async (args) => (await this.local.run(`git ${args} 2>/dev/null || true`, root)).trim() || undefined;
1484
1734
  return { name: await value("config user.name"), email: await value("config user.email"), origin: await value("remote get-url origin") };
1485
1735
  }
1486
- read() {
1487
- this.book ??= this.host.getExtensionData(NAME, BOOK_KEY).then((value) => {
1488
- const book = value ?? {};
1489
- return {
1490
- machine: typeof book.machine === "string" ? book.machine : randomUUID2(),
1491
- handoffs: Array.isArray(book.handoffs) ? book.handoffs : [],
1492
- clones: book.clones && typeof book.clones === "object" ? book.clones : {}
1493
- };
1494
- });
1495
- return this.book;
1496
- }
1497
- save(change) {
1498
- const write = this.writes.then(async () => {
1499
- const book = await this.read();
1500
- change(book);
1501
- await this.host.setExtensionData(NAME, BOOK_KEY, book);
1502
- });
1503
- this.writes = write.catch(() => {
1504
- return;
1505
- });
1506
- return write;
1507
- }
1508
1736
  }
1509
1737
 
1510
1738
  // web-src/host.ts
@@ -1519,6 +1747,9 @@ async function activate(host) {
1519
1747
  handOffAfterTurn: (sessionFile, cloud) => handoffs.handOffAfterTurn(sessionFile, cloud),
1520
1748
  takeBack: (id) => handoffs.takeBack(id),
1521
1749
  away: (sessionFile) => handoffs.away(sessionFile),
1750
+ copy: (copy) => handoffs.copies.copy(copy),
1751
+ wentBack: (sessionFile) => handoffs.copies.wentBack(sessionFile),
1752
+ reach: (cloud, device) => handoffs.reach(cloud, device),
1522
1753
  power: () => auto.power(),
1523
1754
  dispose: () => {
1524
1755
  auto.dispose();