saarthiclaw 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +10 -0
  3. package/dist/chunks/{chunk-EG5A2Q6X.js → chunk-33MUQ6E5.js} +9 -1
  4. package/dist/chunks/{chunk-OS5GVLKA.js → chunk-CGJ4VEUD.js} +1 -1
  5. package/dist/chunks/{chunk-E4DRW4AW.js → chunk-H2FAKNUI.js} +10 -2
  6. package/dist/chunks/{chunk-OICPXSO2.js → chunk-HFMRQTXE.js} +1 -1
  7. package/dist/chunks/{chunk-GX2I7K4S.js → chunk-KAWTUWO2.js} +15 -5
  8. package/dist/chunks/{chunk-VDYO3QC7.js → chunk-N33J57DT.js} +6 -6
  9. package/dist/chunks/{chunk-DSQDVSZS.js → chunk-OF5PQQQ4.js} +6 -6
  10. package/dist/chunks/chunk-R4PMMMD5.js +407 -0
  11. package/dist/chunks/{chunk-SKYTL7AH.js → chunk-S6YZ2A73.js} +17 -8
  12. package/dist/chunks/{chunk-TTT3KK46.js → chunk-SYH37PL6.js} +5 -5
  13. package/dist/chunks/{chunk-ZXVP7JFV.js → chunk-XATEICDJ.js} +11 -13
  14. package/dist/chunks/{chunk-3UFD5346.js → chunk-XT5WAZRV.js} +5 -5
  15. package/dist/chunks/{client-5WRI2PBK.js → client-TI5W2YDP.js} +3 -5
  16. package/dist/chunks/{context-AP3U34DQ.js → context-RKFGCGP7.js} +5 -7
  17. package/dist/chunks/{doctor-O3R2YTRO.js → doctor-ZQICU2F4.js} +11 -6
  18. package/dist/chunks/{errors-ZXTAHCZI.js → errors-OJZTUG74.js} +2 -4
  19. package/dist/chunks/orchestrator-ATA2LHPJ.js +22 -0
  20. package/dist/chunks/{orchestrator-NIDJK4C3.js → orchestrator-NJ7US5XC.js} +9 -11
  21. package/dist/chunks/{orchestrator-KNCW4K57.js → orchestrator-XLVMKC4V.js} +10 -12
  22. package/dist/chunks/{session-CRFC3IEU.js → session-ZC5D2O77.js} +6 -3
  23. package/dist/chunks/{store-KW257WIV.js → store-JG5OKLEO.js} +5 -5
  24. package/dist/chunks/{sync-S2A65FIE.js → sync-ESB3YWI2.js} +7 -9
  25. package/dist/chunks/{team-RBSOK3HT.js → team-PFETXIEC.js} +123 -23
  26. package/dist/chunks/{telegram-JSGRYPIX.js → telegram-IMADPCKR.js} +14 -16
  27. package/dist/chunks/{wakeup-4IP4JXVF.js → wakeup-UX6AM7M6.js} +16 -18
  28. package/dist/chunks/workspace-XERWEYJB.js +281 -0
  29. package/dist/index.js +27 -20
  30. package/package.json +1 -1
  31. package/dist/chunks/chunk-BTFIQWAE.js +0 -185
  32. package/dist/chunks/chunk-G6GCAEKE.js +0 -64
  33. package/dist/chunks/chunk-XTVJWMUH.js +0 -143
  34. package/dist/chunks/orchestrator-JFJU4FGP.js +0 -24
  35. package/dist/chunks/{init-GCJNYE3Y.js → init-5ENYFSX2.js} +3 -3
@@ -3,14 +3,21 @@ import {
3
3
  } from "./chunk-R7ID2QVW.js";
4
4
  import {
5
5
  runTeamSync
6
- } from "./chunk-ZXVP7JFV.js";
7
- import "./chunk-OS5GVLKA.js";
6
+ } from "./chunk-XATEICDJ.js";
7
+ import "./chunk-CGJ4VEUD.js";
8
8
  import "./chunk-QRAFFI5V.js";
9
9
  import {
10
10
  describeTeamMode,
11
11
  getTeamContext,
12
12
  teamClientFor
13
- } from "./chunk-SKYTL7AH.js";
13
+ } from "./chunk-S6YZ2A73.js";
14
+ import {
15
+ LEVEL_LABEL,
16
+ TeamApiError,
17
+ TeamClient
18
+ } from "./chunk-33MUQ6E5.js";
19
+ import "./chunk-HGBZ55ND.js";
20
+ import "./chunk-5WH3FNFK.js";
14
21
  import {
15
22
  KEY_PATTERN,
16
23
  normalizeServer,
@@ -20,24 +27,14 @@ import {
20
27
  removeTeamLink,
21
28
  saveKey,
22
29
  writeTeamLink
23
- } from "./chunk-E4DRW4AW.js";
24
- import "./chunk-HGBZ55ND.js";
25
- import "./chunk-5WH3FNFK.js";
26
- import {
27
- LEVEL_LABEL,
28
- TeamApiError,
29
- TeamClient
30
- } from "./chunk-EG5A2Q6X.js";
31
- import {
32
- UserFacingError
33
- } from "./chunk-G6GCAEKE.js";
34
- import "./chunk-IT46XDPQ.js";
30
+ } from "./chunk-H2FAKNUI.js";
35
31
  import {
32
+ UserFacingError,
36
33
  isSecretPath
37
- } from "./chunk-XTVJWMUH.js";
38
- import "./chunk-BTFIQWAE.js";
34
+ } from "./chunk-R4PMMMD5.js";
39
35
  import "./chunk-2GDAWRT7.js";
40
36
  import "./chunk-MMIJKDOU.js";
37
+ import "./chunk-IT46XDPQ.js";
41
38
 
42
39
  // cli/team.ts
43
40
  import chalk from "chalk";
@@ -174,6 +171,7 @@ Nothing changed. This folder is still ${was}.
174
171
  role: me.role,
175
172
  permissionLevel: me.permissionLevel,
176
173
  projectName: me.project?.name,
174
+ teamAi: Boolean(me.policy?.teamAi),
177
175
  connectedAt: (/* @__PURE__ */ new Date()).toISOString()
178
176
  });
179
177
  const gitignoreChanged = ensureGitignore(session.root, [".saarthiclaw/"]);
@@ -185,8 +183,14 @@ Nothing changed. This folder is still ${was}.
185
183
  console.log(`
186
184
  ${explainLevel(me)}
187
185
  `);
188
- if (!session.config.openrouterApiKey && me.permissionLevel !== "suggest_only") {
189
- console.log(chalk.yellow("One more thing: this folder has no AI key yet, so the agent can't run here.") + chalk.dim(" Add it with ") + chalk.bold("npx saarthiclaw init") + "\n");
186
+ if (me.policy?.teamAi) {
187
+ console.log(chalk.green("🤖 AI: this team uses the Admin's AI key through the dashboard — no AI key is needed on this computer.") + (me.policy.teamAiModel ? chalk.dim(` Model: ${me.policy.teamAiModel}`) : "") + "\n");
188
+ } else if (!session.config.openrouterApiKey && me.permissionLevel !== "suggest_only") {
189
+ if (me.role === "admin") {
190
+ console.log(chalk.yellow("Tip: add a Team AI key on the dashboard (Settings → Team AI) so nobody on the team needs their own AI key.") + "\n");
191
+ } else {
192
+ console.log(chalk.yellow("No AI is available here yet.") + chalk.dim(" Ask the Admin to add a Team AI key on the dashboard (Settings → Team AI), or add your own with ") + chalk.bold("npx saarthiclaw init") + "\n");
193
+ }
190
194
  }
191
195
  if (me.role === "admin") {
192
196
  const share = !session.prompter.interactive || await session.prompter.confirm({
@@ -199,7 +203,8 @@ ${explainLevel(me)}
199
203
  if (link) writeTeamLink(session.root, { ...link, projectName: p.name });
200
204
  console.log(chalk.green(`✓ Dashboard project: ${p.name}`));
201
205
  }
202
- console.log(chalk.dim("\nNext: invite developers with ") + chalk.bold("saarthiclaw team invite <name>") + chalk.dim(" (or on the dashboard → Members).\n"));
206
+ console.log(chalk.dim("\nNext: invite developers with ") + chalk.bold("saarthiclaw team invite <name>") + chalk.dim(" (or on the dashboard → Members)."));
207
+ console.log(chalk.dim("Keep this folder and the website in step: ") + chalk.bold("npx saarthiclaw team watch") + "\n");
203
208
  } else {
204
209
  if (!me.project?.linked) console.log(chalk.yellow("The Admin has not linked a project yet. You can still connect; changes are accepted once they do.\n"));
205
210
  const next = {
@@ -207,7 +212,8 @@ ${explainLevel(me)}
207
212
  needs_approval: 'npx saarthiclaw agent "describe the change" (it waits for the Admin, then applies)',
208
213
  suggest_only: 'npx saarthiclaw team suggest "your idea"'
209
214
  };
210
- console.log(chalk.dim("Next: ") + chalk.bold(next[me.permissionLevel] ?? "npx saarthiclaw") + "\n");
215
+ console.log(chalk.dim("Next: ") + chalk.bold(next[me.permissionLevel] ?? "npx saarthiclaw"));
216
+ console.log(chalk.dim("Get the team's latest code in this folder automatically: ") + chalk.bold("npx saarthiclaw team watch") + "\n");
211
217
  }
212
218
  }
213
219
  async function teamStatus(session) {
@@ -234,6 +240,7 @@ async function teamStatus(session) {
234
240
  }
235
241
  rows.push(["Unread messages", me.unreadMessages ? chalk.cyan(String(me.unreadMessages)) + chalk.dim(" (open the dashboard → Messages)") : "0"]);
236
242
  rows.push(["File changes", me.policy.allowFileModification ? "allowed by the Admin" : chalk.yellow("turned off by the Admin")]);
243
+ rows.push(["AI", me.policy.teamAi ? `team key from the dashboard${me.policy.teamAiModel ? ` (${me.policy.teamAiModel})` : ""}` : session.config.openrouterApiKey ? "your own key" : chalk.yellow("none — ask the Admin for a Team AI key")]);
237
244
  const width = Math.max(...rows.map(([k]) => k.length));
238
245
  for (const [k, v] of rows) console.log(` ${chalk.dim(k.padEnd(width))} ${v}`);
239
246
  console.log(`
@@ -338,7 +345,7 @@ async function teamInbox(session) {
338
345
  });
339
346
  if (what === "back") continue;
340
347
  if (what === "run") {
341
- const { runAgentTask } = await import("./orchestrator-NIDJK4C3.js");
348
+ const { runAgentTask } = await import("./orchestrator-NJ7US5XC.js");
342
349
  const task = `${item.message}${item.adminNote ? `
343
350
 
344
351
  Admin note: ${item.adminNote}` : ""}
@@ -366,6 +373,98 @@ async function teamDisconnect(session) {
366
373
  await getTeamContext(session, { refresh: true });
367
374
  console.log(chalk.green("\n✓ Disconnected. SaarthiClaw now works solo in this project.\n"));
368
375
  }
376
+ async function teamWatch(session, opts) {
377
+ const { syncWorkspace, readWorkspaceState } = await import("./workspace-XERWEYJB.js");
378
+ const { client, link } = requireLinked(session);
379
+ const me = await client.whoami();
380
+ const canPush = me.role === "admin" || me.permissionLevel === "trusted";
381
+ let prefer;
382
+ if (opts.prefer) {
383
+ const p = opts.prefer.trim().toLowerCase();
384
+ if (p !== "website" && p !== "laptop") throw new UserFacingError(`Unknown --prefer "${opts.prefer}".`, "Use --prefer website or --prefer laptop.");
385
+ if (p === "laptop" && !canPush) throw new UserFacingError("Only the Admin and Trusted members can send this folder's version to the website.", "Use --prefer website, or send changes for review with the agent.");
386
+ prefer = p;
387
+ }
388
+ const seconds = Math.min(60, Math.max(1, Number.parseFloat(opts.interval ?? "2") || 2));
389
+ console.log(chalk.bold(`
390
+ 🔄 Syncing this folder with the team website (${link.server})`));
391
+ console.log(chalk.dim(canPush ? " Two-way: approved website changes come down here; your edits in this folder go up to the website (as a version you can revert)." : " One-way: approved website changes come down here. Your own edits go through the agent / website for review."));
392
+ console.log(chalk.dim(" Only text files are synced (no node_modules, build folders, images or secrets like .env).\n"));
393
+ const stamp = () => chalk.dim((/* @__PURE__ */ new Date()).toLocaleTimeString());
394
+ const shownConflicts = /* @__PURE__ */ new Set();
395
+ let offline = false;
396
+ const round = async () => {
397
+ const report = await syncWorkspace(session.root, client, { canPush, prefer });
398
+ if (report.needsChoice) {
399
+ const { differing, onlyLaptop, onlyWebsite } = report.needsChoice;
400
+ console.log(chalk.yellow("This folder and the website have different versions of the project:"));
401
+ if (differing.length) console.log(` • ${differing.length} file(s) differ: ${differing.slice(0, 8).join(", ")}${differing.length > 8 ? ", …" : ""}`);
402
+ if (onlyLaptop.length) console.log(` • ${onlyLaptop.length} file(s) only in this folder: ${onlyLaptop.slice(0, 8).join(", ")}${onlyLaptop.length > 8 ? ", …" : ""}`);
403
+ if (onlyWebsite.length) console.log(` • ${onlyWebsite.length} file(s) only on the website: ${onlyWebsite.slice(0, 8).join(", ")}${onlyWebsite.length > 8 ? ", …" : ""}`);
404
+ if (!session.prompter.interactive) throw new UserFacingError("Choose which version to keep.", `Run again with --prefer website${canPush ? " or --prefer laptop" : ""}.`);
405
+ const options = [
406
+ { value: "website", label: "Use the website version", hint: "overwrites the differing files in this folder" }
407
+ ];
408
+ if (canPush) options.push({ value: "laptop", label: "Use this folder's version", hint: "sends it to the website as a new version (revertable)" });
409
+ options.push({ value: "cancel", label: "Cancel" });
410
+ const choice = await session.prompter.select({ message: "Which version should both sides use?", options });
411
+ if (choice === "cancel") return false;
412
+ prefer = choice;
413
+ return round();
414
+ }
415
+ for (const p of report.pulled) console.log(`${stamp()} ${chalk.cyan("⬇")} ${p} ${chalk.dim("(from the website)")}`);
416
+ for (const p of report.deletedLocal) console.log(`${stamp()} ${chalk.cyan("⬇")} ${p} ${chalk.dim("deleted (from the website)")}`);
417
+ if (report.pushed.length) console.log(`${stamp()} ${chalk.green("⬆")} ${report.pushed.join(", ")} ${chalk.dim(`→ website${report.versionNote ? ` (${report.versionNote})` : ""}`)}`);
418
+ if (report.skippedDeletes) console.log(chalk.yellow(`${stamp()} ⚠ ${report.skippedDeletes} files are missing from this folder. Not deleting them on the website — if that was on purpose, delete them on the website instead.`));
419
+ for (const p of report.conflicts) {
420
+ if (shownConflicts.has(p)) continue;
421
+ shownConflicts.add(p);
422
+ console.log(chalk.yellow(`${stamp()} ⚠ ${p} changed both here and on the website. Your file was left as it is.`));
423
+ console.log(chalk.dim(` Keep the website's: run with --prefer website.${canPush ? " Keep yours: --prefer laptop." : ""} Or compare on the website (Code / History).`));
424
+ }
425
+ return true;
426
+ };
427
+ if (opts.once) {
428
+ if (await round()) {
429
+ const st = readWorkspaceState(session.root);
430
+ console.log(chalk.green(`
431
+ ✓ In sync with website version #${st.lastVersionId}.`) + "\n");
432
+ }
433
+ return;
434
+ }
435
+ let stop = false;
436
+ const onSig = () => {
437
+ stop = true;
438
+ console.log(chalk.dim("\nStopped syncing."));
439
+ };
440
+ process.once("SIGINT", onSig);
441
+ console.log(chalk.dim("Watching… press Ctrl+C to stop.\n"));
442
+ try {
443
+ while (!stop) {
444
+ try {
445
+ const okRound = await round();
446
+ if (!okRound) return;
447
+ if (offline) {
448
+ console.log(chalk.green(`${stamp()} ✓ Connected again.`));
449
+ offline = false;
450
+ }
451
+ if (prefer) prefer = void 0;
452
+ } catch (e) {
453
+ if (e instanceof UserFacingError && !(e instanceof TeamApiError)) {
454
+ if (!offline) console.log(chalk.yellow(`${stamp()} ⚠ ${e.message} Retrying…`));
455
+ offline = true;
456
+ } else if (e instanceof TeamApiError && (e.status === 401 || e.status === 403)) {
457
+ throw e;
458
+ } else {
459
+ console.log(chalk.yellow(`${stamp()} ⚠ ${e.message}`));
460
+ }
461
+ }
462
+ for (let i = 0; i < seconds * 10 && !stop; i++) await new Promise((r) => setTimeout(r, 100));
463
+ }
464
+ } finally {
465
+ process.removeListener("SIGINT", onSig);
466
+ }
467
+ }
369
468
  export {
370
469
  DEFAULT_SERVER,
371
470
  teamConnect,
@@ -374,5 +473,6 @@ export {
374
473
  teamInvite,
375
474
  teamStatus,
376
475
  teamSuggest,
377
- teamSync
476
+ teamSync,
477
+ teamWatch
378
478
  };
@@ -1,24 +1,24 @@
1
1
  import {
2
2
  generatePlan,
3
3
  stepPrompt
4
- } from "./chunk-VDYO3QC7.js";
4
+ } from "./chunk-N33J57DT.js";
5
5
  import {
6
6
  createWebTools
7
- } from "./chunk-OICPXSO2.js";
7
+ } from "./chunk-HFMRQTXE.js";
8
8
  import {
9
9
  createAgentTools,
10
10
  createReadOnlyTools,
11
11
  dedupeReadOnlyTools,
12
12
  finishOnLastStep
13
- } from "./chunk-DSQDVSZS.js";
13
+ } from "./chunk-OF5PQQQ4.js";
14
14
  import {
15
15
  ToolExecutor
16
- } from "./chunk-OS5GVLKA.js";
16
+ } from "./chunk-CGJ4VEUD.js";
17
17
  import {
18
18
  groupPending
19
19
  } from "./chunk-QRAFFI5V.js";
20
- import "./chunk-SKYTL7AH.js";
21
- import "./chunk-E4DRW4AW.js";
20
+ import "./chunk-S6YZ2A73.js";
21
+ import "./chunk-33MUQ6E5.js";
22
22
  import {
23
23
  waitForInterrupt
24
24
  } from "./chunk-HGBZ55ND.js";
@@ -27,21 +27,18 @@ import {
27
27
  createTracker,
28
28
  instructionsFor,
29
29
  readOnlyAgentConfig
30
- } from "./chunk-GX2I7K4S.js";
30
+ } from "./chunk-KAWTUWO2.js";
31
31
  import "./chunk-5WH3FNFK.js";
32
- import "./chunk-EG5A2Q6X.js";
33
- import {
34
- UserFacingError
35
- } from "./chunk-G6GCAEKE.js";
36
- import "./chunk-IT46XDPQ.js";
37
- import "./chunk-XTVJWMUH.js";
32
+ import "./chunk-H2FAKNUI.js";
38
33
  import {
39
34
  AI_MAX_RETRIES,
40
35
  MissingApiKeyError,
36
+ UserFacingError,
41
37
  mapAiError
42
- } from "./chunk-BTFIQWAE.js";
38
+ } from "./chunk-R4PMMMD5.js";
43
39
  import "./chunk-2GDAWRT7.js";
44
40
  import "./chunk-MMIJKDOU.js";
41
+ import "./chunk-IT46XDPQ.js";
45
42
 
46
43
  // modes/telegram/index.ts
47
44
  import chalk from "chalk";
@@ -414,7 +411,7 @@ ${list}`);
414
411
 
415
412
  // modes/telegram/index.ts
416
413
  async function runTelegramMode(session) {
417
- const { getTeamContext } = await import("./context-AP3U34DQ.js");
414
+ const { getTeamContext } = await import("./context-RKFGCGP7.js");
418
415
  const team = await getTeamContext(session);
419
416
  if (team.mode === "needs_approval" || team.mode === "suggest_only") {
420
417
  throw new UserFacingError(
@@ -436,7 +433,8 @@ async function runTelegramMode(session) {
436
433
  "Message @userinfobot on Telegram to find it."
437
434
  );
438
435
  }
439
- if (!session.config.openrouterApiKey) throw new MissingApiKeyError();
436
+ const { hasAiAccess } = await import("./session-ZC5D2O77.js");
437
+ if (!hasAiAccess(session)) throw new MissingApiKeyError();
440
438
  console.log(chalk.bold("\n📱 Telegram Mode\n"));
441
439
  const { Telegraf } = await import("telegraf");
442
440
  const bot = new Telegraf(token);
@@ -1,34 +1,32 @@
1
1
  import {
2
2
  runAgentMode
3
- } from "./chunk-3UFD5346.js";
3
+ } from "./chunk-XT5WAZRV.js";
4
4
  import {
5
5
  runAskMode
6
- } from "./chunk-TTT3KK46.js";
6
+ } from "./chunk-SYH37PL6.js";
7
7
  import {
8
8
  runPlanMode
9
- } from "./chunk-VDYO3QC7.js";
10
- import "./chunk-OICPXSO2.js";
11
- import "./chunk-DSQDVSZS.js";
12
- import "./chunk-OS5GVLKA.js";
9
+ } from "./chunk-N33J57DT.js";
10
+ import "./chunk-HFMRQTXE.js";
11
+ import "./chunk-OF5PQQQ4.js";
12
+ import "./chunk-CGJ4VEUD.js";
13
13
  import "./chunk-QRAFFI5V.js";
14
- import "./chunk-SKYTL7AH.js";
15
- import "./chunk-E4DRW4AW.js";
14
+ import "./chunk-S6YZ2A73.js";
15
+ import "./chunk-33MUQ6E5.js";
16
16
  import {
17
17
  RunCancelledError
18
18
  } from "./chunk-HGBZ55ND.js";
19
- import "./chunk-GX2I7K4S.js";
19
+ import "./chunk-KAWTUWO2.js";
20
20
  import "./chunk-5WH3FNFK.js";
21
- import "./chunk-EG5A2Q6X.js";
21
+ import "./chunk-H2FAKNUI.js";
22
22
  import {
23
23
  reportError
24
- } from "./chunk-G6GCAEKE.js";
24
+ } from "./chunk-R4PMMMD5.js";
25
+ import "./chunk-2GDAWRT7.js";
26
+ import "./chunk-MMIJKDOU.js";
25
27
  import {
26
28
  UserCancelledError
27
29
  } from "./chunk-IT46XDPQ.js";
28
- import "./chunk-XTVJWMUH.js";
29
- import "./chunk-BTFIQWAE.js";
30
- import "./chunk-2GDAWRT7.js";
31
- import "./chunk-MMIJKDOU.js";
32
30
 
33
31
  // tui/wakeup.ts
34
32
  import chalk2 from "chalk";
@@ -124,15 +122,15 @@ async function runWakeup(session) {
124
122
  }
125
123
  if (choice === MainMenu.Telegram) {
126
124
  await runModeSafely(session, async () => {
127
- const { runTelegramMode } = await import("./telegram-JSGRYPIX.js");
125
+ const { runTelegramMode } = await import("./telegram-IMADPCKR.js");
128
126
  await runTelegramMode(session);
129
127
  });
130
128
  }
131
129
  }
132
130
  }
133
131
  async function runTeamMenu(session) {
134
- const team = await import("./team-RBSOK3HT.js");
135
- const { readTeamLink } = await import("./store-KW257WIV.js");
132
+ const team = await import("./team-PFETXIEC.js");
133
+ const { readTeamLink } = await import("./store-JG5OKLEO.js");
136
134
  while (true) {
137
135
  const link = readTeamLink(session.root, session.env ?? process.env);
138
136
  const options = link ? [
@@ -0,0 +1,281 @@
1
+ import {
2
+ TeamApiError
3
+ } from "./chunk-33MUQ6E5.js";
4
+ import {
5
+ sha256Hex
6
+ } from "./chunk-H2FAKNUI.js";
7
+ import {
8
+ isSecretPath
9
+ } from "./chunk-R4PMMMD5.js";
10
+ import "./chunk-2GDAWRT7.js";
11
+ import {
12
+ projectStateDir
13
+ } from "./chunk-MMIJKDOU.js";
14
+ import "./chunk-IT46XDPQ.js";
15
+
16
+ // team/workspace.ts
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", "coverage", "__pycache__", "venv", ".venv", "vendor"]);
20
+ var BINARY_EXT = /\.(png|jpe?g|gif|webp|ico|bmp|pdf|zip|gz|tar|rar|7z|woff2?|ttf|otf|eot|mp3|mp4|wav|mov|avi|exe|dll|so|dylib|class|jar|db|sqlite|lockb)$/i;
21
+ var MAX_FILE = 1024 * 1024;
22
+ var MAX_FILES = 2e3;
23
+ function workspaceStateFile(root) {
24
+ return path.join(projectStateDir(root), "workspace-sync.json");
25
+ }
26
+ function readWorkspaceState(root) {
27
+ try {
28
+ const raw = JSON.parse(fs.readFileSync(workspaceStateFile(root), "utf8"));
29
+ return {
30
+ lastVersionId: Number.isInteger(raw.lastVersionId) ? Number(raw.lastVersionId) : 0,
31
+ files: raw.files && typeof raw.files === "object" ? raw.files : {},
32
+ conflicts: raw.conflicts && typeof raw.conflicts === "object" ? raw.conflicts : {}
33
+ };
34
+ } catch {
35
+ return { lastVersionId: 0, files: {}, conflicts: {} };
36
+ }
37
+ }
38
+ function writeWorkspaceState(root, state) {
39
+ const file = workspaceStateFile(root);
40
+ fs.mkdirSync(path.dirname(file), { recursive: true });
41
+ const tmp = `${file}.tmp`;
42
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2));
43
+ fs.renameSync(tmp, file);
44
+ }
45
+ function resetWorkspaceState(root) {
46
+ try {
47
+ fs.unlinkSync(workspaceStateFile(root));
48
+ } catch {
49
+ }
50
+ }
51
+ function scanLocal(root) {
52
+ const out = /* @__PURE__ */ new Map();
53
+ const walk = (dir, rel) => {
54
+ let entries;
55
+ try {
56
+ entries = fs.readdirSync(dir, { withFileTypes: true });
57
+ } catch {
58
+ return;
59
+ }
60
+ for (const ent of entries) {
61
+ if (out.size >= MAX_FILES) return;
62
+ const relPath = rel ? `${rel}/${ent.name}` : ent.name;
63
+ if (ent.isSymbolicLink()) continue;
64
+ if (ent.isDirectory()) {
65
+ if (ent.name.startsWith(".") || SKIP_DIRS.has(ent.name)) continue;
66
+ walk(path.join(dir, ent.name), relPath);
67
+ } else if (ent.isFile()) {
68
+ if (!isSyncable(relPath)) continue;
69
+ const full = path.join(dir, ent.name);
70
+ try {
71
+ if (fs.statSync(full).size > MAX_FILE) continue;
72
+ const text = fs.readFileSync(full, "utf8");
73
+ if (text.includes("\0")) continue;
74
+ out.set(relPath, text);
75
+ } catch {
76
+ }
77
+ }
78
+ }
79
+ };
80
+ walk(root, "");
81
+ return out;
82
+ }
83
+ function isSyncable(relPosix) {
84
+ if (!relPosix || relPosix.split("/").some((p) => p === ".." || p.startsWith(".") || SKIP_DIRS.has(p))) return false;
85
+ if (isSecretPath(relPosix) || BINARY_EXT.test(relPosix)) return false;
86
+ return true;
87
+ }
88
+ function resolveInside(root, rel) {
89
+ const full = path.resolve(root, ...rel.split("/"));
90
+ const r = path.resolve(root);
91
+ if (full !== r && !full.startsWith(r + path.sep)) throw new Error(`Refusing a path outside the project: ${rel}`);
92
+ return full;
93
+ }
94
+ function writeLocal(root, rel, content) {
95
+ if (!isSyncable(rel)) return;
96
+ const full = resolveInside(root, rel);
97
+ if (content === null) {
98
+ try {
99
+ fs.unlinkSync(full);
100
+ } catch {
101
+ }
102
+ let dir = path.dirname(full);
103
+ while (dir !== path.resolve(root) && dir.startsWith(path.resolve(root))) {
104
+ try {
105
+ if (fs.readdirSync(dir).length) break;
106
+ fs.rmdirSync(dir);
107
+ } catch {
108
+ break;
109
+ }
110
+ dir = path.dirname(dir);
111
+ }
112
+ return;
113
+ }
114
+ fs.mkdirSync(path.dirname(full), { recursive: true });
115
+ const tmp = `${full}.saarthiclaw-tmp`;
116
+ fs.writeFileSync(tmp, content, "utf8");
117
+ fs.renameSync(tmp, full);
118
+ }
119
+ var hashOf = (text) => text === void 0 || text === null ? null : sha256Hex(text);
120
+ async function syncWorkspace(root, client, opts) {
121
+ const state = readWorkspaceState(root);
122
+ const report = { pulled: [], pushed: [], deletedLocal: [], conflicts: [] };
123
+ const local = scanLocal(root);
124
+ if (state.lastVersionId === 0 && Object.keys(state.files).length === 0) {
125
+ const first = await firstSync(root, client, state, local, opts, report);
126
+ writeWorkspaceState(root, state);
127
+ if (!first) return report;
128
+ return report;
129
+ }
130
+ const changes = await client.workspace(state.lastVersionId);
131
+ if (changes.snapshot) {
132
+ const server = new Map(changes.snapshot.map((f) => [f.path, f.content]));
133
+ const paths = /* @__PURE__ */ new Set([...server.keys(), ...Object.keys(state.files)]);
134
+ for (const p of paths) applyServerFile(root, state, local, p, server.has(p) ? server.get(p) : null, opts, report);
135
+ } else {
136
+ for (const v of changes.versions ?? []) for (const f of v.files) applyServerFile(root, state, local, f.path, f.after, opts, report);
137
+ }
138
+ state.lastVersionId = changes.latestVersionId;
139
+ writeWorkspaceState(root, state);
140
+ if (opts.canPush) await pushLocal(root, client, state, scanLocal(root), opts, report);
141
+ writeWorkspaceState(root, state);
142
+ return report;
143
+ }
144
+ function applyServerFile(root, state, local, p, after, opts, report) {
145
+ if (!isSyncable(p)) return;
146
+ const localText = local.has(p) ? local.get(p) : null;
147
+ const localHash = hashOf(localText), afterHash = hashOf(after), recorded = state.files[p] ?? null;
148
+ if (localHash === afterHash) {
149
+ if (afterHash) state.files[p] = afterHash;
150
+ else delete state.files[p];
151
+ delete state.conflicts[p];
152
+ return;
153
+ }
154
+ const untouched = localHash === recorded;
155
+ if (untouched || opts.prefer === "website") {
156
+ writeLocal(root, p, after);
157
+ if (after === null) {
158
+ delete state.files[p];
159
+ local.delete(p);
160
+ report.deletedLocal.push(p);
161
+ } else {
162
+ state.files[p] = afterHash;
163
+ local.set(p, after);
164
+ report.pulled.push(p);
165
+ }
166
+ delete state.conflicts[p];
167
+ return;
168
+ }
169
+ if (opts.prefer === "laptop" && opts.canPush) {
170
+ state.conflicts[p] = afterHash ?? "deleted";
171
+ return;
172
+ }
173
+ state.conflicts[p] = afterHash ?? "deleted";
174
+ report.conflicts.push(p);
175
+ }
176
+ async function pushLocal(root, client, state, local, opts, report) {
177
+ const changes = [];
178
+ const paths = /* @__PURE__ */ new Set([...local.keys(), ...Object.keys(state.files)]);
179
+ for (const p of paths) {
180
+ const text = local.has(p) ? local.get(p) : null;
181
+ const h = hashOf(text), recorded = state.files[p] ?? null;
182
+ if (h === recorded) continue;
183
+ if (state.conflicts[p] !== void 0) {
184
+ if (opts.prefer !== "laptop") continue;
185
+ const serverHash = state.conflicts[p] === "deleted" ? null : state.conflicts[p];
186
+ changes.push({ path: p, content: text, baseHash: serverHash });
187
+ continue;
188
+ }
189
+ changes.push({ path: p, content: text, baseHash: recorded });
190
+ }
191
+ if (!changes.length) return;
192
+ const deletes = changes.filter((c) => c.content === null).length;
193
+ const max = opts.maxDeletes ?? 25;
194
+ if (deletes > max && deletes > Object.keys(state.files).length / 2) {
195
+ report.skippedDeletes = deletes;
196
+ const keep = changes.filter((c) => c.content !== null);
197
+ if (!keep.length) return;
198
+ changes.length = 0;
199
+ changes.push(...keep);
200
+ }
201
+ try {
202
+ const res = await client.pushWorkspace(changes.slice(0, MAX_FILES));
203
+ for (const c of changes) {
204
+ if (c.content === null) delete state.files[c.path];
205
+ else state.files[c.path] = sha256Hex(c.content);
206
+ delete state.conflicts[c.path];
207
+ report.pushed.push(c.path);
208
+ }
209
+ if (res.version) report.versionNote = `version #${res.version.id}`;
210
+ } catch (e) {
211
+ if (e instanceof TeamApiError && e.code === "CONFLICT") {
212
+ for (const c of changes) if (!report.conflicts.includes(c.path)) report.conflicts.push(c.path);
213
+ return;
214
+ }
215
+ throw e;
216
+ }
217
+ }
218
+ async function firstSync(root, client, state, local, opts, report) {
219
+ const snap = await client.workspace(0);
220
+ const server = new Map((snap.snapshot ?? []).map((f) => [f.path, f.content]));
221
+ const differing = [], onlyLaptop = [], onlyWebsite = [];
222
+ for (const [p, c] of server) {
223
+ if (!isSyncable(p)) continue;
224
+ if (!local.has(p)) onlyWebsite.push(p);
225
+ else if (local.get(p) !== c) differing.push(p);
226
+ }
227
+ for (const p of local.keys()) if (!server.has(p)) onlyLaptop.push(p);
228
+ const websiteEmpty = server.size === 0;
229
+ const needChoice = differing.length > 0 || onlyLaptop.length > 0 && !websiteEmpty;
230
+ if (needChoice && !opts.prefer) {
231
+ report.needsChoice = { differing, onlyLaptop, onlyWebsite };
232
+ return false;
233
+ }
234
+ const laptopWins = opts.prefer === "laptop" || websiteEmpty && opts.canPush;
235
+ if (laptopWins && !opts.canPush) throw new Error("Only the Admin and Trusted members can send this folder to the website.");
236
+ for (const [p, c] of server) if (local.get(p) === c) state.files[p] = sha256Hex(c);
237
+ if (laptopWins) {
238
+ const changes = [];
239
+ for (const p of [...differing, ...onlyLaptop]) changes.push({ path: p, content: local.get(p), baseHash: hashOf(server.get(p)) });
240
+ for (const p of onlyWebsite) {
241
+ writeLocal(root, p, server.get(p));
242
+ state.files[p] = sha256Hex(server.get(p));
243
+ report.pulled.push(p);
244
+ }
245
+ if (changes.length) {
246
+ const res = await client.pushWorkspace(changes, "Synced from the laptop folder");
247
+ for (const c of changes) {
248
+ state.files[c.path] = sha256Hex(c.content);
249
+ report.pushed.push(c.path);
250
+ }
251
+ if (res.version) report.versionNote = `version #${res.version.id}`;
252
+ }
253
+ } else {
254
+ for (const p of [...differing, ...onlyWebsite]) {
255
+ writeLocal(root, p, server.get(p));
256
+ state.files[p] = sha256Hex(server.get(p));
257
+ report.pulled.push(p);
258
+ }
259
+ if (opts.canPush && onlyLaptop.length) {
260
+ const changes = onlyLaptop.map((p) => ({ path: p, content: local.get(p), baseHash: null }));
261
+ const res = await client.pushWorkspace(changes, "Synced from the laptop folder");
262
+ for (const c of changes) {
263
+ state.files[c.path] = sha256Hex(c.content);
264
+ report.pushed.push(c.path);
265
+ }
266
+ if (res.version) report.versionNote = `version #${res.version.id}`;
267
+ }
268
+ }
269
+ const after = await client.workspace(0);
270
+ state.lastVersionId = after.latestVersionId;
271
+ return true;
272
+ }
273
+ export {
274
+ isSyncable,
275
+ readWorkspaceState,
276
+ resetWorkspaceState,
277
+ scanLocal,
278
+ syncWorkspace,
279
+ workspaceStateFile,
280
+ writeWorkspaceState
281
+ };