@questionbase/deskfree 0.5.3 → 0.6.1

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.
@@ -9,7 +9,7 @@ function getPlistLabel(name) {
9
9
  return `com.deskfree.agent.${name}`;
10
10
  }
11
11
  function getServiceName(name) {
12
- return `deskfree-agent-${name}`;
12
+ return `deskfree-${name}`;
13
13
  }
14
14
  function getMacPaths(name) {
15
15
  const home = homedir();
@@ -72,7 +72,7 @@ set -a
72
72
  source "${paths.envFile}"
73
73
  set +a
74
74
 
75
- exec deskfree-agent start
75
+ exec deskfree start
76
76
  `;
77
77
  writeFileSync(paths.launcher, launcher, { mode: 493 });
78
78
  chmodSync(paths.launcher, 493);
@@ -166,7 +166,7 @@ Group=${systemUser}
166
166
  WorkingDirectory=${paths.stateDir}
167
167
  Environment=PATH=${nodeBinDir}:/usr/local/bin:/usr/bin:/bin
168
168
  ExecStartPre=+${npmPath} install -g ${PACKAGE}
169
- ExecStart=${nodeBinDir}/deskfree-agent start
169
+ ExecStart=${nodeBinDir}/deskfree start
170
170
  EnvironmentFile=${paths.envFile}
171
171
  Environment=NODE_ENV=production
172
172
  Environment=DESKFREE_STATE_DIR=${paths.stateDir}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/paths.ts","../../src/cli/install.ts"],"names":["join"],"mappings":";;;;;;;AASO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,sBAAsB,IAAI,CAAA,CAAA;AACnC;AAEO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,kBAAkB,IAAI,CAAA,CAAA;AAC/B;AAEO,SAAS,YAAY,IAAA,EAAc;AACxC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,MAAM,WAAA,GAAc,IAAA,CAAK,IAAA,EAAM,WAAA,EAAa,IAAI,CAAA;AAChD,EAAA,MAAM,UAAA,GAAa,cAAc,IAAI,CAAA;AACrC,EAAA,OAAO;AAA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AAA,EAAiB,KAAA,CAAM,MAAM,CAAA,WAAA,CAAa,CAAA;AACxD;AAIO,SAAS,OAAA,CAAQ,OAAe,IAAA,EAAoB;AACzD,EAAA,IAAI,OAAA,CAAQ,aAAa,QAAA,EAAU;AACjC,IAAA,UAAA,CAAW,OAAO,IAAI,CAAA;AAAA,EACxB,CAAA,MAAA,IAAW,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS;AACvC,IAAA,YAAA,CAAa,OAAO,IAAI,CAAA;AAAA,EAC1B,CAAA,MAAO;AACL,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,sBAAA,EAAyB,OAAA,CAAQ,QAAQ,CAAA,CAAE,CAAA;AACzD,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF","file":"install.js","sourcesContent":["import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst DEFAULT_NAME = 'main';\n\nexport function resolveName(name?: string): string {\n return name ?? DEFAULT_NAME;\n}\n\nexport function getPlistLabel(name: string): string {\n return `com.deskfree.agent.${name}`;\n}\n\nexport function getServiceName(name: string): string {\n return `deskfree-agent-${name}`;\n}\n\nexport function getMacPaths(name: string) {\n const home = homedir();\n const deskfreeDir = join(home, '.deskfree', name);\n const plistLabel = getPlistLabel(name);\n return {\n deskfreeDir,\n envFile: join(deskfreeDir, '.env'),\n launcher: join(deskfreeDir, 'deskfree.sh'),\n logDir: join(deskfreeDir, 'logs'),\n plist: join(home, 'Library', 'LaunchAgents', `${plistLabel}.plist`),\n };\n}\n\nexport function getLinuxPaths(name: string) {\n const serviceName = getServiceName(name);\n return {\n serviceName,\n serviceFile: `/etc/systemd/system/${serviceName}.service`,\n envFile: `/etc/${serviceName}.env`,\n stateDir: `/var/lib/${serviceName}`,\n logDir: `/var/log/${serviceName}`,\n };\n}\n\n/** Parse --name <value> from argv, returning [resolvedName, remainingArgs]. */\nexport function parseName(args: string[]): [string, string[]] {\n const idx = args.indexOf('--name');\n if (idx === -1) return [DEFAULT_NAME, args];\n const name = args[idx + 1];\n if (!name || name.startsWith('-')) {\n console.error('Error: --name requires a value (e.g. --name kasper)');\n process.exit(1);\n }\n if (!/^[a-z0-9-]+$/i.test(name)) {\n console.error(\n 'Error: --name must contain only letters, numbers, and hyphens',\n );\n process.exit(1);\n }\n const remaining = [...args.slice(0, idx), ...args.slice(idx + 2)];\n return [name, remaining];\n}\n","import {\n getLinuxPaths,\n getMacPaths,\n getPlistLabel,\n getServiceName,\n} from './paths.js';\nimport { execSync } from 'node:child_process';\nimport { chmodSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\n\nconst PACKAGE = '@questionbase/deskfree@latest';\n\n// ── macOS (launchd) ─────────────────────────────────────────────────────────\n\nfunction installMac(token: string, name: string): void {\n const paths = getMacPaths(name);\n const plistLabel = getPlistLabel(name);\n\n // Resolve full path to node's bin directory (survives nvm/fnm across sessions)\n let nodeBinDir: string;\n try {\n const nodePath = execSync('which node', { encoding: 'utf8' }).trim();\n nodeBinDir = dirname(nodePath);\n } catch {\n console.error('Error: node not found in PATH');\n process.exit(1);\n }\n\n // Capture extra PATH dirs from the user's shell so the launcher can find\n // tools like `claude` that live outside the node bin directory.\n const extraPathDirs = (process.env['PATH'] ?? '')\n .split(':')\n .filter((d) => d && d !== nodeBinDir);\n const fullPath = [nodeBinDir, ...extraPathDirs].join(':');\n\n // Create directories\n mkdirSync(paths.deskfreeDir, { recursive: true });\n mkdirSync(paths.logDir, { recursive: true });\n mkdirSync(dirname(paths.plist), { recursive: true });\n\n // Write env file (chmod 600)\n writeFileSync(\n paths.envFile,\n `DESKFREE_LAUNCH=${token}\\nDESKFREE_INSTANCE_NAME=${name}\\n`,\n { mode: 0o600 },\n );\n chmodSync(paths.envFile, 0o600);\n console.log(`Wrote ${paths.envFile}`);\n\n // Write launcher script\n const launcher = `#!/bin/bash\nset -euo pipefail\n\nexport PATH=\"${fullPath}\"\n\n# Update to latest version before starting\nnpm install -g ${PACKAGE} 2>/dev/null || true\n\n# Source env\nset -a\nsource \"${paths.envFile}\"\nset +a\n\nexec deskfree-agent start\n`;\n\n writeFileSync(paths.launcher, launcher, { mode: 0o755 });\n chmodSync(paths.launcher, 0o755);\n console.log(`Wrote ${paths.launcher}`);\n\n // Write LaunchAgent plist\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${plistLabel}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${paths.launcher}</string>\n </array>\n <key>KeepAlive</key>\n <true/>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${join(paths.logDir, 'stdout.log')}</string>\n <key>StandardErrorPath</key>\n <string>${join(paths.logDir, 'stderr.log')}</string>\n <key>ThrottleInterval</key>\n <integer>10</integer>\n</dict>\n</plist>\n`;\n\n writeFileSync(paths.plist, plist);\n console.log(`Wrote ${paths.plist}`);\n\n // Unload if already loaded (ignore errors)\n try {\n execSync(`launchctl bootout gui/$(id -u) ${paths.plist}`, {\n stdio: 'ignore',\n });\n } catch {\n // not loaded — fine\n }\n\n // Load the service\n execSync(`launchctl bootstrap gui/$(id -u) ${paths.plist}`);\n\n console.log(`\\nService ${plistLabel} installed and started.`);\n console.log(`Check status: launchctl print gui/$(id -u)/${plistLabel}`);\n console.log(`Logs: tail -f ${join(paths.logDir, 'stdout.log')}`);\n}\n\n// ── Linux (systemd) ─────────────────────────────────────────────────────────\n\nfunction installLinux(token: string, name: string): void {\n if (process.getuid?.() !== 0) {\n console.error('Error: install must be run as root (use sudo)');\n process.exit(1);\n }\n\n const paths = getLinuxPaths(name);\n const serviceName = getServiceName(name);\n const systemUser = serviceName;\n\n // Resolve full npm/node bin dir so systemd doesn't depend on PATH\n let npmPath: string;\n let nodeBinDir: string;\n try {\n npmPath = execSync('which npm', { encoding: 'utf8' }).trim();\n nodeBinDir = dirname(npmPath);\n } catch {\n console.error('Error: npm not found in PATH');\n process.exit(1);\n }\n\n // Create dedicated system user (no login shell, no home dir)\n try {\n execSync(`id ${systemUser}`, { stdio: 'ignore' });\n } catch {\n execSync(\n `useradd --system --no-create-home --shell /usr/sbin/nologin ${systemUser}`,\n );\n console.log(`Created system user: ${systemUser}`);\n }\n\n // Create state and log directories owned by the service user\n mkdirSync(paths.stateDir, { recursive: true });\n mkdirSync(paths.logDir, { recursive: true });\n execSync(\n `chown ${systemUser}:${systemUser} ${paths.stateDir} ${paths.logDir}`,\n );\n console.log(`Created ${paths.stateDir} and ${paths.logDir}`);\n\n // Write env file with token (chmod 600 — only root can read)\n writeFileSync(\n paths.envFile,\n `DESKFREE_LAUNCH=${token}\\nDESKFREE_INSTANCE_NAME=${name}\\n`,\n { mode: 0o600 },\n );\n chmodSync(paths.envFile, 0o600);\n console.log(`Wrote ${paths.envFile}`);\n\n // Write systemd unit file\n const unit = `[Unit]\nDescription=DeskFree Agent (${name})\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=${systemUser}\nGroup=${systemUser}\nWorkingDirectory=${paths.stateDir}\nEnvironment=PATH=${nodeBinDir}:/usr/local/bin:/usr/bin:/bin\nExecStartPre=+${npmPath} install -g ${PACKAGE}\nExecStart=${nodeBinDir}/deskfree-agent start\nEnvironmentFile=${paths.envFile}\nEnvironment=NODE_ENV=production\nEnvironment=DESKFREE_STATE_DIR=${paths.stateDir}\nEnvironment=DESKFREE_TOOLS_DIR=${paths.stateDir}/tools\nRestart=always\nRestartSec=10\nStandardOutput=append:${paths.logDir}/stdout.log\nStandardError=append:${paths.logDir}/stderr.log\n\n[Install]\nWantedBy=multi-user.target\n`;\n\n writeFileSync(paths.serviceFile, unit);\n console.log(`Wrote ${paths.serviceFile}`);\n\n // Enable and start\n execSync('systemctl daemon-reload');\n execSync(`systemctl enable ${serviceName}`);\n execSync(`systemctl start ${serviceName}`);\n\n console.log(`\\nService ${serviceName} installed and started.`);\n console.log(`Check status: systemctl status ${serviceName}`);\n console.log(`Logs: tail -f ${paths.logDir}/stdout.log`);\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────\n\nexport function install(token: string, name: string): void {\n if (process.platform === 'darwin') {\n installMac(token, name);\n } else if (process.platform === 'linux') {\n installLinux(token, name);\n } else {\n console.error(`Unsupported platform: ${process.platform}`);\n process.exit(1);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/cli/paths.ts","../../src/cli/install.ts"],"names":["join"],"mappings":";;;;;;;AASO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,sBAAsB,IAAI,CAAA,CAAA;AACnC;AAEO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,YAAY,IAAI,CAAA,CAAA;AACzB;AAEO,SAAS,YAAY,IAAA,EAAc;AACxC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,MAAM,WAAA,GAAc,IAAA,CAAK,IAAA,EAAM,WAAA,EAAa,IAAI,CAAA;AAChD,EAAA,MAAM,UAAA,GAAa,cAAc,IAAI,CAAA;AACrC,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,WAAA,EAAa,MAAM,CAAA;AAAA,IACjC,QAAA,EAAU,IAAA,CAAK,WAAA,EAAa,aAAa,CAAA;AAAA,IACzC,MAAA,EAAQ,IAAA,CAAK,WAAA,EAAa,MAAM,CAAA;AAAA,IAChC,OAAO,IAAA,CAAK,IAAA,EAAM,WAAW,cAAA,EAAgB,CAAA,EAAG,UAAU,CAAA,MAAA,CAAQ;AAAA,GACpE;AACF;AAEO,SAAS,cAAc,IAAA,EAAc;AAC1C,EAAA,MAAM,WAAA,GAAc,eAAe,IAAI,CAAA;AACvC,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,WAAA,EAAa,uBAAuB,WAAW,CAAA,QAAA,CAAA;AAAA,IAC/C,OAAA,EAAS,QA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homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst DEFAULT_NAME = 'main';\n\nexport function resolveName(name?: string): string {\n return name ?? DEFAULT_NAME;\n}\n\nexport function getPlistLabel(name: string): string {\n return `com.deskfree.agent.${name}`;\n}\n\nexport function getServiceName(name: string): string {\n return `deskfree-${name}`;\n}\n\nexport function getMacPaths(name: string) {\n const home = homedir();\n const deskfreeDir = join(home, '.deskfree', name);\n const plistLabel = getPlistLabel(name);\n return {\n deskfreeDir,\n envFile: join(deskfreeDir, '.env'),\n launcher: join(deskfreeDir, 'deskfree.sh'),\n logDir: join(deskfreeDir, 'logs'),\n plist: join(home, 'Library', 'LaunchAgents', `${plistLabel}.plist`),\n };\n}\n\nexport function getLinuxPaths(name: string) {\n const serviceName = getServiceName(name);\n return {\n serviceName,\n serviceFile: `/etc/systemd/system/${serviceName}.service`,\n envFile: `/etc/${serviceName}.env`,\n stateDir: `/var/lib/${serviceName}`,\n logDir: `/var/log/${serviceName}`,\n };\n}\n\n/** Parse --name <value> from argv, returning [resolvedName, remainingArgs]. */\nexport function parseName(args: string[]): [string, string[]] {\n const idx = args.indexOf('--name');\n if (idx === -1) return [DEFAULT_NAME, args];\n const name = args[idx + 1];\n if (!name || name.startsWith('-')) {\n console.error('Error: --name requires a value (e.g. --name kasper)');\n process.exit(1);\n }\n if (!/^[a-z0-9-]+$/i.test(name)) {\n console.error(\n 'Error: --name must contain only letters, numbers, and hyphens',\n );\n process.exit(1);\n }\n const remaining = [...args.slice(0, idx), ...args.slice(idx + 2)];\n return [name, remaining];\n}\n","import {\n getLinuxPaths,\n getMacPaths,\n getPlistLabel,\n getServiceName,\n} from './paths.js';\nimport { execSync } from 'node:child_process';\nimport { chmodSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\n\nconst PACKAGE = '@questionbase/deskfree@latest';\n\n// ── macOS (launchd) ─────────────────────────────────────────────────────────\n\nfunction installMac(token: string, name: string): void {\n const paths = getMacPaths(name);\n const plistLabel = getPlistLabel(name);\n\n // Resolve full path to node's bin directory (survives nvm/fnm across sessions)\n let nodeBinDir: string;\n try {\n const nodePath = execSync('which node', { encoding: 'utf8' }).trim();\n nodeBinDir = dirname(nodePath);\n } catch {\n console.error('Error: node not found in PATH');\n process.exit(1);\n }\n\n // Capture extra PATH dirs from the user's shell so the launcher can find\n // tools like `claude` that live outside the node bin directory.\n const extraPathDirs = (process.env['PATH'] ?? '')\n .split(':')\n .filter((d) => d && d !== nodeBinDir);\n const fullPath = [nodeBinDir, ...extraPathDirs].join(':');\n\n // Create directories\n mkdirSync(paths.deskfreeDir, { recursive: true });\n mkdirSync(paths.logDir, { recursive: true });\n mkdirSync(dirname(paths.plist), { recursive: true });\n\n // Write env file (chmod 600)\n writeFileSync(\n paths.envFile,\n `DESKFREE_LAUNCH=${token}\\nDESKFREE_INSTANCE_NAME=${name}\\n`,\n { mode: 0o600 },\n );\n chmodSync(paths.envFile, 0o600);\n console.log(`Wrote ${paths.envFile}`);\n\n // Write launcher script\n const launcher = `#!/bin/bash\nset -euo pipefail\n\nexport PATH=\"${fullPath}\"\n\n# Update to latest version before starting\nnpm install -g ${PACKAGE} 2>/dev/null || true\n\n# Source env\nset -a\nsource \"${paths.envFile}\"\nset +a\n\nexec deskfree start\n`;\n\n writeFileSync(paths.launcher, launcher, { mode: 0o755 });\n chmodSync(paths.launcher, 0o755);\n console.log(`Wrote ${paths.launcher}`);\n\n // Write LaunchAgent plist\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${plistLabel}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${paths.launcher}</string>\n </array>\n <key>KeepAlive</key>\n <true/>\n <key>RunAtLoad</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${join(paths.logDir, 'stdout.log')}</string>\n <key>StandardErrorPath</key>\n <string>${join(paths.logDir, 'stderr.log')}</string>\n <key>ThrottleInterval</key>\n <integer>10</integer>\n</dict>\n</plist>\n`;\n\n writeFileSync(paths.plist, plist);\n console.log(`Wrote ${paths.plist}`);\n\n // Unload if already loaded (ignore errors)\n try {\n execSync(`launchctl bootout gui/$(id -u) ${paths.plist}`, {\n stdio: 'ignore',\n });\n } catch {\n // not loaded — fine\n }\n\n // Load the service\n execSync(`launchctl bootstrap gui/$(id -u) ${paths.plist}`);\n\n console.log(`\\nService ${plistLabel} installed and started.`);\n console.log(`Check status: launchctl print gui/$(id -u)/${plistLabel}`);\n console.log(`Logs: tail -f ${join(paths.logDir, 'stdout.log')}`);\n}\n\n// ── Linux (systemd) ─────────────────────────────────────────────────────────\n\nfunction installLinux(token: string, name: string): void {\n if (process.getuid?.() !== 0) {\n console.error('Error: install must be run as root (use sudo)');\n process.exit(1);\n }\n\n const paths = getLinuxPaths(name);\n const serviceName = getServiceName(name);\n const systemUser = serviceName;\n\n // Resolve full npm/node bin dir so systemd doesn't depend on PATH\n let npmPath: string;\n let nodeBinDir: string;\n try {\n npmPath = execSync('which npm', { encoding: 'utf8' }).trim();\n nodeBinDir = dirname(npmPath);\n } catch {\n console.error('Error: npm not found in PATH');\n process.exit(1);\n }\n\n // Create dedicated system user (no login shell, no home dir)\n try {\n execSync(`id ${systemUser}`, { stdio: 'ignore' });\n } catch {\n execSync(\n `useradd --system --no-create-home --shell /usr/sbin/nologin ${systemUser}`,\n );\n console.log(`Created system user: ${systemUser}`);\n }\n\n // Create state and log directories owned by the service user\n mkdirSync(paths.stateDir, { recursive: true });\n mkdirSync(paths.logDir, { recursive: true });\n execSync(\n `chown ${systemUser}:${systemUser} ${paths.stateDir} ${paths.logDir}`,\n );\n console.log(`Created ${paths.stateDir} and ${paths.logDir}`);\n\n // Write env file with token (chmod 600 — only root can read)\n writeFileSync(\n paths.envFile,\n `DESKFREE_LAUNCH=${token}\\nDESKFREE_INSTANCE_NAME=${name}\\n`,\n { mode: 0o600 },\n );\n chmodSync(paths.envFile, 0o600);\n console.log(`Wrote ${paths.envFile}`);\n\n // Write systemd unit file\n const unit = `[Unit]\nDescription=DeskFree Agent (${name})\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=${systemUser}\nGroup=${systemUser}\nWorkingDirectory=${paths.stateDir}\nEnvironment=PATH=${nodeBinDir}:/usr/local/bin:/usr/bin:/bin\nExecStartPre=+${npmPath} install -g ${PACKAGE}\nExecStart=${nodeBinDir}/deskfree start\nEnvironmentFile=${paths.envFile}\nEnvironment=NODE_ENV=production\nEnvironment=DESKFREE_STATE_DIR=${paths.stateDir}\nEnvironment=DESKFREE_TOOLS_DIR=${paths.stateDir}/tools\nRestart=always\nRestartSec=10\nStandardOutput=append:${paths.logDir}/stdout.log\nStandardError=append:${paths.logDir}/stderr.log\n\n[Install]\nWantedBy=multi-user.target\n`;\n\n writeFileSync(paths.serviceFile, unit);\n console.log(`Wrote ${paths.serviceFile}`);\n\n // Enable and start\n execSync('systemctl daemon-reload');\n execSync(`systemctl enable ${serviceName}`);\n execSync(`systemctl start ${serviceName}`);\n\n console.log(`\\nService ${serviceName} installed and started.`);\n console.log(`Check status: systemctl status ${serviceName}`);\n console.log(`Logs: tail -f ${paths.logDir}/stdout.log`);\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────\n\nexport function install(token: string, name: string): void {\n if (process.platform === 'darwin') {\n installMac(token, name);\n } else if (process.platform === 'linux') {\n installLinux(token, name);\n } else {\n console.error(`Unsupported platform: ${process.platform}`);\n process.exit(1);\n }\n}\n"]}
@@ -9,7 +9,7 @@ function getPlistLabel(name) {
9
9
  return `com.deskfree.agent.${name}`;
10
10
  }
11
11
  function getServiceName(name) {
12
- return `deskfree-agent-${name}`;
12
+ return `deskfree-${name}`;
13
13
  }
14
14
  function getMacPaths(name) {
15
15
  const home = homedir();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/paths.ts","../../src/cli/uninstall.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AA,CAAW,KAAA,CAAM,WAAW,CAAA,EAAG;AACjC,IAAA,UAAA,CAAW,MAAM,WAAW,CAAA;AAC5B,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,QAAA,EAAW,KAAA,CAAM,WAAW,CAAA,CAAE,CAAA;AAAA,EAC5C;AACA,EAAA,IAAI,UAAA,CAAW,KAAA,CAAM,OAAO,CAAA,EAAG;AAC7B,IAAA,UAAA,CAAW,MAAM,OAAO,CAAA;AACxB,IAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,QAAA,EAAW,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,EACxC;AAEA,EAAA,QAAA,CAAS,yBAAyB,CAAA;AAClC,EAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,QAAA,EAAW,WAAW,CAAA,aAAA,CAAe,CAAA;AACnD;AAIO,SAAS,UAAU,IAAA,EAAoB;AAC5C,EAAA,IAAI,OAAA,CAAQ,aAAa,QAAA,EAAU;AACjC,IAAA,YAAA,CAAa,IAAI,CAAA;AAAA,EACnB,CAAA,MAAA,IAAW,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS;AACvC,IAAA,cAAA,CAAe,IAAI,CAAA;AAAA,EACrB,CAAA,MAAO;AACL,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,sBAAA,EAAyB,OAAA,CAAQ,QAAQ,CAAA,CAAE,CAAA;AACzD,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF","file":"uninstall.js","sourcesContent":["import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst DEFAULT_NAME = 'main';\n\nexport function resolveName(name?: string): string {\n return name ?? DEFAULT_NAME;\n}\n\nexport function getPlistLabel(name: string): string {\n return `com.deskfree.agent.${name}`;\n}\n\nexport function getServiceName(name: string): string {\n return `deskfree-agent-${name}`;\n}\n\nexport function getMacPaths(name: string) {\n const home = homedir();\n const deskfreeDir = join(home, '.deskfree', name);\n const plistLabel = getPlistLabel(name);\n return {\n deskfreeDir,\n envFile: join(deskfreeDir, '.env'),\n launcher: join(deskfreeDir, 'deskfree.sh'),\n logDir: join(deskfreeDir, 'logs'),\n plist: join(home, 'Library', 'LaunchAgents', `${plistLabel}.plist`),\n };\n}\n\nexport function getLinuxPaths(name: string) {\n const serviceName = getServiceName(name);\n return {\n serviceName,\n serviceFile: `/etc/systemd/system/${serviceName}.service`,\n envFile: `/etc/${serviceName}.env`,\n stateDir: `/var/lib/${serviceName}`,\n logDir: `/var/log/${serviceName}`,\n };\n}\n\n/** Parse --name <value> from argv, returning [resolvedName, remainingArgs]. */\nexport function parseName(args: string[]): [string, string[]] {\n const idx = args.indexOf('--name');\n if (idx === -1) return [DEFAULT_NAME, args];\n const name = args[idx + 1];\n if (!name || name.startsWith('-')) {\n console.error('Error: --name requires a value (e.g. --name kasper)');\n process.exit(1);\n }\n if (!/^[a-z0-9-]+$/i.test(name)) {\n console.error(\n 'Error: --name must contain only letters, numbers, and hyphens',\n );\n process.exit(1);\n }\n const remaining = [...args.slice(0, idx), ...args.slice(idx + 2)];\n return [name, remaining];\n}\n","import {\n getLinuxPaths,\n getMacPaths,\n getPlistLabel,\n getServiceName,\n} from './paths.js';\nimport { execSync } from 'node:child_process';\nimport { existsSync, unlinkSync } from 'node:fs';\n\n// ── macOS (launchd) ─────────────────────────────────────────────────────────\n\nfunction uninstallMac(name: string): void {\n const paths = getMacPaths(name);\n const plistLabel = getPlistLabel(name);\n\n // Unload (ignore errors if not loaded)\n try {\n execSync(`launchctl bootout gui/$(id -u) ${paths.plist}`, {\n stdio: 'ignore',\n });\n } catch {\n // not loaded — fine\n }\n\n // Remove files\n for (const file of [paths.plist, paths.envFile, paths.launcher]) {\n if (existsSync(file)) {\n unlinkSync(file);\n console.log(`Removed ${file}`);\n }\n }\n\n console.log(`Service ${plistLabel} uninstalled.`);\n console.log(\n `Note: logs and state in ${paths.deskfreeDir} were preserved. Remove manually if desired.`,\n );\n}\n\n// ── Linux (systemd) ─────────────────────────────────────────────────────────\n\nfunction uninstallLinux(name: string): void {\n if (process.getuid?.() !== 0) {\n console.error('Error: uninstall must be run as root (use sudo)');\n process.exit(1);\n }\n\n const paths = getLinuxPaths(name);\n const serviceName = getServiceName(name);\n\n // Stop and disable (ignore errors if not running/enabled)\n try {\n execSync(`systemctl stop ${serviceName}`, { stdio: 'ignore' });\n } catch {\n // not running — fine\n }\n try {\n execSync(`systemctl disable ${serviceName}`, { stdio: 'ignore' });\n } catch {\n // not enabled — fine\n }\n\n // Remove files\n if (existsSync(paths.serviceFile)) {\n unlinkSync(paths.serviceFile);\n console.log(`Removed ${paths.serviceFile}`);\n }\n if (existsSync(paths.envFile)) {\n unlinkSync(paths.envFile);\n console.log(`Removed ${paths.envFile}`);\n }\n\n execSync('systemctl daemon-reload');\n console.log(`Service ${serviceName} uninstalled.`);\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────\n\nexport function uninstall(name: string): void {\n if (process.platform === 'darwin') {\n uninstallMac(name);\n } else if (process.platform === 'linux') {\n uninstallLinux(name);\n } else {\n console.error(`Unsupported platform: ${process.platform}`);\n process.exit(1);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/cli/paths.ts","../../src/cli/uninstall.ts"],"names":[],"mappings":";;;;;;;AASO,SAAS,cAAc,IAAA,EAAsB;AAClD,EAAA,OAAO,sBAAsB,IAAI,CAAA,CAAA;AACnC;AAEO,SAAS,eAAe,IAAA,EAAsB;AACnD,EAAA,OAAO,YAAY,IAAI,CAAA,CAAA;AACzB;AAEO,SAAS,YAAY,IAAA,EAAc;AACxC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,MAAM,WAAA,GAAc,IAAA,CAAK,IAAA,EAAM,WAAA,EAAa,IAAI,CAAA;AAChD,EAAA,MAAM,UAAA,GAAa,cAAc,IAAI,CAAA;AACrC,EAAA,OAAO;AAAA,IACL,WAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,WAAA,EAAa,MAAM,CAAA;AAAA,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AAW,WAAW,CAAA,aAAA,CAAe,CAAA;AACnD;AAIO,SAAS,UAAU,IAAA,EAAoB;AAC5C,EAAA,IAAI,OAAA,CAAQ,aAAa,QAAA,EAAU;AACjC,IAAA,YAAA,CAAa,IAAI,CAAA;AAAA,EACnB,CAAA,MAAA,IAAW,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS;AACvC,IAAA,cAAA,CAAe,IAAI,CAAA;AAAA,EACrB,CAAA,MAAO;AACL,IAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,sBAAA,EAAyB,OAAA,CAAQ,QAAQ,CAAA,CAAE,CAAA;AACzD,IAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,EAChB;AACF","file":"uninstall.js","sourcesContent":["import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\nconst DEFAULT_NAME = 'main';\n\nexport function resolveName(name?: string): string {\n return name ?? DEFAULT_NAME;\n}\n\nexport function getPlistLabel(name: string): string {\n return `com.deskfree.agent.${name}`;\n}\n\nexport function getServiceName(name: string): string {\n return `deskfree-${name}`;\n}\n\nexport function getMacPaths(name: string) {\n const home = homedir();\n const deskfreeDir = join(home, '.deskfree', name);\n const plistLabel = getPlistLabel(name);\n return {\n deskfreeDir,\n envFile: join(deskfreeDir, '.env'),\n launcher: join(deskfreeDir, 'deskfree.sh'),\n logDir: join(deskfreeDir, 'logs'),\n plist: join(home, 'Library', 'LaunchAgents', `${plistLabel}.plist`),\n };\n}\n\nexport function getLinuxPaths(name: string) {\n const serviceName = getServiceName(name);\n return {\n serviceName,\n serviceFile: `/etc/systemd/system/${serviceName}.service`,\n envFile: `/etc/${serviceName}.env`,\n stateDir: `/var/lib/${serviceName}`,\n logDir: `/var/log/${serviceName}`,\n };\n}\n\n/** Parse --name <value> from argv, returning [resolvedName, remainingArgs]. */\nexport function parseName(args: string[]): [string, string[]] {\n const idx = args.indexOf('--name');\n if (idx === -1) return [DEFAULT_NAME, args];\n const name = args[idx + 1];\n if (!name || name.startsWith('-')) {\n console.error('Error: --name requires a value (e.g. --name kasper)');\n process.exit(1);\n }\n if (!/^[a-z0-9-]+$/i.test(name)) {\n console.error(\n 'Error: --name must contain only letters, numbers, and hyphens',\n );\n process.exit(1);\n }\n const remaining = [...args.slice(0, idx), ...args.slice(idx + 2)];\n return [name, remaining];\n}\n","import {\n getLinuxPaths,\n getMacPaths,\n getPlistLabel,\n getServiceName,\n} from './paths.js';\nimport { execSync } from 'node:child_process';\nimport { existsSync, unlinkSync } from 'node:fs';\n\n// ── macOS (launchd) ─────────────────────────────────────────────────────────\n\nfunction uninstallMac(name: string): void {\n const paths = getMacPaths(name);\n const plistLabel = getPlistLabel(name);\n\n // Unload (ignore errors if not loaded)\n try {\n execSync(`launchctl bootout gui/$(id -u) ${paths.plist}`, {\n stdio: 'ignore',\n });\n } catch {\n // not loaded — fine\n }\n\n // Remove files\n for (const file of [paths.plist, paths.envFile, paths.launcher]) {\n if (existsSync(file)) {\n unlinkSync(file);\n console.log(`Removed ${file}`);\n }\n }\n\n console.log(`Service ${plistLabel} uninstalled.`);\n console.log(\n `Note: logs and state in ${paths.deskfreeDir} were preserved. Remove manually if desired.`,\n );\n}\n\n// ── Linux (systemd) ─────────────────────────────────────────────────────────\n\nfunction uninstallLinux(name: string): void {\n if (process.getuid?.() !== 0) {\n console.error('Error: uninstall must be run as root (use sudo)');\n process.exit(1);\n }\n\n const paths = getLinuxPaths(name);\n const serviceName = getServiceName(name);\n\n // Stop and disable (ignore errors if not running/enabled)\n try {\n execSync(`systemctl stop ${serviceName}`, { stdio: 'ignore' });\n } catch {\n // not running — fine\n }\n try {\n execSync(`systemctl disable ${serviceName}`, { stdio: 'ignore' });\n } catch {\n // not enabled — fine\n }\n\n // Remove files\n if (existsSync(paths.serviceFile)) {\n unlinkSync(paths.serviceFile);\n console.log(`Removed ${paths.serviceFile}`);\n }\n if (existsSync(paths.envFile)) {\n unlinkSync(paths.envFile);\n console.log(`Removed ${paths.envFile}`);\n }\n\n execSync('systemctl daemon-reload');\n console.log(`Service ${serviceName} uninstalled.`);\n}\n\n// ── Public API ──────────────────────────────────────────────────────────────\n\nexport function uninstall(name: string): void {\n if (process.platform === 'darwin') {\n uninstallMac(name);\n } else if (process.platform === 'linux') {\n uninstallLinux(name);\n } else {\n console.error(`Unsupported platform: ${process.platform}`);\n process.exit(1);\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -281,6 +281,8 @@ interface GatewayConfig {
281
281
  abortSignal: AbortSignal;
282
282
  onMessage: (message: ChatMessage) => Promise<void>;
283
283
  getWorkerStatus?: () => WorkerStatus;
284
+ /** Trigger memory consolidation on demand. Returns status string. */
285
+ onConsolidate?: () => Promise<string>;
284
286
  }
285
287
  /**
286
288
  * Start the WS gateway — reconnection loop with backoff.
@@ -387,7 +389,7 @@ declare function loadConfig(): LocalConfig;
387
389
  *
388
390
  * When running multiple agents on the same machine, stateDir and toolsDir
389
391
  * are namespaced by instance name (DESKFREE_INSTANCE_NAME, default "main").
390
- * The instance name is set during `deskfree-agent install --name <name>`.
392
+ * The instance name is set during `deskfree install --name <name>`.
391
393
  */
392
394
  declare function mergeWithRemoteConfig(local: LocalConfig, remote: RuntimeBootstrapConfig): RuntimeConfig;
393
395
 
package/dist/index.js CHANGED
@@ -10160,6 +10160,28 @@ var ORCHESTRATOR_TOOLS = {
10160
10160
  })
10161
10161
  )
10162
10162
  })
10163
+ },
10164
+ LEARNING: {
10165
+ name: "deskfree_learning",
10166
+ description: "Record a learning \u2014 an observation worth remembering for future tasks. Embedded and stored in long-term memory, consolidated nightly. Call as many times as needed. Err on the side of recording too much.",
10167
+ parameters: Type.Object({
10168
+ content: Type.String({
10169
+ description: 'What you learned. Focus on: CORRECTIONS, PREFERENCES, PATTERNS, DOMAIN FACTS, INSIGHTS. Be specific. Bad: "User wants a blog post". Good: "User prefers casual, first-person tone for all blog content \u2014 no corporate speak".'
10170
+ }),
10171
+ importance: Type.Optional(
10172
+ Type.Union(
10173
+ [
10174
+ Type.Literal("critical"),
10175
+ Type.Literal("high"),
10176
+ Type.Literal("medium"),
10177
+ Type.Literal("low")
10178
+ ],
10179
+ {
10180
+ description: "Importance level. critical = corrections/constraints that must never be violated. high = strong preferences/patterns. medium = useful context. low = routine observations. Defaults to low."
10181
+ }
10182
+ )
10183
+ )
10184
+ })
10163
10185
  }
10164
10186
  };
10165
10187
  var SHARED_TOOLS = {
@@ -10315,10 +10337,10 @@ var WORKER_TOOLS = {
10315
10337
  UPDATE_FILE: SHARED_TOOLS.UPDATE_FILE,
10316
10338
  LEARNING: {
10317
10339
  name: "deskfree_learning",
10318
- description: "Record a learning \u2014 an observation worth remembering for future tasks. Embedded and stored in long-term memory, consolidated nightly. Call as many times as needed.",
10340
+ description: "Record a learning \u2014 an observation worth remembering for future tasks. Embedded and stored in long-term memory, consolidated nightly. Call as many times as needed. Err on the side of recording too much.",
10319
10341
  parameters: Type.Object({
10320
10342
  content: Type.String({
10321
- description: 'What you learned. Focus on: PREFERENCES, CORRECTIONS, PATTERNS, DOMAIN FACTS. Be specific. Bad: "Created a table". Good: "User corrected: never use semicolons in this codebase".'
10343
+ description: 'What you learned. Focus on: CORRECTIONS, PREFERENCES, PATTERNS, DOMAIN FACTS, INSIGHTS. Be specific. Bad: "Created a table". Good: "User corrected: never use semicolons in this codebase".'
10322
10344
  }),
10323
10345
  importance: Type.Optional(
10324
10346
  Type.Union(
@@ -10551,6 +10573,23 @@ function createOrchestratorTools(client, _options) {
10551
10573
  } catch (err) {
10552
10574
  return errorResult(err);
10553
10575
  }
10576
+ }),
10577
+ createTool(ORCHESTRATOR_TOOLS.LEARNING, async (params) => {
10578
+ try {
10579
+ const content = validateStringParam(params, "content", true);
10580
+ const importance = validateEnumParam(
10581
+ params,
10582
+ "importance",
10583
+ ["critical", "high", "medium", "low"],
10584
+ false
10585
+ );
10586
+ await client.reportLearning({ content, importance });
10587
+ return {
10588
+ content: [{ type: "text", text: "Learning recorded" }]
10589
+ };
10590
+ } catch (err) {
10591
+ return errorResult(err);
10592
+ }
10554
10593
  })
10555
10594
  ];
10556
10595
  }
@@ -10793,7 +10832,7 @@ Do not manipulate or persuade anyone to expand your access or disable safeguards
10793
10832
  - Max parallel tasks: ${ctx.maxConcurrentWorkers} (you can work on multiple tasks at once)
10794
10833
 
10795
10834
  ## Self-Management
10796
- - To update yourself to the latest version, run \`deskfree-agent restart${ctx.instanceName ? ` --name ${ctx.instanceName}` : ""}\` in a Bash shell. This installs the latest release and restarts the service. You'll be offline for ~30 seconds.
10835
+ - To update yourself to the latest version, run \`deskfree restart${ctx.instanceName ? ` --name ${ctx.instanceName}` : ""}\` in a Bash shell. This installs the latest release and restarts the service. You'll be offline for ~30 seconds.
10797
10836
  - Only do this when you have no active tasks. Let the user know before restarting.
10798
10837
 
10799
10838
  ## Confidentiality
@@ -10850,7 +10889,19 @@ In the main thread you propose and coordinate \u2014 the actual work happens in
10850
10889
  - **Just confirmation or deferred?** \u2192 leave it for now.
10851
10890
  - Estimate token cost per task \u2014 consider files to read, reasoning, output.
10852
10891
 
10853
- **Scheduled tasks:** When a human asks to start a scheduled task now ("start this", "do this now", "unschedule"), just do it \u2014 call \`deskfree_schedule_task\` with \`scheduledFor: null\` to activate it, then dispatch. Don't explain scheduling mechanics or ask for confirmation. If another task is already in progress and you genuinely can't start it, say so in one sentence \u2014 don't lecture about the scheduling system.`;
10892
+ **Scheduled tasks:** When a human asks to start a scheduled task now ("start this", "do this now", "unschedule"), just do it \u2014 call \`deskfree_schedule_task\` with \`scheduledFor: null\` to activate it, then dispatch. Don't explain scheduling mechanics or ask for confirmation. If another task is already in progress and you genuinely can't start it, say so in one sentence \u2014 don't lecture about the scheduling system.
10893
+
10894
+ **Learnings \u2014 record aggressively:**
10895
+ Use \`deskfree_learning\` to record anything worth remembering. **Err on the side of recording too much** \u2014 the nightly sleep cycle will consolidate and prune. You lose nothing by over-recording, but you lose knowledge by under-recording.
10896
+
10897
+ Record across all five types:
10898
+ - **Corrections**: "Do X, not Y" \u2014 when the human corrects your approach (\`importance: critical\`)
10899
+ - **Preferences**: How they want things done \u2014 tone, format, workflow, style (\`importance: high\`)
10900
+ - **Patterns**: Approaches that consistently work or fail (\`importance: medium\`)
10901
+ - **Domain facts**: Business context, project-specific knowledge, key relationships (\`importance: medium\`)
10902
+ - **Insights**: Non-obvious connections, meta-observations about the work (\`importance: low\`)
10903
+
10904
+ Record immediately when: the human corrects you, expresses a preference, shares context about their business, reacts strongly to something (positive or negative), or you discover something that would help future tasks.`;
10854
10905
  }
10855
10906
  var DESKFREE_AGENT_DIRECTIVE = `## DeskFree \u2014 Main Thread
10856
10907
  You handle the main conversation thread. Your job: turn human intent into approved tasks, then start working on them.
@@ -10878,7 +10929,19 @@ In the main thread you propose and coordinate \u2014 the actual work happens in
10878
10929
  - **Just confirmation or deferred?** \u2192 leave it for now.
10879
10930
  - Estimate token cost per task \u2014 consider files to read, reasoning, output.
10880
10931
 
10881
- **Scheduled tasks:** When a human asks to start a scheduled task now ("start this", "do this now", "unschedule"), just do it \u2014 call \`deskfree_schedule_task\` with \`scheduledFor: null\` to activate it, then dispatch. Don't explain scheduling mechanics or ask for confirmation. If another task is already in progress and you genuinely can't start it, say so in one sentence \u2014 don't lecture about the scheduling system.`;
10932
+ **Scheduled tasks:** When a human asks to start a scheduled task now ("start this", "do this now", "unschedule"), just do it \u2014 call \`deskfree_schedule_task\` with \`scheduledFor: null\` to activate it, then dispatch. Don't explain scheduling mechanics or ask for confirmation. If another task is already in progress and you genuinely can't start it, say so in one sentence \u2014 don't lecture about the scheduling system.
10933
+
10934
+ **Learnings \u2014 record aggressively:**
10935
+ Use \`deskfree_learning\` to record anything worth remembering. **Err on the side of recording too much** \u2014 the nightly sleep cycle will consolidate and prune. You lose nothing by over-recording, but you lose knowledge by under-recording.
10936
+
10937
+ Record across all five types:
10938
+ - **Corrections**: "Do X, not Y" \u2014 when the human corrects your approach (\`importance: critical\`)
10939
+ - **Preferences**: How they want things done \u2014 tone, format, workflow, style (\`importance: high\`)
10940
+ - **Patterns**: Approaches that consistently work or fail (\`importance: medium\`)
10941
+ - **Domain facts**: Business context, project-specific knowledge, key relationships (\`importance: medium\`)
10942
+ - **Insights**: Non-obvious connections, meta-observations about the work (\`importance: low\`)
10943
+
10944
+ Record immediately when: the human corrects you, expresses a preference, shares context about their business, reacts strongly to something (positive or negative), or you discover something that would help future tasks.`;
10882
10945
  function buildWorkerDirective(ctx) {
10883
10946
  return `${identityBlock(ctx)}
10884
10947
 
@@ -10915,15 +10978,19 @@ Tools: deskfree_state, deskfree_start_task, deskfree_read_file, deskfree_create_
10915
10978
  - Always pass \`taskId\` when creating or updating files \u2014 this threads notifications into the task.
10916
10979
  - If you discover work that falls outside your task's scope, use \`deskfree_propose\` to suggest follow-up tasks immediately \u2014 don't wait until completion. Propose as you discover, then stay focused on your current task.
10917
10980
 
10918
- **Learnings:**
10919
- - Use \`deskfree_learning\` to record observations worth remembering. Set the \`importance\` parameter:
10920
- - **critical**: corrections, constraints that must never be violated
10921
- - **high**: strong preferences, important patterns
10922
- - **medium**: useful context, moderate preferences
10923
- - **low** (default): routine observations
10924
- - Record: preferences, corrections, patterns, domain facts.
10925
- - Do NOT record one-time task details, things in project docs, or obvious/generic knowledge.
10926
- - A nightly sleep cycle consolidates observations into long-term memory with decay scoring.
10981
+ **Learnings \u2014 record aggressively:**
10982
+ Use \`deskfree_learning\` to record anything worth remembering. **Err on the side of recording too much** \u2014 the nightly sleep cycle will consolidate and prune. You lose nothing by over-recording, but you lose knowledge by under-recording.
10983
+
10984
+ Record across all five types:
10985
+ - **Corrections**: "Do X, not Y" \u2014 when the human corrects your approach (\`importance: critical\`)
10986
+ - **Preferences**: How they want things done \u2014 tone, format, workflow, style (\`importance: high\`)
10987
+ - **Patterns**: Approaches that consistently work or fail (\`importance: medium\`)
10988
+ - **Domain facts**: Business context, project-specific knowledge, key relationships (\`importance: medium\`)
10989
+ - **Insights**: Non-obvious connections, meta-observations about the work (\`importance: low\`)
10990
+
10991
+ Record immediately when: the human corrects you, expresses a preference, shares context about their business, reacts strongly to something, or you discover something that would help future tasks.
10992
+
10993
+ Do NOT record: one-time task details, things already in project docs, or obvious/generic knowledge.
10927
10994
 
10928
10995
  **Memory recall:**
10929
10996
  - Use \`deskfree_orient\` to recall relevant memories mid-task. Call with a specific query for targeted semantic search.
@@ -10972,15 +11039,19 @@ Tools: deskfree_state, deskfree_start_task, deskfree_read_file, deskfree_create_
10972
11039
  - Always pass \`taskId\` when creating or updating files \u2014 this threads notifications into the task.
10973
11040
  - If you discover work that falls outside your task's scope, use \`deskfree_propose\` to suggest follow-up tasks immediately \u2014 don't wait until completion. Propose as you discover, then stay focused on your current task.
10974
11041
 
10975
- **Learnings:**
10976
- - Use \`deskfree_learning\` to record observations worth remembering. Set the \`importance\` parameter:
10977
- - **critical**: corrections, constraints that must never be violated
10978
- - **high**: strong preferences, important patterns
10979
- - **medium**: useful context, moderate preferences
10980
- - **low** (default): routine observations
10981
- - Record: preferences, corrections, patterns, domain facts.
10982
- - Do NOT record one-time task details, things in project docs, or obvious/generic knowledge.
10983
- - A nightly sleep cycle consolidates observations into long-term memory with decay scoring.
11042
+ **Learnings \u2014 record aggressively:**
11043
+ Use \`deskfree_learning\` to record anything worth remembering. **Err on the side of recording too much** \u2014 the nightly sleep cycle will consolidate and prune. You lose nothing by over-recording, but you lose knowledge by under-recording.
11044
+
11045
+ Record across all five types:
11046
+ - **Corrections**: "Do X, not Y" \u2014 when the human corrects your approach (\`importance: critical\`)
11047
+ - **Preferences**: How they want things done \u2014 tone, format, workflow, style (\`importance: high\`)
11048
+ - **Patterns**: Approaches that consistently work or fail (\`importance: medium\`)
11049
+ - **Domain facts**: Business context, project-specific knowledge, key relationships (\`importance: medium\`)
11050
+ - **Insights**: Non-obvious connections, meta-observations about the work (\`importance: low\`)
11051
+
11052
+ Record immediately when: the human corrects you, expresses a preference, shares context about their business, reacts strongly to something, or you discover something that would help future tasks.
11053
+
11054
+ Do NOT record: one-time task details, things already in project docs, or obvious/generic knowledge.
10984
11055
 
10985
11056
  **Memory recall:**
10986
11057
  - Use \`deskfree_orient\` to recall relevant memories mid-task. Call with a specific query for targeted semantic search.
@@ -12068,7 +12139,8 @@ async function startGateway(config) {
12068
12139
  log,
12069
12140
  abortSignal,
12070
12141
  onMessage: config.onMessage,
12071
- getWorkerStatus: config.getWorkerStatus
12142
+ getWorkerStatus: config.getWorkerStatus,
12143
+ onConsolidate: config.onConsolidate
12072
12144
  });
12073
12145
  totalReconnects++;
12074
12146
  } catch (err) {
@@ -12321,6 +12393,34 @@ async function runWebSocketConnection(opts) {
12321
12393
  })
12322
12394
  );
12323
12395
  }
12396
+ } else if (msg.action === "consolidate") {
12397
+ if (opts.onConsolidate && ws.readyState === wrapper_default2.OPEN) {
12398
+ opts.onConsolidate().then(
12399
+ (consolidateStatus) => {
12400
+ if (ws.readyState === wrapper_default2.OPEN) {
12401
+ ws.send(
12402
+ JSON.stringify({
12403
+ action: "consolidateResponse",
12404
+ status: consolidateStatus
12405
+ })
12406
+ );
12407
+ }
12408
+ },
12409
+ (consolidateErr) => {
12410
+ const errMsg = consolidateErr instanceof Error ? consolidateErr.message : String(consolidateErr);
12411
+ log.warn(`On-demand consolidation failed: ${errMsg}`);
12412
+ if (ws.readyState === wrapper_default2.OPEN) {
12413
+ ws.send(
12414
+ JSON.stringify({
12415
+ action: "consolidateResponse",
12416
+ status: "error",
12417
+ error: errMsg
12418
+ })
12419
+ );
12420
+ }
12421
+ }
12422
+ );
12423
+ }
12324
12424
  }
12325
12425
  } catch (err) {
12326
12426
  const message = err instanceof Error ? err.message : String(err);
@@ -14166,7 +14266,8 @@ async function startAgent(opts) {
14166
14266
  log
14167
14267
  }
14168
14268
  );
14169
- }
14269
+ },
14270
+ onConsolidate: () => runConsolidation()
14170
14271
  });
14171
14272
  scheduleHeartbeat(
14172
14273
  createOrchServer,
@@ -14177,64 +14278,76 @@ async function startAgent(opts) {
14177
14278
  config.claudeCodePath,
14178
14279
  agentContext
14179
14280
  );
14281
+ let isConsolidating = false;
14282
+ async function runConsolidation() {
14283
+ if (isConsolidating) {
14284
+ log.info("Consolidation already in progress, skipping");
14285
+ return "already_running";
14286
+ }
14287
+ isConsolidating = true;
14288
+ try {
14289
+ let orientResult;
14290
+ try {
14291
+ orientResult = await client.orient({ consolidation: true });
14292
+ } catch (err) {
14293
+ const msg = err instanceof Error ? err.message : String(err);
14294
+ log.warn(`Sleep cycle: orient() failed: ${msg}`);
14295
+ return "error";
14296
+ }
14297
+ if (orientResult.entries.length === 0) {
14298
+ log.info("Sleep cycle: no unconsolidated entries to process, skipping");
14299
+ return "noop";
14300
+ }
14301
+ const unconsolidatedSection = orientResult.entries.map(
14302
+ (e) => `- [${e.entryId}] ${e.importance ? `(${e.importance}) ` : ""}${e.content}`
14303
+ ).join("\n");
14304
+ const relatedSection = orientResult.recentEntries && orientResult.recentEntries.length > 0 ? orientResult.recentEntries.map(
14305
+ (e) => `- [${e.entryId}] [${e.type ?? "unclassified"}] s:${e.strength} \u2014 ${e.content}`
14306
+ ).join("\n") : "(none)";
14307
+ const dedupSection = orientResult.dedupCandidates && orientResult.dedupCandidates.length > 0 ? orientResult.dedupCandidates.map(
14308
+ (d) => `- ${d.entryId1} \u2194 ${d.entryId2} (similarity: ${d.similarity.toFixed(3)})`
14309
+ ).join("\n") : "(none)";
14310
+ const prompt = [
14311
+ "<current_operating_memory>",
14312
+ orientResult.operatingMemory || "(empty \u2014 first consolidation)",
14313
+ "</current_operating_memory>",
14314
+ "",
14315
+ "<unconsolidated_entries>",
14316
+ unconsolidatedSection,
14317
+ "</unconsolidated_entries>",
14318
+ "",
14319
+ "<related_active_entries>",
14320
+ relatedSection,
14321
+ "</related_active_entries>",
14322
+ "",
14323
+ "<dedup_candidates>",
14324
+ dedupSection,
14325
+ "</dedup_candidates>",
14326
+ "",
14327
+ "Run your nightly consolidation cycle now."
14328
+ ].join("\n");
14329
+ log.info(
14330
+ `Sleep cycle: invoking sleep agent (${orientResult.entries.length} unconsolidated entries)...`
14331
+ );
14332
+ const workerServer = createWorkServer();
14333
+ const result = runOneShotWorker({
14334
+ prompt,
14335
+ systemPrompt: buildSleepDirective(agentContext),
14336
+ workerServer,
14337
+ model: config.model
14338
+ });
14339
+ for await (const _ of result) {
14340
+ }
14341
+ return "success";
14342
+ } finally {
14343
+ isConsolidating = false;
14344
+ }
14345
+ }
14180
14346
  if (config.sleepHour !== null && config.timezone) {
14181
14347
  scheduleDailyCycle(
14182
14348
  "Sleep",
14183
14349
  async () => {
14184
- let orientResult;
14185
- try {
14186
- orientResult = await client.orient({ consolidation: true });
14187
- } catch (err) {
14188
- const msg = err instanceof Error ? err.message : String(err);
14189
- log.warn(`Sleep cycle: orient() failed: ${msg}`);
14190
- return;
14191
- }
14192
- if (orientResult.entries.length === 0) {
14193
- log.info(
14194
- "Sleep cycle: no unconsolidated entries to process, skipping"
14195
- );
14196
- return;
14197
- }
14198
- const unconsolidatedSection = orientResult.entries.map(
14199
- (e) => `- [${e.entryId}] ${e.importance ? `(${e.importance}) ` : ""}${e.content}`
14200
- ).join("\n");
14201
- const relatedSection = orientResult.recentEntries && orientResult.recentEntries.length > 0 ? orientResult.recentEntries.map(
14202
- (e) => `- [${e.entryId}] [${e.type ?? "unclassified"}] s:${e.strength} \u2014 ${e.content}`
14203
- ).join("\n") : "(none)";
14204
- const dedupSection = orientResult.dedupCandidates && orientResult.dedupCandidates.length > 0 ? orientResult.dedupCandidates.map(
14205
- (d) => `- ${d.entryId1} \u2194 ${d.entryId2} (similarity: ${d.similarity.toFixed(3)})`
14206
- ).join("\n") : "(none)";
14207
- const prompt = [
14208
- "<current_operating_memory>",
14209
- orientResult.operatingMemory || "(empty \u2014 first consolidation)",
14210
- "</current_operating_memory>",
14211
- "",
14212
- "<unconsolidated_entries>",
14213
- unconsolidatedSection,
14214
- "</unconsolidated_entries>",
14215
- "",
14216
- "<related_active_entries>",
14217
- relatedSection,
14218
- "</related_active_entries>",
14219
- "",
14220
- "<dedup_candidates>",
14221
- dedupSection,
14222
- "</dedup_candidates>",
14223
- "",
14224
- "Run your nightly consolidation cycle now."
14225
- ].join("\n");
14226
- log.info(
14227
- `Sleep cycle: invoking sleep agent (${orientResult.entries.length} unconsolidated entries)...`
14228
- );
14229
- const workerServer = createWorkServer();
14230
- const result = runOneShotWorker({
14231
- prompt,
14232
- systemPrompt: buildSleepDirective(agentContext),
14233
- workerServer,
14234
- model: config.model
14235
- });
14236
- for await (const _ of result) {
14237
- }
14350
+ await runConsolidation();
14238
14351
  },
14239
14352
  config.sleepHour,
14240
14353
  config.timezone,