friend-assistant 0.1.110 → 0.1.112

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/dist/BUILD.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "friend-assistant",
3
- "version": "0.1.110",
4
- "builtAt": "2026-11-27T17:39:26.709Z"
3
+ "version": "0.1.112",
4
+ "builtAt": "2026-11-27T18:06:56.316Z"
5
5
  }
package/dist/friend.mjs CHANGED
@@ -22090,10 +22090,14 @@ if ($got -ne $agentSha) {
22090
22090
  }
22091
22091
  Move-Item -Force $part $agent
22092
22092
 
22093
- # 3. start at every logon, and again after a crash or an update
22093
+ # 3. start at every logon, and every five minutes if it is not running (after a crash or an update; while it runs the task ignores the trigger)
22094
22094
  $who = $env:USERDOMAIN + '\\' + $env:USERNAME
22095
- $action = New-ScheduledTaskAction -Execute $nodeExe -Argument ($q + $agent + $q) -WorkingDirectory $dir
22096
- $trigger = New-ScheduledTaskTrigger -AtLogOn -User $who
22095
+ # node.exe is a console program and would open a terminal window at every logon: Windows Script Host starts it with no window at all
22096
+ $vbs = Join-Path $dir 'run.vbs'
22097
+ $vbsLines = @('Set s = CreateObject(' + $q + 'WScript.Shell' + $q + ')', ('s.CurrentDirectory = ' + $q + $dir + $q), ('rc = s.Run(' + $q + $q + $q + $nodeExe + $q + $q + ' ' + $q + $q + $agent + $q + $q + $q + ', 0, True)'), 'WScript.Quit rc')
22098
+ [IO.File]::WriteAllText($vbs, (($vbsLines -join [Environment]::NewLine) + [Environment]::NewLine), [Text.Encoding]::Default)
22099
+ $action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('//B //Nologo ' + $q + $vbs + $q) -WorkingDirectory $dir
22100
+ $trigger = @((New-ScheduledTaskTrigger -AtLogOn -User $who), (New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(2)) -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650)))
22097
22101
  $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew
22098
22102
  $principal = New-ScheduledTaskPrincipal -UserId $who -LogonType Interactive -RunLevel Limited
22099
22103
  Register-ScheduledTask -TaskName $task -Action $action -Trigger $trigger -Settings $settings -Principal $principal -Force | Out-Null
@@ -27330,6 +27334,7 @@ var DeckStore = class {
27330
27334
  import { createHash as createHash14, randomBytes as randomBytes17, timingSafeEqual as timingSafeEqual5 } from "node:crypto";
27331
27335
  var CODE_TTL_MS = 10 * 6e4;
27332
27336
  var ACCESS_TTL_MS = 60 * 6e4;
27337
+ var REFRESH_GRACE_MS = 15 * 6e4;
27333
27338
  var ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
27334
27339
  var sha = (s) => createHash14("sha256").update(s).digest("hex");
27335
27340
  var token = () => randomBytes17(32).toString("base64url");
@@ -27399,8 +27404,14 @@ var PcEnroll = class {
27399
27404
  const h = sha(refresh2);
27400
27405
  const cur = this.db.prepare("select * from pc_tokens where refresh_hash = ?").get(h);
27401
27406
  if (!cur) {
27402
- const old = this.db.prepare("select pc_id from pc_tokens where previous_refresh_hash = ?").get(h);
27403
- if (old) this.store.revoke(old.pc_id);
27407
+ const old = this.db.prepare("select id, pc_id, created_at from pc_tokens where previous_refresh_hash = ?").get(h);
27408
+ if (old) {
27409
+ const pc3 = this.store.get(old.pc_id);
27410
+ if (pc3 && !pc3.revoked && this.clock() - old.created_at < REFRESH_GRACE_MS) {
27411
+ return this.issue(pc3.id, h);
27412
+ }
27413
+ this.store.revoke(old.pc_id);
27414
+ }
27404
27415
  return { error: "That sign-in is no longer valid. Add the PC again." };
27405
27416
  }
27406
27417
  const pc2 = this.store.get(cur.pc_id);
@@ -29511,7 +29522,7 @@ function currentSelf() {
29511
29522
  // ../server/src/system/npm.ts
29512
29523
  import { spawn as spawn11 } from "node:child_process";
29513
29524
  var PACKAGE = "friend-assistant";
29514
- var runningVersion = () => true ? "0.1.110" : "development";
29525
+ var runningVersion = () => true ? "0.1.112" : "development";
29515
29526
  async function npmLatest(fetchFn = fetch, timeoutMs = 1e4) {
29516
29527
  try {
29517
29528
  const res = await fetchFn(`https://registry.npmjs.org/${PACKAGE}/latest`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
@@ -35503,7 +35514,7 @@ import { appendFileSync } from "node:fs";
35503
35514
  import { join as join44 } from "node:path";
35504
35515
  var PACKAGE2 = "friend-assistant";
35505
35516
  var real2 = {
35506
- current: () => true ? "0.1.110" : "development",
35517
+ current: () => true ? "0.1.112" : "development",
35507
35518
  latest: () => new Promise((resolve13) => {
35508
35519
  const child = crossSpawn5("npm", ["view", PACKAGE2, "version", "--prefer-online"], { stdio: ["ignore", "pipe", "ignore"] });
35509
35520
  let out = "";
@@ -35821,7 +35832,7 @@ async function run2(argv, io2) {
35821
35832
  case "version":
35822
35833
  case "--version":
35823
35834
  case "-v":
35824
- io2.out(true ? "0.1.110" : "development");
35835
+ io2.out(true ? "0.1.112" : "development");
35825
35836
  return 0;
35826
35837
  case "lan":
35827
35838
  return await lanCommand(rest, io2);
@@ -7108,11 +7108,11 @@ var require_xterm_headless = __commonJS({
7108
7108
  });
7109
7109
 
7110
7110
  // ../pc-agent/src/main.ts
7111
- var import_node_child_process3 = require("node:child_process");
7111
+ var import_node_child_process4 = require("node:child_process");
7112
7112
  var import_node_crypto2 = require("node:crypto");
7113
- var import_node_fs4 = require("node:fs");
7113
+ var import_node_fs5 = require("node:fs");
7114
7114
  var import_node_os3 = require("node:os");
7115
- var import_node_path4 = require("node:path");
7115
+ var import_node_path5 = require("node:path");
7116
7116
 
7117
7117
  // ../../node_modules/.pnpm/ws@8.22.0/node_modules/ws/wrapper.mjs
7118
7118
  var import_stream = __toESM(require_stream(), 1);
@@ -28889,7 +28889,7 @@ var import_node_crypto = require("node:crypto");
28889
28889
  var json2 = { "content-type": "application/json" };
28890
28890
  async function signIn(d) {
28891
28891
  const f = d.fetch ?? fetch;
28892
- const sleep = d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
28892
+ const sleep2 = d.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
28893
28893
  const verifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
28894
28894
  const challenge = (0, import_node_crypto.createHash)("sha256").update(verifier).digest("base64url");
28895
28895
  const base = d.server.replace(/\/+$/, "");
@@ -28899,7 +28899,7 @@ async function signIn(d) {
28899
28899
  d.show(`${base}${s.verifyPath ?? `/pc/approve?code=${s.userCode}`}`, s.userCode);
28900
28900
  const deadline = Date.now() + (d.maxWaitMs ?? (s.expiresIn ?? 600) * 1e3);
28901
28901
  for (; ; ) {
28902
- await sleep(Math.max(1, s.interval ?? 3) * 1e3);
28902
+ await sleep2(Math.max(1, s.interval ?? 3) * 1e3);
28903
28903
  if (Date.now() > deadline) throw new Error("The code was not approved in time. Run the install command again.");
28904
28904
  const r = await f(`${base}/api/pc/enroll/token`, { method: "POST", headers: json2, body: JSON.stringify({ deviceCode: s.deviceCode, verifier }) });
28905
28905
  const body = await r.json().catch(() => ({}));
@@ -30930,9 +30930,117 @@ function toTask(r) {
30930
30930
  return { id: Number(r.id), title: String(r.title), state: r.state, note: String(r.note ?? ""), createdAt: Number(r.created_at), startedAt: r.started_at === null ? null : Number(r.started_at), finishedAt: r.finished_at === null ? null : Number(r.finished_at) };
30931
30931
  }
30932
30932
 
30933
- // ../pc-agent/src/main.ts
30934
- var VERSION = "0.1.110";
30933
+ // ../pc-agent/src/watchdog.ts
30934
+ var import_node_child_process3 = require("node:child_process");
30935
+ var import_node_fs4 = require("node:fs");
30936
+ var import_node_path4 = require("node:path");
30935
30937
  var TASK = "Friend PC Agent";
30938
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30939
+ function runningAgent(pid) {
30940
+ try {
30941
+ process.kill(pid, 0);
30942
+ } catch (e) {
30943
+ if (e.code !== "EPERM") return false;
30944
+ }
30945
+ if (process.platform !== "win32") return true;
30946
+ try {
30947
+ return /node\.exe/i.test((0, import_node_child_process3.execFileSync)("tasklist.exe", ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"], { windowsHide: true, encoding: "utf8", timeout: 8e3 }));
30948
+ } catch {
30949
+ return true;
30950
+ }
30951
+ }
30952
+ async function takeLock(dir, log, waitMs = 8e3) {
30953
+ const file2 = (0, import_node_path4.join)(dir, "agent.pid");
30954
+ const deadline = Date.now() + waitMs;
30955
+ for (; ; ) {
30956
+ let other = 0;
30957
+ try {
30958
+ other = Number((0, import_node_fs4.readFileSync)(file2, "utf8").trim()) || 0;
30959
+ } catch {
30960
+ }
30961
+ if (!other || other === process.pid || !runningAgent(other)) break;
30962
+ if (Date.now() > deadline) {
30963
+ log(`another agent is running (process ${other}): this one stops`);
30964
+ return false;
30965
+ }
30966
+ await sleep(500);
30967
+ }
30968
+ try {
30969
+ (0, import_node_fs4.writeFileSync)(file2, String(process.pid));
30970
+ } catch {
30971
+ }
30972
+ process.on("exit", () => {
30973
+ try {
30974
+ if ((0, import_node_fs4.readFileSync)(file2, "utf8").trim() === String(process.pid)) (0, import_node_fs4.unlinkSync)(file2);
30975
+ } catch {
30976
+ }
30977
+ });
30978
+ return true;
30979
+ }
30980
+ function launcherVbs(dir, nodeExe, agentFile) {
30981
+ const q = (s) => s.replace(/"/g, '""');
30982
+ return [
30983
+ 'Set s = CreateObject("WScript.Shell")',
30984
+ `s.CurrentDirectory = "${q(dir)}"`,
30985
+ `rc = s.Run("""${q(nodeExe)}"" ""${q(agentFile)}""", 0, True)`,
30986
+ "WScript.Quit rc",
30987
+ ""
30988
+ ].join("\r\n");
30989
+ }
30990
+ var POWERSHELL = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
30991
+ function restartSoon(dir, log) {
30992
+ if (process.platform !== "win32" || process.env.FRIEND_PC_NO_TASK) return;
30993
+ try {
30994
+ (0, import_node_child_process3.spawn)("powershell.exe", [...POWERSHELL, `Start-Sleep -Seconds 4; Start-ScheduledTask -TaskName '${TASK}'`], { cwd: dir, detached: true, stdio: "ignore", windowsHide: true }).unref();
30995
+ } catch (e) {
30996
+ log(`could not ask for a restart: ${e.message}`);
30997
+ }
30998
+ }
30999
+ async function ensureWatchdog(dir, nodeExe, agentFile, log) {
31000
+ if (process.platform !== "win32" || process.env.FRIEND_PC_NO_TASK) return;
31001
+ const vbs = (0, import_node_path4.join)(dir, "run.vbs");
31002
+ try {
31003
+ (0, import_node_fs4.writeFileSync)(vbs, launcherVbs(dir, nodeExe, agentFile));
31004
+ } catch (e) {
31005
+ log(`could not write the launcher: ${e.message}`);
31006
+ return;
31007
+ }
31008
+ const q = (s) => `'${s.replace(/'/g, "''")}'`;
31009
+ const script = `$ErrorActionPreference = 'Stop'
31010
+ $task = '${TASK}'
31011
+ $vbs = ${q(vbs)}
31012
+ $dir = ${q(dir)}
31013
+ $t = Get-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue
31014
+ if (-not $t) { Write-Output 'no task'; exit 0 }
31015
+ $did = @()
31016
+ $exe = ''
31017
+ if ($t.Actions.Count -gt 0) { $exe = [string]$t.Actions[0].Execute }
31018
+ if ($exe -notmatch 'wscript') {
31019
+ $action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('//B //Nologo ' + [char]34 + $vbs + [char]34) -WorkingDirectory $dir
31020
+ Set-ScheduledTask -TaskName $task -Action $action | Out-Null
31021
+ $did += 'hidden'
31022
+ }
31023
+ $has = $false
31024
+ foreach ($x in $t.Triggers) { if ($x.Repetition -and $x.Repetition.Interval) { $has = $true } }
31025
+ if (-not $has) {
31026
+ $who = $env:USERDOMAIN + '\\' + $env:USERNAME
31027
+ $triggers = @((New-ScheduledTaskTrigger -AtLogOn -User $who), (New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(2)) -RepetitionInterval (New-TimeSpan -Minutes 5) -RepetitionDuration (New-TimeSpan -Days 3650)))
31028
+ Set-ScheduledTask -TaskName $task -Trigger $triggers | Out-Null
31029
+ $did += 'watchdog'
31030
+ }
31031
+ Write-Output ('changed: ' + ($did -join ','))`;
31032
+ await new Promise((resolve) => {
31033
+ (0, import_node_child_process3.execFile)("powershell.exe", [...POWERSHELL, script], { windowsHide: true, timeout: 3e4 }, (e, out) => {
31034
+ if (e) log(`could not check the restart task: ${e.message.split("\n")[0]}`);
31035
+ else if (/changed: \S/.test(out)) log(`the logon task was updated (${out.replace(/^[\s\S]*changed:\s*/, "").trim()}): it starts the agent without a window, and again every five minutes if it is not running`);
31036
+ resolve();
31037
+ });
31038
+ });
31039
+ }
31040
+
31041
+ // ../pc-agent/src/main.ts
31042
+ var VERSION = "0.1.112";
31043
+ var TASK2 = "Friend PC Agent";
30936
31044
  function parse3(argv) {
30937
31045
  const out = {};
30938
31046
  for (let i = 0; i < argv.length; i++) {
@@ -30948,30 +31056,31 @@ function parse3(argv) {
30948
31056
  }
30949
31057
  var windowsName = () => `Windows ${/^10\.0\.(2[2-9]\d{3})/.test((0, import_node_os3.release)()) ? "11" : "10"}`;
30950
31058
  function uninstall(dir) {
30951
- (0, import_node_child_process3.execFile)("schtasks.exe", ["/delete", "/tn", TASK, "/f"], { windowsHide: true }, () => {
31059
+ (0, import_node_child_process4.execFile)("schtasks.exe", ["/delete", "/tn", TASK2, "/f"], { windowsHide: true }, () => {
30952
31060
  });
30953
31061
  const ps = `Start-Sleep -Seconds 3; Remove-Item -LiteralPath $env:FR_DIR -Recurse -Force -ErrorAction SilentlyContinue`;
30954
- (0, import_node_child_process3.spawn)("powershell.exe", ["-NoProfile", "-WindowStyle", "Hidden", "-Command", ps], { detached: true, stdio: "ignore", windowsHide: true, env: { ...process.env, FR_DIR: dir } }).unref();
31062
+ (0, import_node_child_process4.spawn)("powershell.exe", ["-NoProfile", "-WindowStyle", "Hidden", "-Command", ps], { detached: true, stdio: "ignore", windowsHide: true, env: { ...process.env, FR_DIR: dir } }).unref();
30955
31063
  console.log("Friend PC Agent is being removed from this PC.");
30956
31064
  process.exit(0);
30957
31065
  }
30958
31066
  async function main() {
30959
31067
  const args = parse3(process.argv.slice(2));
30960
- const dir = process.env.FRIEND_PC_DIR ?? (0, import_node_path4.join)(process.env.LOCALAPPDATA ?? (0, import_node_os3.homedir)(), "Friend", "pc-agent");
30961
- (0, import_node_fs4.mkdirSync)(dir, { recursive: true });
31068
+ const dir = process.env.FRIEND_PC_DIR ?? (0, import_node_path5.join)(process.env.LOCALAPPDATA ?? (0, import_node_os3.homedir)(), "Friend", "pc-agent");
31069
+ (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
30962
31070
  if (args.uninstall) return uninstall(dir);
30963
- const logFile = (0, import_node_path4.join)(dir, "agent.log");
31071
+ const logFile = (0, import_node_path5.join)(dir, "agent.log");
30964
31072
  const log = (line) => {
30965
31073
  const text = `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
30966
31074
  `;
30967
31075
  try {
30968
- if ((0, import_node_fs4.existsSync)(logFile) && (0, import_node_fs4.statSync)(logFile).size > 1e6) (0, import_node_fs4.truncateSync)(logFile, 0);
30969
- (0, import_node_fs4.appendFileSync)(logFile, text);
31076
+ if ((0, import_node_fs5.existsSync)(logFile) && (0, import_node_fs5.statSync)(logFile).size > 1e6) (0, import_node_fs5.truncateSync)(logFile, 0);
31077
+ (0, import_node_fs5.appendFileSync)(logFile, text);
30970
31078
  } catch {
30971
31079
  }
30972
31080
  if (process.stdout.isTTY) process.stdout.write(text);
30973
31081
  };
30974
- const store = new AgentStore((0, import_node_path4.join)(dir, "agent.db"));
31082
+ if (!await takeLock(dir, log)) process.exit(0);
31083
+ const store = new AgentStore((0, import_node_path5.join)(dir, "agent.db"));
30975
31084
  if (typeof args.server === "string") store.set("server", args.server.replace(/\/+$/, ""));
30976
31085
  if (typeof args.name === "string") store.set("name", args.name);
30977
31086
  const server = store.get("server");
@@ -30980,9 +31089,9 @@ async function main() {
30980
31089
  process.exit(2);
30981
31090
  }
30982
31091
  const self = process.argv[1] ?? "";
30983
- const agentSha256 = self && (0, import_node_fs4.existsSync)(self) ? (0, import_node_crypto2.createHash)("sha256").update((0, import_node_fs4.readFileSync)(self)).digest("hex") : void 0;
31092
+ const agentSha256 = self && (0, import_node_fs5.existsSync)(self) ? (0, import_node_crypto2.createHash)("sha256").update((0, import_node_fs5.readFileSync)(self)).digest("hex") : void 0;
30984
31093
  const holder = {};
30985
- const helper = new Helper({ spawn: powershellSpawner((0, import_node_path4.join)(dir, "helper")), onEvent: (e, d) => holder.agent?.onHelperEvent(e, d) });
31094
+ const helper = new Helper({ spawn: powershellSpawner((0, import_node_path5.join)(dir, "helper")), onEvent: (e, d) => holder.agent?.onHelperEvent(e, d) });
30986
31095
  const selfUpdate = async (url2, sha256) => {
30987
31096
  if (!url2.startsWith("/api/pc/agent.js") || !self || sha256 === agentSha256) return;
30988
31097
  try {
@@ -30991,9 +31100,10 @@ async function main() {
30991
31100
  const res = await fetch(`${server}${url2}`, { headers: { authorization: `Bearer ${token}` } });
30992
31101
  const body = Buffer.from(await res.arrayBuffer());
30993
31102
  if (!res.ok || (0, import_node_crypto2.createHash)("sha256").update(body).digest("hex") !== sha256) throw new Error("the new agent did not match its hash");
30994
- (0, import_node_fs4.writeFileSync)(`${self}.new`, body);
30995
- (0, import_node_fs4.renameSync)(`${self}.new`, self);
31103
+ (0, import_node_fs5.writeFileSync)(`${self}.new`, body);
31104
+ (0, import_node_fs5.renameSync)(`${self}.new`, self);
30996
31105
  log(`updated to ${sha256.slice(0, 8)}, restarting`);
31106
+ restartSoon(dir, log);
30997
31107
  process.exit(75);
30998
31108
  } catch (e) {
30999
31109
  log(`update failed: ${e.message}`);
@@ -31016,17 +31126,18 @@ Friend PC Agent
31016
31126
  Approve this PC: ${url2}
31017
31127
  Code: ${code}
31018
31128
  `);
31019
- if (!process.env.FRIEND_PC_NO_BROWSER) (0, import_node_child_process3.execFile)("cmd.exe", ["/c", "start", "", url2], { windowsHide: true }, () => {
31129
+ if (!process.env.FRIEND_PC_NO_BROWSER) (0, import_node_child_process4.execFile)("cmd.exe", ["/c", "start", "", url2], { windowsHide: true }, () => {
31020
31130
  });
31021
31131
  },
31022
31132
  log,
31023
31133
  onUpdate: (url2, sha) => void selfUpdate(url2, sha),
31024
31134
  onRevoked: () => {
31025
31135
  log("This PC was removed by the owner. Stopping.");
31026
- (0, import_node_child_process3.execFile)("schtasks.exe", ["/delete", "/tn", TASK, "/f"], { windowsHide: true }, () => setTimeout(() => process.exit(0), 500));
31136
+ (0, import_node_child_process4.execFile)("schtasks.exe", ["/delete", "/tn", TASK2, "/f"], { windowsHide: true }, () => setTimeout(() => process.exit(0), 500));
31027
31137
  }
31028
31138
  });
31029
31139
  holder.agent = agent;
31140
+ void ensureWatchdog(dir, process.execPath, self, log);
31030
31141
  const stop = () => void agent.stop().finally(() => process.exit(0));
31031
31142
  process.on("SIGINT", stop);
31032
31143
  process.on("SIGTERM", stop);
@@ -1 +1 @@
1
- a66c4fcf1d4e49a224ac71b9615f9bd5cb1a81748c8725d8c4f89fdbbb9c0117
1
+ 5896d75c965a48307ff135ba9d476e23848f2a02aaafef6d741d74b00bde7477
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "friend-assistant",
3
- "version": "0.1.110",
3
+ "version": "0.1.112",
4
4
  "description": "A self-hosted personal AI assistant for your own PC: a full-screen stage, voice, tools with your approval, and your Claude subscription or a local model.",
5
5
  "keywords": ["ai", "assistant", "jarvis", "voice", "claude", "ollama", "mcp", "self-hosted"],
6
6
  "license": "UNLICENSED",