Personal Telegram developer console for GitHub
feat(cp7): add durable policy-aware automation engine
* feat(cp7): add durable workflow state machine * feat(cp7): add durable automation store * feat(cp7): add automation store client * feat(cp7): add policy aware automation runner * test(cp7): cover workflow pause resume and idempotency * feat(cp7): export automation durable object * feat(cp7): bind dedicated automation store * fix(cp7): make inspect transition side effect free * fix(cp7): preserve webhook fail-closed responses
davoodmehraban89 committed
Oct 5, 2026 at 06:23 UTC
b65f013347332e8e54850d581982c884c99f64d5
7 files changed
+11
-18
src/core/automation-runner.js
new
+1
@@ -0,0 +1 @@
1
+import {transitionAutomation} from './automation.js';export class AutomationRunner{constructor({router,store}){this.router=router;this.store=store;}async advance(state){const step=state.steps[state.cursor];if(!step)return state;const routed=await this.router.dispatchCallback(step.callback,{isOwner:true,ownerId:state.ownerId});if(!routed)throw new Error('Automation action unavailable');if(routed.requiresApproval){const next=transitionAutomation(state,{type:'pause',intent:{pluginId:routed.pluginId,actionId:routed.actionId,risk:routed.risk,input:routed.approval?.input,callback:step.callback,key:step.key}});await this.store.put(next);return next;}const checkpoint=await this.store.put(state);const result=routed.execute?await routed.execute():routed;const next=transitionAutomation(checkpoint,{type:'complete_step',key:step.key});await this.store.put(next);return {...next,lastResult:result};}async resume(state,{approval,key}){if(!approval||state.approvalIntent?.key!==key)throw new Error('Matching approval required');const resumed=transitionAutomation(state,{type:'resume',key});await this.store.put(resumed);return resumed;}}
src/core/automation-store.js
new
+1
@@ -0,0 +1 @@
1
+export class DurableAutomationStoreClient{constructor({namespace,ownerId}){this.namespace=namespace;this.ownerId=String(ownerId||'');}stub(id){if(!this.namespace||!this.ownerId)throw new Error('Automation store is not configured');return this.namespace.get(this.namespace.idFromName(`owner:${this.ownerId}:automation:${id}`));}async get(id){const r=await this.stub(id).fetch(`https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(id)}`);if(r.status===404)return null;if(!r.ok)throw new Error('Automation read failed');return r.json();}async put(state){const r=await this.stub(state.id).fetch(`https://automation.local/?owner=${encodeURIComponent(this.ownerId)}&id=${encodeURIComponent(state.id)}`,{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(state)});if(!r.ok)throw new Error('Automation write failed');return r.json();}}
src/core/automation.js
new
+2
@@ -0,0 +1,2 @@
1
+export const createAutomation=({id,ownerId,recipe,steps=[]})=>({version:1,id,ownerId:String(ownerId),recipe,status:'ready',cursor:0,steps,completedKeys:[],updatedAt:Date.now()});
2
+export function transitionAutomation(state,event={}){if(event.type==='inspect')return structuredClone(state);const s=structuredClone(state);if(['completed','cancelled','failed'].includes(s.status))throw new Error('Automation is terminal');if(event.type==='cancel'){s.status='cancelled';}else if(event.type==='fail'){s.status='failed';s.error=String(event.error||'failed');}else if(event.type==='pause'){s.status='awaiting_approval';s.approvalIntent=event.intent;}else if(event.type==='resume'){if(s.status!=='awaiting_approval')throw new Error('Automation is not awaiting approval');if(event.key&&s.completedKeys.includes(event.key))throw new Error('Automation step already executed');s.status='ready';delete s.approvalIntent;}else if(event.type==='complete_step'){if(event.key&&s.completedKeys.includes(event.key))return s;if(event.key)s.completedKeys.push(event.key);s.cursor++;s.status=s.cursor>=s.steps.length?'completed':'ready';}else throw new Error('Unsupported automation transition');s.updatedAt=Date.now();return s;}
src/durable/automation-store.js
new
+1
@@ -0,0 +1 @@
1
+const json=(x,s=200)=>new Response(JSON.stringify(x),{status:s,headers:{'content-type':'application/json'}});export class AutomationStore{constructor(state){this.storage=state.storage;}async fetch(req){const u=new URL(req.url),owner=u.searchParams.get('owner')||'',id=u.searchParams.get('id')||'';if(!owner||!id)return json({error:'owner/id required'},400);const key=`automation:${owner}:${id}`;if(req.method==='GET'){const v=await this.storage.get(key);return v?json(v):json({error:'not found'},404);}if(req.method==='PUT'){const body=await req.json();if(String(body.ownerId)!==owner||body.id!==id||body.version!==1)return json({error:'invalid state'},400);await this.storage.put(key,body);return json(body);}return json({error:'not found'},404);}}
src/index.js
+2
-12
@@ -4,15 +4,5 @@ import { handleWorkspaceEditorRequest, workspaceEditorPageResponse } from './wor
4
export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
5
export { WorkspaceStore } from './durable/workspace-store.js';
6
export { IncidentStore } from './durable/incident-store.js';
7
-
8
-const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), { status, headers: { 'Content-Type': 'application/json; charset=utf-8' } });
9
-const publicHealthPayload = () => ({ status: 'online', bot: 'Nexa Dev Bot', version: '1.1.1', mode: 'Cloudflare Worker Webhook' });
10
-function senderIdFromUpdate(update) { return update?.message?.from?.id ?? update?.callback_query?.from?.id ?? null; }
11
-function isOwnerUpdate(update, env) { if (!env.OWNER_TELEGRAM_ID) return false; const senderId = senderIdFromUpdate(update); return senderId !== null && String(senderId) === String(env.OWNER_TELEGRAM_ID); }
12
-function safeErrorMessage(error, env = {}) { let message=String(error?.message||'Unknown error'); for(const secret of [env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET]){const value=String(secret||'');if(value)message=message.split(value).join('[REDACTED]');} return message; }
13
-export default { async fetch(request,env={},ctx={}) { const url=new URL(request.url);
14
- if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();
15
- if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT')){const workspaces=new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE});return handleWorkspaceEditorRequest(request,{workspaces,botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});}
16
- if(request.method==='GET'){if(url.pathname==='/health'||url.pathname==='/'||url.pathname==='/status')return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}
17
- if(request.method==='POST'&&url.pathname==='/telegram/webhook'){if(!env.TELEGRAM_WEBHOOK_SECRET)return new Response('Webhook secret not configured',{status:503});if(request.headers.get('X-Telegram-Bot-Api-Secret-Token')!==env.TELEGRAM_WEBHOOK_SECRET)return new Response('Forbidden',{status:403});if(!env.OWNER_TELEGRAM_ID)return new Response('Owner not configured',{status:503});if(!env.TELEGRAM_BOT_TOKEN)return new Response('Telegram bot token not configured',{status:503});try{const update=await request.json();if(!isOwnerUpdate(update,env))return jsonResponse({ok:true,ignored:true});const bot=new GuidedNexaDevBot(env);return jsonResponse(await bot.handleUpdate(update));}catch(err){console.error('telegram_webhook_error',safeErrorMessage(err,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}
18
- if(request.method==='POST')return new Response('Not Found',{status:404}); return new Response('Method Not Allowed',{status:405}); } };
7
+export { AutomationStore } from './durable/automation-store.js';
8
+const jsonResponse=(p,s=200)=>new Response(JSON.stringify(p),{status:s,headers:{'Content-Type':'application/json; charset=utf-8'}});const publicHealthPayload=()=>({status:'online',bot:'Nexa Dev Bot',version:'1.1.1',mode:'Cloudflare Worker Webhook'});const senderIdFromUpdate=u=>u?.message?.from?.id??u?.callback_query?.from?.id??null;const isOwnerUpdate=(u,e)=>!!e.OWNER_TELEGRAM_ID&&senderIdFromUpdate(u)!==null&&String(senderIdFromUpdate(u))===String(e.OWNER_TELEGRAM_ID);function safeErrorMessage(error,env={}){let m=String(error?.message||'Unknown error');for(const s of[env.TELEGRAM_BOT_TOKEN,env.TELEGRAM_WEBHOOK_SECRET,env.GITHUB_TOKEN,env.CLOUDFLARE_API_TOKEN,env.APPROVAL_SIGNING_SECRET]){const v=String(s||'');if(v)m=m.split(v).join('[REDACTED]');}return m;}export default{async fetch(request,env={}){const url=new URL(request.url);if(request.method==='GET'&&url.pathname==='/workspace/editor')return workspaceEditorPageResponse();if(url.pathname==='/workspace/api/editor'&&(request.method==='GET'||request.method==='PUT'))return handleWorkspaceEditorRequest(request,{workspaces:new DurableWorkspaceStoreClient({namespace:env.WORKSPACE_STORE}),botToken:env.TELEGRAM_BOT_TOKEN||'',ownerId:env.OWNER_TELEGRAM_ID||''});if(request.method==='GET'){if(['/health','/','/status'].includes(url.pathname))return jsonResponse(publicHealthPayload());return new Response('Not Found',{status:404});}if(request.method==='POST'&&url.pathname==='/telegram/webhook'){if(!env.TELEGRAM_WEBHOOK_SECRET)return new Response('Webhook secret not configured',{status:503});if(request.headers.get('X-Telegram-Bot-Api-Secret-Token')!==env.TELEGRAM_WEBHOOK_SECRET)return new Response('Forbidden',{status:403});if(!env.OWNER_TELEGRAM_ID)return new Response('Owner not configured',{status:503});if(!env.TELEGRAM_BOT_TOKEN)return new Response('Telegram bot token not configured',{status:503});try{const u=await request.json();if(!isOwnerUpdate(u,env))return jsonResponse({ok:true,ignored:true});return jsonResponse(await new GuidedNexaDevBot(env).handleUpdate(u));}catch(e){console.error('telegram_webhook_error',safeErrorMessage(e,env));return jsonResponse({ok:false,error:'Telegram webhook processing failed'},400);}}return new Response(request.method==='POST'?'Not Found':'Method Not Allowed',{status:request.method==='POST'?404:405});}};
test/automation.test.js
new
+3
@@ -0,0 +1,3 @@
1
+import test from 'node:test';import assert from 'node:assert/strict';import {createAutomation,transitionAutomation}from'../src/core/automation.js';
2
+test('CP7 state machine pauses resumes and completes',()=>{let s=createAutomation({id:'1',ownerId:'o',recipe:'ci-recovery',steps:[{key:'a'},{key:'b'}]});s=transitionAutomation(s,{type:'pause',intent:{key:'a'}});assert.equal(s.status,'awaiting_approval');s=transitionAutomation(s,{type:'resume',key:'a'});s=transitionAutomation(s,{type:'complete_step',key:'a'});assert.equal(s.cursor,1);s=transitionAutomation(s,{type:'complete_step',key:'b'});assert.equal(s.status,'completed');});
3
+test('CP7 idempotency prevents duplicate step effects',()=>{let s=createAutomation({id:'1',ownerId:'o',recipe:'r',steps:[{key:'a'}]});s=transitionAutomation(s,{type:'complete_step',key:'a'});assert.equal(transitionAutomation(s,{type:'inspect'}).status,'completed');assert.throws(()=>transitionAutomation(s,{type:'resume',key:'a'}));});
wrangler.jsonc
+1
-6
@@ -1,6 +1 @@
1
-{
2
- "$schema":"node_modules/wrangler/config-schema.json","name":"nexa-dev-bot","main":"src/index.js","compatibility_date":"2026-10-02","workers_dev":true,"keep_vars":true,"observability":{"enabled":true},
3
- "durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"}]},
4
- "previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"}]}},
5
- "exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"}}
6
-}
1
+{"$schema":"node_modules/wrangler/config-schema.json","name":"nexa-dev-bot","main":"src/index.js","compatibility_date":"2026-10-02","workers_dev":true,"keep_vars":true,"observability":{"enabled":true},"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"}]},"previews":{"durable_objects":{"bindings":[{"name":"APPROVAL_REPLAY_GUARD","class_name":"ApprovalReplayGuard"},{"name":"WORKSPACE_STORE","class_name":"WorkspaceStore"},{"name":"INCIDENT_STORE","class_name":"IncidentStore"},{"name":"AUTOMATION_STORE","class_name":"AutomationStore"}]}},"exports":{"ApprovalReplayGuard":{"type":"durable-object","storage":"sqlite"},"WorkspaceStore":{"type":"durable-object","storage":"sqlite"},"IncidentStore":{"type":"durable-object","storage":"sqlite"},"AutomationStore":{"type":"durable-object","storage":"sqlite"}}}