UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 16.7 kB
import{a as retainedJson,i as recordWakeFailure,n as ResearchState,o as retentionMs,r as hash,s as terminal,t as ResearchStartRejectedError}from"./job-state-BYHS6F2i.mjs";import{n as renderResearchDocument}from"./evidence-BiL1baUo.mjs";import{a as recordManagedPollFailure,i as reconcileManaged,n as finishManaged,r as managedClient,t as assertManagedRequest}from"./managed-BAzGvJOO.mjs";import{isDeepStrictEqual}from"node:util"; //!extensions/deep-research/src/execution.ts async function withResearchExecution(e,t,n){t.assertInvocationCurrent();const{agentId:r,sessionKey:i,sessionId:a}=t;if(!e||!r||!i||!a)throw new Error(`Research requires the current Gateway conversation authority.`);return e.withCurrent({agentId:r,sessionKey:i,toolName:`deep_research`},e=>{const assertInvocationCurrent=()=>{t.assertInvocationCurrent();e.assertCurrent();if(e.target.sessionId!==a)throw new Error(`Research conversation changed during invocation.`)};assertInvocationCurrent();return n({...e.target,assertInvocationCurrent})})} //!extensions/deep-research/src/job-request.ts function assertResearchStart(e,t){if(!t.sessionKey||!t.sessionId||!t.agentId)throw new ResearchStartRejectedError(`Research requires a current conversation generation.`);if(e.engine===`google`)try{assertManagedRequest(e)}catch(e){throw new ResearchStartRejectedError(e instanceof Error?e.message:`Invalid managed request`)}if(Buffer.byteLength(JSON.stringify(e))>262144)throw new ResearchStartRejectedError(`Research request exceeds the retained input limit.`)} //!extensions/deep-research/src/view-state.ts function belongs(e,t){return e.sessionKey===t.sessionKey&&e.sessionId===t.sessionId&&e.agentId===t.agentId}function assertResearchJobCurrent(e,t){t.assertInvocationCurrent();if(!e||!belongs(e,t))throw new Error(`Research job not found in this conversation generation.`)}async function listResearchJobs(e,t){const n=await e.open(`jobs`,t).entries();t.assertInvocationCurrent();return n.map(e=>e.value).filter(e=>belongs(e,t)).toSorted((e,t)=>t.createdAt-e.createdAt)}async function readResearchJob(e,t,n){const r=await e.open(`jobs`,n).lookup(t);assertResearchJobCurrent(r,n);const i=await e.open(`cancellations`,n).lookup(t);n.assertInvocationCurrent();return i?{...r,cancelRequested:true}:r}async function requestResearchWake(e,t,n,r,i){const a=e.open(`jobs`,n);const o=await a.observe(t);assertResearchJobCurrent(o.value,n);if(terminal(o.value))return o.value;const s={...o.value,recovery:`ready`,wakeFailures:0,pollFailures:0,nextWakeAt:r,updatedAt:r,...i?{cancelRequested:true}:{}};await e.prepareWake(s,n.assertInvocationCurrent);const c=await a.compareAndApply(t,o.comparison,{operation:`update`,action:`set`,value:retainedJson(s),ttlMs:retentionMs});const l=c.status===`conflict`?c.current.value:s;assertResearchJobCurrent(l,n);if(!terminal(l)&&(l.recovery!==`ready`||(l.nextWakeAt??Infinity)>r))throw new Error(`Research changed while requesting control. Refresh and retry.`);await e.prepareWake(l,n.assertInvocationCurrent);return l} //!extensions/deep-research/src/jobs.ts var ResearchJobs=class{constructor(e,t,n,r=()=>{}){this.api=e;this.scheduler=t;this.sessionWork=n;this.changed=r;this.active=/* @__PURE__ */ new Map;this.capacityWaiters=/* @__PURE__ */ new Set;this.state=new ResearchState(e,t)}async readRecoveryJob(e){const t=await this.state.wakes().lookup(e);this.scheduler.signal.throwIfAborted();if(!t)return;const n={agentId:t.agentId,sessionKey:t.sessionKey,sessionId:t.sessionId,assertInvocationCurrent:()=>this.scheduler.signal.throwIfAborted()};const r=await this.state.open(`jobs`,n).lookup(e);n.assertInvocationCurrent();return r&&r.id===e&&r.agentId===t.agentId&&r.sessionKey===t.sessionKey&&r.sessionId===t.sessionId?{job:r,context:n}:void 0}async startRecovery(){for(const{value:e}of await this.state.wakes().entries()){this.scheduler.signal.throwIfAborted();this.enqueue(e.id,e.nextWakeAt)}}enqueue(e,t){if(!this.sessionWork||this.scheduler.signal.aborted||this.active.has(e))return;this.scheduler.schedule({id:`research-wake:${e}`,atMs:Math.max(this.scheduler.now()+1e3,t),mode:`earliest`,run:()=>this.wake(e)})}schedule(e){if(!terminal(e)&&e.recovery===`ready`)this.enqueue(e.id,e.nextWakeAt??this.scheduler.now())}async wake(e){if(!this.sessionWork||this.active.has(e))return;const t=await this.readRecoveryJob(e);if(this.active.has(e))return;const n=t?.job;if(!n||terminal(n)||n.recovery!==`ready`){await this.state.pruneWake(e);return}if((n.nextWakeAt??0)>this.scheduler.now()){this.schedule(n);return}if(this.active.size>=4){this.capacityWaiters.add(e);return}try{const t=await this.sessionWork.run(e,async t=>{const n={...t.target,assertInvocationCurrent:t.assertCurrent};const r=await this.get(e,n);return this.run(r,n,t.signal)});this.scheduler.signal.throwIfAborted();if(t.status===`unavailable`)await this.defer(e,t.reason,t.retryAfterMs)}catch{this.scheduler.signal.throwIfAborted();await this.defer(e,`Current source authority or execution became unavailable`,5e3)}}async defer(e,t,n){const r=await this.readRecoveryJob(e);if(!r||this.active.has(e))return;const i=await this.state.settleUnavailable(e,r.context,t,n);if(i){this.schedule(i);this.changed()}}withCurrent(e,t){return withResearchExecution(this.sessionWork,e,t)}list(e){return listResearchJobs(this.state,e)}read(e,t){return readResearchJob(this.state,e,t)}async requestResume(e,t){const n=await this.read(e.id,t);if(n.state!==`paused`||n.cancelRequested||this.active.has(n.id))throw new Error(`This job cannot be resumed safely; inspect its retained state.`);return this.requestWake(n,t)}async requestWake(e,t,n=false){const r=await requestResearchWake(this.state,e.id,t,this.scheduler.now(),n);this.schedule(r);this.changed();return r}async get(e,t){const n=this.state.open(`jobs`,t);const r=await this.read(e,t);if(!this.active.has(e)&&[`running`,`submitting`].includes(r.state)){r.state=r.state===`submitting`&&!r.handle?`indeterminate`:`paused`;r.progress=r.state===`indeterminate`?`Submission outcome is unknown; not resubmitted.`:`Recovering the recorded job without another submission.`;if(terminal(r))delete r.nextWakeAt;await n.register(e,r,{ttlMs:retentionMs});await this.state.retireWake(r,t.assertInvocationCurrent);this.changed()}return r}async start(e,t,n,r,i,a=false){n.assertInvocationCurrent();assertResearchStart(e,n);const o=hash(`${n.agentId}\n${n.sessionKey}\n${n.sessionId}\n${t}`);const s=this.state.open(`jobs`,n);const c=await s.lookup(o);n.assertInvocationCurrent();if(c){const t=await this.get(o,n);if(!isDeepStrictEqual(t.request,retainedJson(e)))throw new ResearchStartRejectedError(`Idempotency key belongs to a different research request.`);await this.state.prepareWake(t,n.assertInvocationCurrent);this.schedule(t);return t}if(await s.count()>=32)throw new ResearchStartRejectedError(`Research job capacity reached for this conversation.`);n.assertInvocationCurrent();const l=e.sources?.web??!e.sources?.documents?.length;const u=e.engine===`google`?[]:[...l?[`web_search`]:[],...l||e.sources?.urls?.length?[`web_fetch`]:[]];const d=this.sessionWork?await this.sessionWork.admit({id:o,agentId:n.agentId,sessionKey:n.sessionKey,toolName:`deep_research`,...u.length?{delegatedTools:u}:{}}).catch(e=>{throw new ResearchStartRejectedError(e instanceof Error?e.message:`Research admission rejected`)}):void 0;n.assertInvocationCurrent();if(d&&(d.target.sessionId!==n.sessionId||d.target.lifecycleRevision!==n.lifecycleRevision))throw new ResearchStartRejectedError(`Research conversation changed during admission`);if(a&&!d?.recoverable)throw new ResearchStartRejectedError(`Research start needs a recoverable authenticated source; no work was started.`);const f={version:1,id:o,request:e,sessionKey:n.sessionKey,sessionId:n.sessionId,agentId:n.agentId,createdAt:this.scheduler.now(),deadlineAt:0,state:`queued`,progress:`Accepted`,...d?{recovery:d.recoverable?`ready`:`unavailable`,lifecycleRevision:d.target.lifecycleRevision,nextWakeAt:this.scheduler.now()}:{}};await this.state.prepareWake(f,n.assertInvocationCurrent);if(!await s.registerIfAbsent(o,retainedJson(f),{ttlMs:6048e5})){const t=await this.get(o,n);if(!isDeepStrictEqual(t.request,retainedJson(e)))throw new ResearchStartRejectedError(`Idempotency key belongs to a different research request.`);return t}this.schedule(f);this.changed();i?.(`Research accepted`,f.id);return a?f:this.run(f,n,r,i)}async cancel(e,t,n,r=false){const i=await this.read(e.id,t);if(terminal(i))return i;await this.state.open(`cancellations`,t).register(i.id,true,{ttlMs:retentionMs});t.assertInvocationCurrent();const a=this.active.get(i.id);if(a){a.abort(/* @__PURE__ */ new Error(`Research cancellation requested`));this.changed();return{...i,cancelRequested:true}}const o=await this.requestWake(i,t,true);return r?o:this.run(o,t,n)}async run(e,t,n,r=()=>{}){assertResearchJobCurrent(e,t);let i=e;if(terminal(i)||this.active.has(i.id))return i;if(this.active.size>=4){if(i.recovery===`ready`)this.capacityWaiters.add(i.id);return{...i,progress:`Four research invocations are active; this job remains queued.`}}const a=new AbortController;const o=AbortSignal.any([this.scheduler.signal,...n?[n]:[]]);const s=AbortSignal.any([o,a.signal]);const assertCurrent=()=>{o.throwIfAborted();t.assertInvocationCurrent()};const c=this.state.open(`jobs`,t,assertCurrent);const prepareSave=()=>{if(terminal(i)){delete i.nextWakeAt;if(i.result&&!i.publicationId){i.publicationId=i.id;i.publishedAt=this.scheduler.now()}}else if(i.recovery===`ready`)i.nextWakeAt=Math.max(this.scheduler.now()+5e3,i.nextWakeAt??0)};const save=async()=>{assertCurrent();prepareSave();i.updatedAt=this.scheduler.now();await this.state.prepareWake(i,assertCurrent);await c.register(i.id,retainedJson(i),{ttlMs:retentionMs});assertCurrent();await this.state.retireWake(i,assertCurrent);this.schedule(i);this.changed()};const saveStoppedInvocation=async()=>{const assertReceiptCurrent=()=>{this.scheduler.signal.throwIfAborted();t.assertInvocationCurrent()};assertReceiptCurrent();prepareSave();i.updatedAt=this.scheduler.now();await this.state.prepareWake(i,assertReceiptCurrent);await this.state.open(`jobs`,t,assertReceiptCurrent).register(i.id,retainedJson(i),{ttlMs:retentionMs});assertReceiptCurrent();await this.state.retireWake(i,assertReceiptCurrent)};let l=false;let u=false;let d=false;let f=false;let p=false;let m=false;const h=this.state.open(`steps`,t,assertCurrent);const memo=async(e,t)=>{assertCurrent();s.throwIfAborted();const n=`${i.id}:${hash(e)}`;const r=await h.lookup(n);assertCurrent();s.throwIfAborted();if(r?.state===`done`)return r.value;if(r?.state===`started`){p=true;throw new Error(`Interrupted operation has no recorded receipt; not repeated.`)}if(r?.state===`failed`)throw new Error(`A prior operation failed and will not be repeated automatically.`);if(m||this.scheduler.now()>=i.deadlineAt)throw new Error(`Research deadline exhausted; only recorded receipts may be replayed.`);await h.register(n,{state:`started`},{ttlMs:retentionMs});assertCurrent();s.throwIfAborted();try{const e=await t();assertCurrent();await h.register(n,retainedJson({state:`done`,value:e}),{ttlMs:retentionMs});return e}catch(e){assertCurrent();if(!s.aborted)await h.register(n,{state:`failed`},{ttlMs:retentionMs});throw e}};this.active.set(i.id,a);try{assertCurrent();i=await this.get(i.id,t);l=true;if(i.state===`submitting`&&!i.handle){i.state=`indeterminate`;i.progress=`Submission outcome is unknown; not resubmitted.`;await save()}if(terminal(i))return i;i.cancelRequested=await this.state.open(`cancellations`,t,assertCurrent).lookup(i.id)??i.cancelRequested??false;if(i.request.engine===`google`){const e=managedClient(this.api,t,{dispatched:()=>{f=true},retainOutcome:async e=>{try{i=await this.state.retainStartOutcome(i,e)}catch(e){u=true;throw e}}});if(!i.handle&&!i.cancelRequested){const r=await e({version:1,action:`describe`},o);if(!r.ok){recordWakeFailure(i,this.scheduler.now(),r.reason,r.retryAfterMs);await save();return i}if(!(`kind`in r.value)||r.value.kind!==`managed-research`)throw new Error(`No explicitly activated managed research adapter is available.`);d=true;i.state=`submitting`;i.progress=`Submitting managed research`;await save();i.cancelRequested=await this.state.open(`cancellations`,t,assertCurrent).lookup(i.id)??i.cancelRequested;assertCurrent();if(i.cancelRequested||a.signal.aborted){i.state=`cancelled`;i.progress=`Cancelled before submission`;await save();return i}o.throwIfAborted();const s=await e({version:1,action:`start`,question:i.request.question,...i.request.output===void 0?{}:{output:i.request.output},...i.request.asOf===void 0?{}:{asOf:i.request.asOf}},this.scheduler.signal);if(n?.aborted){i.state=i.handle||!s.ok&&s.state===`blocked`?`paused`:`indeterminate`;i.progress=i.handle?`Invocation stopped after submission; resume or cancel the retained provider job.`:i.state===`paused`?`Provider did not accept the request; resume with fresh authority.`:`Submission outcome is unknown; do not repeat it.`;await saveStoppedInvocation();n.throwIfAborted()}if(!s.ok){i.handle=s.handle;i.state=s.handle?`paused`:s.state===`indeterminate`?`indeterminate`:s.state===`blocked`?`paused`:`failed`;i.progress=s.reason;if(s.state===`blocked`)recordWakeFailure(i,this.scheduler.now(),s.reason,s.retryAfterMs);await save();return i}if(!(`state`in s.value))throw new Error(`Adapter returned a descriptor instead of a research receipt.`);i.handle=s.value.handle;assertCurrent();if(s.value.state!==`running`)return await finishManaged(i,s.value,save)}if(!i.handle){i.state=`cancelled`;i.progress=`Cancelled before submission`;await save();return i}assertCurrent();i.cancelRequested=await this.state.open(`cancellations`,t,assertCurrent).lookup(i.id)??i.cancelRequested??false;const c=await reconcileManaged(e,i.handle,i.cancelRequested,o);if(!c.ok)recordManagedPollFailure(i,c,this.scheduler.now());else{delete i.pollFailures;if(!(`state`in c.value))throw new Error(`Expected a research snapshot.`);if(c.value.state!==`running`)return await finishManaged(i,c.value,save);s.throwIfAborted();i.state=`paused`;i.nextWakeAt=this.scheduler.now()+(c.value.retryAfterMs??5e3);i.progress=i.cancelRequested?`Provider cancellation is not confirmed; reconciliation is pending.`:`Provider research is running`}await save();r(i.progress);return i}if(!i.deadlineAt)i.deadlineAt=this.scheduler.now()+(i.request.budget?.durationMs??18e4);const e=i.deadlineAt-this.scheduler.now();m=i.cancelRequested||e<=0;i.state=`running`;i.progress=`Researching`;await save();const{executePortableResearch:c}=await import(`./portable-tool-mNl3aprf.mjs`);const h=await c(this.api,t,{...i.request,budget:{...i.request.budget,durationMs:m?1e4:e}},s,async(e,t)=>{assertCurrent();i.progress=e;if(t)i.observation=t;await save();r(e)},memo,new Date(i.createdAt).toISOString());assertCurrent();i.cancelRequested=await this.state.open(`cancellations`,t,assertCurrent).lookup(i.id)??i.cancelRequested??false;if(m){h.status=`partial`;h.gaps.push(i.cancelRequested?`Research cancelled; only recorded evidence was replayed, with no new calls.`:`Global research deadline exhausted; only recorded evidence was replayed, with no new calls.`);const e=renderResearchDocument(i.request.question,h.findings,h.sources,h.gaps);h.report=e.report;h.reportCitations=e.citations}i.result=i.cancelRequested?{...h,status:`cancelled`}:h;i.state=i.cancelRequested?`cancelled`:p?`indeterminate`:i.result.status;i.progress=i.state===`cancelled`?`Cancelled; retained evidence is available.`:p?`Interrupted operation was not repeated; available evidence is partial.`:`Report ready`;await save();return i}catch(e){if(!l||u||i.state===`indeterminate`)throw e;if(d&&i.request.engine===`google`&&i.state===`submitting`&&!f)i=await this.state.retainStartOutcome(i);assertCurrent();if(a.signal.aborted&&i.request.engine===`google`&&i.handle){const e=await reconcileManaged(managedClient(this.api,t),i.handle,true,o);if(e.ok&&`state`in e.value&&e.value.state!==`running`)return await finishManaged(i,e.value,save);i.state=`paused`;i.progress=`Cancellation requested; provider termination is not confirmed. Reconciliation is pending.`;await save();return i}i.state=i.request.engine===`google`?i.state===`submitting`&&!i.handle?`indeterminate`:`paused`:a.signal.aborted?`cancelled`:`failed`;i.progress=i.state===`indeterminate`?`Submission outcome is unknown; do not repeat it.`:i.state===`cancelled`?`Cancelled.`:`Research interrupted; inspect the retained state before resuming.`;await save();if(a.signal.aborted)return i;throw e}finally{this.active.delete(i.id);this.schedule(i);this.changed();const e=[...this.capacityWaiters];this.capacityWaiters.clear();for(const t of e)this.enqueue(t,this.scheduler.now())}}};export{ResearchJobs};