module.exports=[73596,e=>{"use strict";let t;var n=e.i(6015),o=e.i(76222),r=e.i(13826),i=e.i(47751),a=e.i(51474),s=e.i(14747),l=e.i(22734),u=e.i(25289),d=e.i(20993),p=e.i(48705),c=e.i(5779),m=e.i(7416);let f=s.default.join(process.cwd(),"data","employees");var y=e.i(69719);let g=y.z.object({summary:y.z.string().describe("One short line of what happened this shift."),contextUpdate:y.z.string().optional().describe("One paragraph the twin wants to remember next shift."),decisions:y.z.array(y.z.object({text:y.z.string(),rationale:y.z.string().optional()})).optional(),learnings:y.z.array(y.z.string()).optional(),goalUpdates:y.z.array(y.z.object({departmentId:y.z.string(),metric:y.z.string(),increment:y.z.number().int()})).optional(),tasksCreate:y.z.array(y.z.object({toTwinId:y.z.string().optional(),toDepartmentId:y.z.string().optional(),title:y.z.string(),description:y.z.string().optional(),priority:y.z.number().int().min(1).max(5).default(3)})).optional(),tasksComplete:y.z.array(y.z.object({taskId:y.z.string(),result:y.z.string()})).optional(),feedItems:y.z.array(y.z.object({kind:y.z.enum(["update","alert","needs-review"]),title:y.z.string(),detail:y.z.string().optional(),priority:y.z.number().int().min(1).max(5).default(3)})).optional().describe("Items the twin wants to surface to the CEO in /flow."),artifacts:y.z.array(y.z.string()).optional().describe("Relative paths the twin created or modified.")}),h=(function e(t){if(t&&"object"==typeof t)for(let n of(delete t.$schema,"integer"===t.type&&(t.minimum===Number.MIN_SAFE_INTEGER&&delete t.minimum,t.maximum===Number.MAX_SAFE_INTEGER&&delete t.maximum),Object.keys(t))){let o=t[n];Array.isArray(o)?o.forEach(e):e(o)}}(t=JSON.parse(JSON.stringify(y.z.toJSONSchema(g)))),t);var w=e.i(85824),S=e.i(50990),R=e.i(38261);let _=s.default.join(process.cwd(),"data","employees");function b(e){return s.default.join(_,e,".shift","focus-cache.json")}async function $(e){var t;let n=(0,R.getFocusConfig)(e);if(!n.prefetches.length)return[];let o=function(e){let t=b(e);if(!l.default.existsSync(t))return{};try{let e=JSON.parse(l.default.readFileSync(t,"utf8"));return e&&"object"==typeof e?e:{}}catch(e){return console.warn("[twin-focus-prefetch] cache read failed:",e),{}}}(e),r=(0,d.getComposio)(),i=(0,d.composioUserIdFor)(e),a=[];for(let e of n.prefetches){let n=e.cacheTtlMs??3e5,s=`${e.toolSlug}|${function e(t){return null===t||"object"!=typeof t?JSON.stringify(t):Array.isArray(t)?"["+t.map(e).join(",")+"]":"{"+Object.keys(t).sort().map(n=>JSON.stringify(n)+":"+e(t[n])).join(",")+"}"}(e.arguments??{})}`,l=o[s];if(l&&function(e,t){let n=Date.now()-new Date(e.ts).getTime();return Number.isFinite(n)&&n<t}(l,n)){a.push({label:e.label,toolSlug:e.toolSlug,ts:l.ts,cached:!0,ok:!0,data:l.data,durationMs:0,maxItems:e.maxItems});continue}let u=Date.now();try{let n=(t=await r.tools.execute(e.toolSlug,{userId:i,arguments:e.arguments}))&&"object"==typeof t&&"data"in t?t.data:t,l=new Date().toISOString();o[s]={ts:l,data:n},a.push({label:e.label,toolSlug:e.toolSlug,ts:l,cached:!1,ok:!0,data:n,durationMs:Date.now()-u,maxItems:e.maxItems})}catch(n){let t=n instanceof Error?n.message:String(n);a.push({label:e.label,toolSlug:e.toolSlug,ts:new Date().toISOString(),cached:!1,ok:!1,data:null,errorMessage:t,durationMs:Date.now()-u,maxItems:e.maxItems})}}try{let t,n;t=b(e),n=s.default.dirname(t),l.default.existsSync(n)||l.default.mkdirSync(n,{recursive:!0}),l.default.writeFileSync(t,JSON.stringify(o,null,2),"utf8")}catch(e){console.warn("[twin-focus-prefetch] cache write failed:",e)}return a}let k="\n\n_(focus snapshot truncated to fit prompt budget)_";var I=e.i(38745),x=e.i(43127),v=e.i(8035);let N=["EXPERTISE.md","TONE.md","CONTEXT.md","DECISIONS.md","PREFERENCES.md","PEOPLE.md","PROJECTS.md","BOUNDARIES.md","EMPLOYMENT.md"];async function O(e){let{employee:t,trigger:n,abortController:r}=e,i=`shift_${t.id}_${Date.now()}`,a=s.default.join(process.cwd(),"data","employees",t.id);(0,x.registerRun)({runId:i,surface:"shift",employeeId:t.id,employeeName:t.name,label:`Shift (${n})`,startedAt:new Date().toISOString(),logPath:(0,v.logPathFor)("shift",i)}),(0,v.appendRunLog)("shift",i,{type:"meta",message:`Shift started — trigger: ${n}`});let y=0,R=0,_="natural",b="";try{let e,O,T,E,z,A,D,C,j,M,[P,L,U]=await Promise.all([(0,d.buildEmployeeMcpServer)(t.id),(0,p.loadOrgCustomMcpServers)(),$(t.id).catch(e=>(console.warn("[shift-runner] focus prefetch failed:",e),[]))]),F=function(e){if(!e.length)return"";let t=[`# Focus snapshot (as of ${new Date().toISOString()})`,...e.map(e=>(function(e,t){if(!e.ok)return`## ${e.label}
_(prefetch failed: ${e.errorMessage??"unknown error"})_`;let n=JSON.stringify(function(e,t){if(Array.isArray(e))return e.slice(0,t);if(e&&"object"==typeof e){for(let n of["items","data","results"])if(Array.isArray(e[n]))return{...e,[n]:e[n].slice(0,t)}}return e}(e.data,t),null,2);return n.length>1500&&(n=n.slice(0,1500)+"\n…(truncated)"),`## ${e.label}
\`\`\`json
${n}
\`\`\``})(e,e.maxItems??5))].join("\n\n");if(t.length<=8e3)return t;let n=8e3-k.length;return t.slice(0,Math.max(0,n))+k}(U),Y={...L,...P?{composio:P}:{}},J=Object.keys(Y).length>0;if(!J){try{(0,I.appendFeedItem)({source:{kind:"shift",employeeId:t.id,runId:i},type:"needs-review",title:`${t.firstName} can't run shifts: no tools connected`,detail:`${t.firstName}-twin has zero MCP connections (no Composio toolkits, no org-wide MCP servers), so this shift was skipped before the model ran ($0 spent). Connect at least one toolkit at /connections/${t.id}.`,priority:1})}catch(e){console.warn("[shift-runner] no-mcp feed item failed:",e)}return(0,v.appendRunLog)("shift",i,{type:"meta",message:"Skipped: no MCP connections"}),(0,x.unregisterRun)(i,{status:"complete",costUsd:0}),{report:null,summary:`Skipped: no MCP connections active for ${t.firstName}.`,turns:0,costUsd:0,stoppedReason:"natural",runId:i}}if(!P)try{(0,I.appendFeedItem)({source:{kind:"shift",employeeId:t.id,runId:i},type:"needs-review",title:`${t.firstName} has no personal toolkits connected`,detail:`${t.firstName}-twin will run this shift on org-wide MCP servers only. No personal Slack/Gmail/GitHub/Linear etc. — the twin can't act AS ${t.firstName} on real systems until you connect at least one personal toolkit at /connections/${t.id}.`,priority:3})}catch(e){console.warn("[shift-runner] no-personal-mcp feed item failed:",e)}let B=async(e,n)=>{let o=n??{},r=(0,c.classifyTool)(e,o),a=e.replace(/^mcp__[a-z0-9_]+__/i,"");return"allow"===r.kind?{behavior:"allow",updatedInput:n}:"block"===r.kind?((0,m.appendAuditEntry)({runId:i,employeeId:t.id,employeeName:t.name,toolName:e,bareName:a,input:o,verdict:"hard_blocked",blockReason:r.reason}),{behavior:"deny",message:r.reason}):((0,m.appendAuditEntry)({runId:i,employeeId:t.id,employeeName:t.name,toolName:e,bareName:a,input:o,verdict:"deferred_to_flow"}),{behavior:"deny",message:`${r.reason} — This action requires CEO approval and cannot run in unattended shift mode. Do not retry. Instead, note the intended action in your ShiftReport under "pending_actions" so the CEO can approve it later.`})},G=(0,w.buildBaseOptions)({surface:"routine",abortController:r,runId:i,employeeId:t.id}),H=(0,w.buildTwinHooks)({runId:i,employeeId:t.id,employeeName:t.name,surface:"routine"}),X=(0,u.query)({prompt:"Run your shift. Use your MCP tools as needed, then emit a ShiftReport.",options:{...G,cwd:a,systemPrompt:(e=N.map(e=>{try{let t=l.default.readFileSync(s.default.join(a,e),"utf8");return`### ${e}

${t.trim()}`}catch{return null}}).filter(Boolean).join("\n\n---\n\n"),O=`You are the digital twin of ${t.name}, ${t.role} at Employee001 — an early-stage AI startup building a digital employee twin platform that lets CEOs chat with and delegate tasks to AI versions of their team.

You have been trained on ${t.firstName}'s real working style, decisions, and expertise. You speak in ${t.firstName}'s voice — with their tone, values, and reasoning.

# Your profile files (pre-loaded — do NOT call Read, Glob, or Grep)

${e}

# Shift mode — autonomous run

You are running in autonomous shift mode. No CEO is present. Your job is to:
1. Review your shift state (context, decisions, learnings) below.
2. Use your MCP tools to take useful actions grounded in your role.
3. At the end, emit a structured ShiftReport. Every field is optional except \`summary\`.

**Rules for this shift:**
- Read before you write. Prefer read-only tools first.
- Do NOT send messages, emails, or post to external channels without a prior decision recorded in your shift log.
- Destructive or external-facing actions are automatically deferred to /flow for CEO review.
- Keep the summary to one short line: what actually happened, not what you planned.`,T=function(e){function t(t){let n=s.default.join(s.default.join(f,e,".shift"),`${t}.md`);return l.default.existsSync(n)?l.default.readFileSync(n,"utf8").trim():""}return{context:t("context"),decisions:t("decisions"),learnings:t("learnings")}}(t.id),E=new Date,z=`# Current date and time

- Today: **${E.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"Asia/Jerusalem"})}** (Israel time)
- Local time: ${E.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",timeZone:"Asia/Jerusalem",hour12:!1})} IST
- ISO (UTC): ${E.toISOString()}

Use this when reasoning about deadlines, scheduling, "tomorrow", overdue items, or anything time-sensitive. Do NOT make up dates from your training data.`,A=`# Your shift memory

## Context (recent)
${T.context||"(none yet)"}

## Decisions (recent)
${T.decisions||"(none yet)"}

## Learnings (recent)
${T.learnings||"(none yet)"}`,D=(0,S.getTasksFor)(t.id,"pending"),j=(C=[...(0,S.getTasksFor)(t.id,"in_progress"),...D]).length>0?`# Tasks for you (${C.length})

You have the following tasks waiting. When you complete one, include it in \`tasksComplete[]\` in your ShiftReport with the result. You can also create new tasks for other twins via \`tasksCreate[]\`.

${C.map(e=>{let t=Math.floor((Date.now()-new Date(e.createdAt).getTime())/6e4),n=t<60?`${t}m ago`:t<1440?`${Math.floor(t/60)}h ago`:`${Math.floor(t/1440)}d ago`,o=e.description?`
  ${e.description}`:"";return`- [${e.id}] **${e.title}** (priority ${e.priority}, ${e.status}, ${n}, from ${e.fromEmployeeId})${o}`}).join("\n")}`:"# Tasks for you\n\n(no pending tasks — you can still create tasks for other twins via `tasksCreate[]` if helpful)",M=[z,A,F,j,"wakeup"===n?`# Catch-up note
This shift was delayed and is running as a catch-up. Lean toward summarising recent state rather than emitting many actions.`:""].filter(Boolean),[O,u.SYSTEM_PROMPT_DYNAMIC_BOUNDARY,...M]),allowedTools:["TodoWrite"],...J?{mcpServers:Y}:{},maxTurns:12,includePartialMessages:!0,permissionMode:J?"default":"bypassPermissions",canUseTool:J?B:void 0,outputFormat:{type:"json_schema",schema:h},settingSources:[],hooks:H}}),q=0,W="",Z=()=>{if(!W.trim()){W="";return}(0,v.appendRunLog)("shift",i,{type:"text",text:W}),(0,x.updateRun)(i,{lastText:W.slice(-200)}),W=""};for await(let e of X){if("stream_event"===e.type){let t=e.event;"content_block_delta"===t.type&&"text_delta"===t.delta.type&&t.delta.text&&(b+=t.delta.text,W+=t.delta.text,/[.!?\n]\s*$/.test(W)&&W.length>30&&Z());continue}if("assistant"===e.type){for(let t of(Z(),e.message.content))if("tool_use"===t.type){q++;let e=t.name.replace(/^mcp__[a-z0-9_]+__/i,"");(0,v.appendRunLog)("shift",i,{type:"tool_use",tool:e,input:t.input}),(0,x.updateRun)(i,{toolCalls:q,currentTool:e})}continue}if("user"===e.type){let t=e.message.content;if(Array.isArray(t))for(let e of t)"object"==typeof e&&null!==e&&"type"in e&&"tool_result"===e.type&&(0,v.appendRunLog)("shift",i,{type:"tool_result",tool:"result"});continue}if("result"===e.type){Z(),y=e.num_turns??0,R=e.total_cost_usd??0;let n=e.subtype;"error_max_budget_usd"===n?_="max_budget":"error_max_turns"===n?_="max_turns":"error_max_structured_output_retries"===n&&console.warn(`[shift-runner] structured output exhausted retries for run ${i}`);let r=e.structured_output,a=g.safeParse(r);if(a.success)return(0,v.appendRunLog)("shift",i,{type:"done",summary:a.data.summary,costUsd:R,turns:y}),(0,x.unregisterRun)(i,{status:"complete",costUsd:R}),R>0&&(0,o.recordSpend)(t.id,R),{report:a.data,summary:a.data.summary,turns:y,costUsd:R,stoppedReason:_,runId:i}}}Z();let K=b.trim().slice(0,200)||"Shift completed";return(0,v.appendRunLog)("shift",i,{type:"done",summary:K,costUsd:R,turns:y}),(0,x.unregisterRun)(i,{status:"max_budget"===_||"max_turns"===_?"error":"complete",costUsd:R}),R>0&&(0,o.recordSpend)(t.id,R),{report:null,summary:K,turns:y,costUsd:R,stoppedReason:_,runId:i}}catch(t){let e=t instanceof Error?t.message:"Unknown error";return(0,v.appendRunLog)("shift",i,{type:"error",message:e}),(0,x.unregisterRun)(i,{status:"error",costUsd:0}),{report:null,summary:`Shift failed: ${e}`,turns:0,costUsd:0,stoppedReason:"error",runId:i}}}function T(){let e=globalThis;return e.__routineScheduler||(e.__routineScheduler={interval:null,running:new Set}),e.__routineScheduler}function E(){let e=Date.now();for(let t of(0,n.listRoutines)())t.enabled&&t.nextRunAt&&(new Date(t.nextRunAt).getTime()>e||A(t,"scheduled"))}function z(){let e=Date.now();for(let t of(0,n.listRoutines)()){if(!t.enabled||!t.nextRunAt)continue;let n=new Date(t.nextRunAt).getTime();n>=e-6e4||(console.log(`[scheduler] catch-up: firing ${t.id} (nextRunAt=${t.nextRunAt}, ${Math.floor((e-n)/6e4)} min late)`),A(t,"wakeup"))}}async function A(t,s){let l=T();if(l.running.has(t.id))return"error";if(l.running.add(t.id),"scheduled"===s||"wakeup"===s){let e=(0,n.computeNextRun)(t.schedule).toISOString();(0,n.updateRoutine)(t.id,{nextRunAt:e})}let u=await (0,i.loadEmployeesFromDisk)(),d=[...u,...(0,a.getHiredEmployees)().filter(e=>!u.some(t=>t.id===e.id))].find(e=>e.id===t.employeeId);if(!d)return l.running.delete(t.id),(0,n.updateRoutine)(t.id,{lastRunAt:new Date().toISOString(),lastRunStatus:"error",lastRunSummary:"Employee not found"}),"error";if("shift"===t.kind&&!(0,o.isUnderBudget)(d.id)){try{let{appendFeedItem:t}=await e.A(86212);t({source:{kind:"shift",employeeId:d.id,runId:`budget_${Date.now()}`},type:"needs-review",title:`${d.firstName} is over daily budget — shift skipped`,detail:`${d.firstName}-twin has spent its daily budget and won't run again until midnight (Israel time). Raise the limit at /budgets if needed.`,priority:2})}catch{}return l.running.delete(t.id),(0,n.updateRoutine)(t.id,{lastRunAt:new Date().toISOString(),lastRunStatus:"skipped",lastRunSummary:"Skipped: daily budget exhausted"}),"skipped"}let p="",c=!1,m=!1,f=0,y=0,g="shift"!==t.kind?`rtrun_${t.id}_${Date.now()}`:null;g&&((0,x.registerRun)({runId:g,surface:"routine",employeeId:d.id,employeeName:d.name,label:t.name,startedAt:new Date().toISOString(),logPath:(0,v.logPathFor)("routine",g)}),(0,v.appendRunLog)("routine",g,{type:"meta",message:`Routine "${t.name}" started — trigger: ${s}`}));let h="",w=()=>{if(!g||!h.trim()){h="";return}(0,v.appendRunLog)("routine",g,{type:"text",text:h}),(0,x.updateRun)(g,{lastText:h.slice(-200)}),h=""};try{if("shift"===t.kind){let e=await O({employee:d,trigger:s});p=e.summary,"error"===e.stoppedReason&&(m=!0)}else await (0,r.runSingleTwin)(d,t.task,e=>{if("text_delta"===e.type&&(p+=e.delta,g&&(h+=e.delta,/[.!?\n]\s*$/.test(h)&&h.length>30&&w())),"tool_use"===e.type&&g){w(),f++;let t=e.tool.replace(/^mcp__[a-z0-9_]+__/i,"");(0,v.appendRunLog)("routine",g,{type:"tool_use",tool:t,input:e.input}),(0,x.updateRun)(g,{toolCalls:f,currentTool:t})}"tool_result"===e.type&&g&&(0,v.appendRunLog)("routine",g,{type:"tool_result",tool:e.tool}),"tool_approval_resolved"===e.type&&("deny"===e.decision&&(c=!0),g&&(0,v.appendRunLog)("routine",g,{type:"approval",tool:"(approval)",decision:e.decision})),"tool_blocked"===e.type&&(c=!0,g&&(0,v.appendRunLog)("routine",g,{type:"meta",message:`Blocked: ${e.tool} — ${e.reason}`})),"employee_error"===e.type&&(m=!0,g&&(0,v.appendRunLog)("routine",g,{type:"error",message:e.message})),"employee_done"===e.type&&(y=e.costUsd??0,g&&(0,x.updateRun)(g,{costUsd:y}))},[],{surface:"background",context:{type:"routine",routineId:t.id,routineName:t.name}})}catch{m=!0}g&&(w(),(0,v.appendRunLog)("routine",g,{type:"done",summary:p.trim().slice(0,200)||"Routine completed",costUsd:y}),(0,x.unregisterRun)(g,{status:m?"error":"complete",costUsd:y}));let S=m?"error":c?"denied":"ok",R=p.trim()||("error"===S?"Run failed":"denied"===S?"Action was declined":"Completed");if((0,n.updateRoutine)(t.id,{lastRunAt:new Date().toISOString(),lastRunStatus:S,lastRunSummary:R}),"shift"!==t.kind){let e=`rt_${t.id}_${Date.now()}`,n="error"===S?"Routine failed":"denied"===S?"Routine declined":"Routine completed";try{(0,I.appendFeedItem)({source:{kind:"routine",employeeId:t.employeeId,runId:e,routineId:t.id,routineName:t.name},type:"error"===S?"alert":"update",title:`${n}: ${t.name}`,detail:R.length>600?R.slice(0,580)+"…":R,priority:"error"===S?2:3})}catch(e){console.warn("[scheduler] feed append failed",e)}}return l.running.delete(t.id),S}e.s(["ensureSchedulerStarted",0,function(){let e=T();e.interval||(e.interval=setInterval(E,3e4),setTimeout(E,1e3),setTimeout(z,2e3))},"fireRoutine",0,A],73596)}];

//# sourceMappingURL=src_lib_routine-scheduler_ts_0vht_3x._.js.map