11#!/usr/bin/env node
22
33import { spawn , spawnSync } from 'node:child_process'
4- import { existsSync , mkdirSync , readdirSync , readFileSync , realpathSync , rmSync , writeFileSync } from 'node:fs'
4+ import { existsSync , mkdirSync , readdirSync , readFileSync , realpathSync , rmSync , unlinkSync , writeFileSync } from 'node:fs'
55import { homedir , platform , tmpdir } from 'node:os'
66import { basename , join , resolve } from 'node:path'
77import { fileURLToPath , pathToFileURL } from 'node:url'
@@ -118,20 +118,37 @@ export function shotDirCandidates() {
118118}
119119
120120export function configDir ( ) {
121- return join ( homedir ( ) , '.agentshot' )
121+ return configDirCandidates ( ) [ 0 ]
122+ }
123+
124+ export function configDirCandidates ( ) {
125+ const configured = process . env . AGENTSHOT_HOME ?. trim ( )
126+ return [
127+ configured ,
128+ join ( homedir ( ) , '.agentshot' ) ,
129+ join ( tmpdir ( ) , 'agentshot' ) ,
130+ ] . filter ( Boolean )
122131}
123132
124133export function daemonLogPath ( ) {
125- return join ( configDir ( ) , 'daemon.log' )
134+ return join ( ensureConfigDir ( ) , 'daemon.log' )
126135}
127136
128137export function daemonConfigPath ( ) {
129- return join ( configDir ( ) , 'daemon.json' )
138+ return join ( ensureConfigDir ( ) , 'daemon.json' )
130139}
131140
132141function ensureConfigDir ( ) {
133- mkdirSync ( configDir ( ) , { recursive : true } )
134- return configDir ( )
142+ const errors = [ ]
143+ for ( const dir of configDirCandidates ( ) ) {
144+ try {
145+ mkdirSync ( dir , { recursive : true } )
146+ return dir
147+ } catch ( error ) {
148+ errors . push ( `${ dir } : ${ error instanceof Error ? error . message : String ( error ) } ` )
149+ }
150+ }
151+ throw new Error ( `Unable to create AgentShot config directory. Tried: ${ errors . join ( '; ' ) } ` )
135152}
136153
137154function currentScriptPath ( ) {
@@ -383,23 +400,23 @@ export function renderPrompt(file, options) {
383400 const ask = options . ask ?. trim ( )
384401 const templates = {
385402 claude : ask
386- ? `${ ask } \n\nPlease inspect this local image:\n ${ pathForPrompt } `
387- : `Please inspect this local image:\n ${ pathForPrompt } ` ,
403+ ? `${ ask } Please inspect this local image: ${ pathForPrompt } `
404+ : `Please inspect this local image: ${ pathForPrompt } ` ,
388405 codex : ask
389- ? `${ ask } \n\nAnalyze this local screenshot:\n ${ pathForPrompt } `
390- : `Analyze this local screenshot:\n ${ pathForPrompt } ` ,
406+ ? `${ ask } Analyze this local screenshot: ${ pathForPrompt } `
407+ : `Analyze this local screenshot: ${ pathForPrompt } ` ,
391408 aider : ask
392- ? `${ ask } \n\nUse this image as context:\n ${ pathForPrompt } `
393- : `Use this image as context:\n ${ pathForPrompt } ` ,
409+ ? `${ ask } Use this image as context: ${ pathForPrompt } `
410+ : `Use this image as context: ${ pathForPrompt } ` ,
394411 gemini : ask
395- ? `${ ask } \n\nReview this local image:\n ${ pathForPrompt } `
396- : `Review this local image:\n ${ pathForPrompt } ` ,
412+ ? `${ ask } Review this local image: ${ pathForPrompt } `
413+ : `Review this local image: ${ pathForPrompt } ` ,
397414 opencode : ask
398- ? `${ ask } \n\nInspect this screenshot file:\n ${ pathForPrompt } `
399- : `Inspect this screenshot file:\n ${ pathForPrompt } ` ,
415+ ? `${ ask } Inspect this screenshot file: ${ pathForPrompt } `
416+ : `Inspect this screenshot file: ${ pathForPrompt } ` ,
400417 generic : ask
401- ? `${ ask } \n\nImage path:\n ${ pathForPrompt } `
402- : `Please analyze this local image:\n ${ pathForPrompt } ` ,
418+ ? `${ ask } Image path: ${ pathForPrompt } `
419+ : `Please analyze this local image: ${ pathForPrompt } ` ,
403420 }
404421 return templates [ options . tool ] ?? templates . generic
405422}
@@ -414,10 +431,21 @@ async function copyText(text) {
414431 }
415432
416433 if ( platform ( ) === 'win32' ) {
417- const child = spawn ( 'powershell.exe' , [ '-NoProfile' , '-Command' , 'Set-Clipboard -Value ([Console]::In.ReadToEnd())' ] )
418- child . stdin . write ( text )
419- child . stdin . end ( )
420- await waitForChild ( child , 'Set-Clipboard' )
434+ const clipboardTextPath = join ( tmpdir ( ) , `agentshot-clipboard-${ process . pid } -${ Date . now ( ) } .txt` )
435+ writeFileSync ( clipboardTextPath , text , 'utf8' )
436+ const script = `
437+ $text = Get-Content -LiteralPath '${ escapePowerShellSingleQuoted ( clipboardTextPath ) } ' -Raw -Encoding UTF8
438+ Set-Clipboard -Value $text
439+ `
440+ try {
441+ await powershell ( [ '-Command' , script ] , 'ignore' )
442+ } finally {
443+ try {
444+ unlinkSync ( clipboardTextPath )
445+ } catch {
446+ // Temporary clipboard file cleanup is best-effort.
447+ }
448+ }
421449 return
422450 }
423451
@@ -508,9 +536,10 @@ async function watchClipboard(options) {
508536 }
509537}
510538
511- function daemonArgs ( options ) {
539+ function daemonArgs ( options , settings = { } ) {
540+ const includeAsk = settings . includeAsk ?? true
512541 const args = [ 'daemon' , 'run' , '--tool' , options . tool , '--interval' , String ( options . intervalMs ) ]
513- if ( options . ask ) args . push ( '--ask' , options . ask )
542+ if ( includeAsk && options . ask ) args . push ( '--ask' , options . ask )
514543 if ( options . paste ) args . push ( '--paste' )
515544 if ( options . wsl ) args . push ( '--wsl' )
516545 return args
@@ -537,6 +566,19 @@ function readDaemonConfig() {
537566 }
538567}
539568
569+ function applyDaemonConfig ( options ) {
570+ const config = readDaemonConfig ( )
571+ if ( ! config ) return options
572+ return {
573+ ...options ,
574+ ask : options . ask || config . ask || '' ,
575+ tool : options . tool === 'generic' && config . tool ? config . tool : options . tool ,
576+ paste : options . paste || Boolean ( config . paste ) ,
577+ wsl : options . wsl || Boolean ( config . wsl ) ,
578+ intervalMs : options . intervalMs === 800 && config . intervalMs ? config . intervalMs : options . intervalMs ,
579+ }
580+ }
581+
540582function shellQuoteWindows ( value ) {
541583 return `"${ String ( value ) . replaceAll ( '"' , '\\"' ) } "`
542584}
@@ -551,24 +593,71 @@ function installWindowsDaemon(options) {
551593 const node = process . execPath
552594 const script = currentScriptPath ( )
553595 const log = daemonLogPath ( )
554- const taskCommand = [
555- shellQuoteWindows ( node ) ,
556- shellQuoteWindows ( script ) ,
557- ...daemonArgs ( options ) . map ( shellQuoteWindows ) ,
558- '>>' ,
559- shellQuoteWindows ( log ) ,
560- '2>>&1' ,
561- ] . join ( ' ' )
562- const taskRun = `powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -Command ${ shellQuoteWindows ( taskCommand ) } `
596+ const runnerPath = join ( ensureConfigDir ( ) , 'daemon-run.cmd' )
597+ const runner = [
598+ '@echo off' ,
599+ 'setlocal' ,
600+ `set "AGENTSHOT_HOME=${ ensureConfigDir ( ) } "` ,
601+ `set "AGENTSHOT_DIR=${ ensureShotDir ( ) } "` ,
602+ ':loop' ,
603+ `echo [%date% %time%] AgentShot daemon starting.>> "${ log } "` ,
604+ `${ shellQuoteWindows ( node ) } ${ shellQuoteWindows ( script ) } ${ daemonArgs ( options , { includeAsk : false } ) . map ( shellQuoteWindows ) . join ( ' ' ) } >> "${ log } " 2>&1` ,
605+ `echo [%date% %time%] AgentShot daemon exited with code %ERRORLEVEL%. Restarting in 2s.>> "${ log } "` ,
606+ 'timeout /t 2 /nobreak >nul' ,
607+ 'goto loop' ,
608+ '' ,
609+ ] . join ( '\r\n' )
610+ writeFileSync ( runnerPath , `${ runner } \r\n` )
611+ const taskRun = shellQuoteWindows ( runnerPath )
563612 const result = spawnSync ( 'schtasks.exe' , [ '/Create' , '/TN' , taskName , '/SC' , 'ONLOGON' , '/TR' , taskRun , '/F' ] , {
564613 shell : false ,
565614 stdio : 'pipe' ,
566615 encoding : 'utf8' ,
567616 } )
568- if ( result . status !== 0 ) throw new Error ( result . stderr . trim ( ) || result . stdout . trim ( ) || 'Failed to create scheduled task.' )
617+ if ( result . status !== 0 ) {
618+ return installWindowsStartupFallback ( runnerPath , result . stderr . trim ( ) || result . stdout . trim ( ) )
619+ }
620+ startWindowsRunner ( runnerPath )
569621 return `Installed Windows scheduled task: ${ taskName } `
570622}
571623
624+ function startWindowsRunner ( runnerPath ) {
625+ const child = spawn ( 'cmd.exe' , [ '/d' , '/c' , runnerPath ] , {
626+ shell : false ,
627+ stdio : 'ignore' ,
628+ windowsHide : true ,
629+ detached : true ,
630+ } )
631+ child . unref ( )
632+ }
633+
634+ function installWindowsStartupFallback ( runnerPath , reason ) {
635+ const startupDir = join (
636+ process . env . APPDATA || join ( homedir ( ) , 'AppData' , 'Roaming' ) ,
637+ 'Microsoft' ,
638+ 'Windows' ,
639+ 'Start Menu' ,
640+ 'Programs' ,
641+ 'Startup' ,
642+ )
643+ mkdirSync ( startupDir , { recursive : true } )
644+ const startupScript = join ( startupDir , 'AgentShot.cmd' )
645+ writeFileSync (
646+ startupScript ,
647+ [
648+ '@echo off' ,
649+ `start "" /min ${ shellQuoteWindows ( runnerPath ) } ` ,
650+ '' ,
651+ ] . join ( '\r\n' ) ,
652+ )
653+ startWindowsRunner ( runnerPath )
654+ return `Installed Windows Startup fallback: ${ startupScript } ${ reason ? ` (scheduled task unavailable: ${ reason } )` : '' } `
655+ }
656+
657+ function toPowerShellLiteral ( value ) {
658+ return `'${ escapePowerShellSingleQuoted ( String ( value ) ) } '`
659+ }
660+
572661function installMacOSDaemon ( options ) {
573662 writeDaemonConfig ( options )
574663 const label = 'com.junchenmeteor.agentshot'
@@ -746,7 +835,7 @@ export async function main(argv = process.argv.slice(2)) {
746835 if ( options . daemonAction && options . daemonAction !== 'run' ) {
747836 throw new Error ( `Unknown daemon action: ${ options . daemonAction } ` )
748837 }
749- await watchClipboard ( options )
838+ await watchClipboard ( options . daemonAction === 'run' ? applyDaemonConfig ( options ) : options )
750839 return
751840 }
752841 if ( command === 'watch' ) {
@@ -762,7 +851,7 @@ export async function main(argv = process.argv.slice(2)) {
762851 else if ( command === 'clipboard' ) file = await saveClipboardScreenshot ( )
763852 else if ( command === 'last' ) {
764853 const latest = latestShotPath ( )
765- if ( ! latest ) throw new Error ( `No saved screenshots found in ${ shotDir ( ) } ` )
854+ if ( ! latest ) throw new Error ( `No saved screenshots found in ${ ensureShotDir ( ) } ` )
766855 file = latest
767856 } else {
768857 throw new Error ( `Unknown command: ${ command } ` )
0 commit comments