UNPKG

@sellable/install

Version:

One-command installer for Sellable MCP in Claude Code, Codex, and Hermes

209 lines (205 loc) • 9.57 kB
import { execFile } from "node:child_process"; import { lstatSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import { promisify } from "node:util"; export function firstCampaignWelcome(botUserId) { if (!/^[UW][A-Z0-9]+$/.test(botUserId ?? "") || /[\r\n\0]/.test(botUserId)) throw new Error("first_welcome_identity_rejected"); return [ // Hermes converts standard Markdown to Slack mrkdwn. Single stars here // became italics in the 2026-09-19 whole-image welcome receipt. "**Hi, I'm your Sellable Agent. I run your LinkedIn outbound from Slack.**", // The goal first, so every later step reads as progress toward it. "**Our first goal:** launch your first campaign and start getting replies, so we learn what works for you.", [ "**How it works**", "1. You send me your LinkedIn profile. I research you and your company.", // One word for each approval, the same words the plan uses: yes // approves the plan, launch starts sending. "Say go when you approve // the plan" read as if approving the plan launched it (2026-11-19). "2. I bring back a campaign plan: who to reach, what to offer and where to find them. You reply **yes** to approve it.", // Owner, 2026-12-01: "we want approval of message before coitning": // the list fills after the customer's yes to the first message. "3. I show you the first message for a real person. Reply **yes**, and I fill your list.", // Sending needs the customer's LinkedIn account; the hello said "I // send" before any was connected (round-9 journey pass, 2026-11-19). "4. You connect LinkedIn and reply **launch**. I send and bring every reply here with an answer ready. Or reply **yes, launch** to the plan.", ].join("\n"), // One ask. The onboarding skill starts from a profile URL in this thread. // Owner, 2026-12-01: "can you at end say...also if you alreay know the // camapign you want to run, just tell us who you want to reach and what // you want to say and well draft that". The plan already takes that // answer; the welcome now offers it from the start. "**Your move**\n1. Reply in this thread with your LinkedIn profile URL.\nAlready know the campaign you want to run? Tell me who you want to reach and what you want to say, and I'll draft that.", // A reply in a thread this bot started needs no mention: the gateway // wakes on a bot-authored thread root. A new conversation does need one. `Nothing is sent on LinkedIn until you say **launch**.\nTo talk to me later, reply in one of my threads or tag <@${botUserId}>. To have me listen in other channels, add them in the Sellable app under Agent.`, ].join("\n\n"); } // Hand the welcome to the live gateway through Hermes' durable delivery queue // (cron/deliveries.db), the queue restart-safe cron workers use for their final // send. The gateway watches that file once a second and drains it through its // live Slack adapter, so the hello posts as soon as it is queued. A one-shot // cron job waited for the next 60 s ticker pass instead: the hello came about // 53 s after "Sellable is live" (production walk, 2026-11-20). Do not send to // Slack from this script or start an LLM merely to print the welcome. // // The queue keys each send on its execution id and never retries a send that // may have happened. The id here is fixed per Agent, channel and bot, so a // retried enqueue (a crash between DISPATCHING and QUEUED, a restart) finds // the same row and cannot queue a second welcome. The intent lives under cron/ // so native snapshots retain it. const PREPARE = String.raw` import fcntl,hashlib,json,os,sys,tempfile from datetime import datetime,timezone from pathlib import Path from cron.delivery_queue import enqueue from cron.jobs import load_jobs v=json.loads(sys.argv[1]) root=Path(os.environ['HERMES_HOME']) cron=root/'cron' cron.mkdir(mode=0o700,exist_ok=True) name='sellable-first-welcome' marker=cron/(name+'.json') scope={k:v[k] for k in ['workspaceId','channelId','botUserId']} key=hashlib.sha256(json.dumps(scope,sort_keys=True).encode()).hexdigest() execution_id=name+'-'+key[:24] def save(path,value): fd,tmp=tempfile.mkstemp(dir=path.parent,prefix='.'+path.name) try: with os.fdopen(fd,'w') as f: f.write(value); f.flush(); os.fsync(f.fileno()) os.replace(tmp,path) directory=os.open(path.parent,os.O_RDONLY|os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) finally: if os.path.exists(tmp): os.unlink(tmp) def result(**value): print(json.dumps(value)) def dispatch(state): state.update(status='DISPATCHING',executionId=execution_id) save(marker,json.dumps(state)) # The record a native no-agent one-shot would carry. Slack's bot-authored # parent already supports normal thread replies; attach_to_session would # prepend a separate "Hermes — job" seed message and bury the welcome. job={'id':key[:12],'name':name,'prompt':'','skills':[],'skill':None,'script':None, 'no_agent':True,'deliver':'slack:'+v['channelId'],'failure_deliver':'local', 'origin':{'platform':'slack','chat_id':v['channelId']},'attach_to_session':False, 'repeat':{'times':1,'completed':0},'enabled':True,'state':'scheduled', 'created_at':datetime.now(timezone.utc).isoformat(),'execution_id':execution_id} row=enqueue(execution_id,job,v['message']) state['status']='QUEUED' save(marker,json.dumps(state)) result(ok=True,status='QUEUED',executionId=execution_id,delivery=row.get('status')) with os.fdopen(os.open(cron/(name+'.lock'),os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600),'a') as lock: fcntl.flock(lock,fcntl.LOCK_EX) if marker.is_symlink(): raise ValueError('unsafe welcome marker') jobs=load_jobs() state=json.loads(marker.read_text()) if marker.exists() else None if state is None: existing=not v['newAgent'] or any(j.get('name')=='sellable-first-campaign-onboarding' for j in jobs) state={'schemaVersion':1,**scope,'status':'EXISTING' if existing else 'PENDING'} save(marker,json.dumps(state)) if any(state.get(k)!=val for k,val in scope.items()): result(ok=False,code='first_welcome_scope_mismatch') elif state['status'] in ['EXISTING','QUEUED'] or not v['ready']: result(ok=True,status=state['status'],jobId=state.get('jobId'),executionId=state.get('executionId')) elif state['status']=='DISPATCHING': if state.get('executionId')==execution_id: # Same key, same row: finishing the enqueue cannot greet twice. dispatch(state) else: # A crash in the older cron-job dispatch: whether its job was # created is unknown. Never read uncertainty as permission to send. result(ok=False,code='first_welcome_dispatch_uncertain') elif state['status']=='PENDING': if any(j.get('name')==name for j in jobs): result(ok=False,code='first_welcome_inventory_rejected') else: dispatch(state) else: result(ok=False,code='first_welcome_state_rejected') `; /** Prepare before installing the daily cron; enqueue only after ready/complete. * QUEUED means the gateway's delivery queue owns the send, NOT that Slack * delivery succeeded. * Failure must never turn a healthy Agent into failed web onboarding. */ export async function ensureHermesFirstWelcome({ profileId, profileRoot, hermesRoot, workspaceId, channelId, botUserId, newAgent = false, ready = false, hermesPython = "/opt/hermes/.venv/bin/python", runChild, }) { try { if ( !/^[a-zA-Z0-9_-]+$/.test(profileId ?? "") || !/^[a-zA-Z0-9_-]+$/.test(workspaceId ?? "") || !/^C[A-Z0-9]+$/.test(channelId ?? "") || /[\r\n\0]/.test(`${profileId}${workspaceId}${channelId}`) || !isAbsolute(hermesRoot) || resolve(profileRoot) !== join(resolve(hermesRoot), "profiles", profileId) ) return { ok: false, code: "first_welcome_identity_rejected" }; for (const path of [ hermesRoot, join(hermesRoot, "profiles"), profileRoot, join(profileRoot, "cron"), ]) { try { if (!lstatSync(path).isDirectory()) return { ok: false, code: "first_welcome_path_rejected" }; } catch (e) { if (e.code !== "ENOENT" || path !== join(profileRoot, "cron")) throw e; } } const message = firstCampaignWelcome(botUserId); const input = { command: hermesPython, args: [ "-c", PREPARE, JSON.stringify({ workspaceId, channelId, botUserId, newAgent: newAgent === true, ready: ready === true, message, }), ], env: { ...process.env, HOME: hermesRoot, HERMES_HOME: profileRoot, HERMES_PROFILE: profileId, NO_COLOR: "1", }, timeoutMs: 30_000, shell: false, }; const child = runChild ? await runChild(input) : { exitCode: 0, ...(await promisify(execFile)(input.command, input.args, { env: input.env, timeout: input.timeoutMs, maxBuffer: 64 * 1024, })), }; if (child.exitCode !== 0 || child.timedOut) throw new Error("native child failed"); return JSON.parse(child.stdout.trim()); } catch { return { ok: false, code: "first_welcome_prepare_failed" }; } }