/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/almond-dialog-agent@1.8.0/lib/almond.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";const events=require("events"),interpolate=require("string-interp"),ThingTalk=require("thingtalk"),Semantic=require("./semantic"),Intent=Semantic.Intent,ValueCategory=Semantic.ValueCategory,ParserClient=require("./parserclient"),Dispatcher=require("./dispatcher"),DEFAULT_GETTEXT={dgettext:(e,t)=>t,dngettext:(e,t,n,s)=>1===s?t:n,dpgettext:(e,t,n)=>n};function apiCompat(e,t){void 0===e.principal&&(e.principal=e.speakerId?"speaker:"+e.speakerId:"user:"+e.id),void 0===e.isOwner&&(e.isOwner=!0),void 0===e.canConfigureDevice&&(e.canConfigureDevice=function(){return this.isOwner}),void 0===e.canCreatePermissionRule&&(e.canCreatePermissionRule=function(){return this.isOwner}),void 0===e.canExecute&&(e.canExecute=async function(e){return!!this.isOwner||!e.principal&&t.permissions.checkCanBeAllowed(this.principal,e)}),void 0===e.applyPermissionRules&&(e.applyPermissionRules=async function(e){return this.isOwner?e:e.principal?null:t.permissions.checkIsAllowed(this.principal,e)}),void 0===e.adjustPermissionRule&&(e.adjustPermissionRule=async function(e,t){return[e,t,{}]}),void 0===e.adjustProgram&&(e.adjustProgram=async function(e,t,n){return[e,t,n]}),void 0===e.logProgramExecution&&(e.logProgramExecution=async function(e,t,n){}),void 0===e.logPermissionRule&&(e.logPermissionRule=async function(e,t,n,s){})}const DummyStatistics={hit(){}};module.exports=class extends events.EventEmitter{constructor(e,t,n,s,i){super(),this._engine=e,this._user=n,apiCompat(n,this),this._conversationId=t,this._gettext=this._engine.platform.getCapability("gettext"),this._gettext||(this._gettext=DEFAULT_GETTEXT);let r=this._gettext;this._ngettext=function(e,t,n){return r.dngettext("almond",e,t,n)},this._pgettext=function(e,t){return r.dpgettext("almond",e,t)},this._=function(e){return r.dgettext("almond",e)},this._stats=this._engine.platform.getCapability("statistics"),null===this._stats&&(this._stats=DummyStatistics),this._raw=!1,this._options=i||{},this._debug=!!this._options.debug,this._delegate=s,this.parser=new ParserClient(this._options.sempreUrl,e.platform.locale,e.platform.getSharedPreferences(),e.platform),this._dispatcher=new Dispatcher(this,this._engine,this._debug),this._choices=[],this._context={timeout:1/0,code:"null",entities:{}},this._lastCommand=null,this._lastCandidates=null}get isAnonymous(){return this._options.anonymous}get id(){return this._conversationId}get user(){return this._user}get platform(){return this._engine.platform}get locale(){return this._engine.platform.locale}get timezone(){return this._engine.platform.timezone}get gettext(){return this._gettext}get stats(){return this._stats}get apps(){return this._engine.apps}get devices(){return this._engine.devices}get messaging(){return this._engine.messaging}get schemas(){return this._engine.schemas}get thingpedia(){return this._engine.thingpedia}get discovery(){return this._engine.discovery}get remote(){return this._engine.remote}get permissions(){return this._engine.permissions}notify(){return this._dispatcher.dispatchNotify.apply(this._dispatcher,arguments)}notifyError(){return this._dispatcher.dispatchNotifyError.apply(this._dispatcher,arguments)}askForPermission(){return this._dispatcher.dispatchAskForPermission.apply(this._dispatcher,arguments)}askQuestion(){return this._dispatcher.dispatchAskQuestion.apply(this._dispatcher,arguments)}interactiveConfigure(){return this._dispatcher.dispatchInteractiveConfigure.apply(this._dispatcher,arguments)}runProgram(){return this._dispatcher.dispatchRunProgram.apply(this._dispatcher,arguments)}expect(e){this._expecting=e,this._choices=[],this._raw=e===ValueCategory.RawString||e===ValueCategory.Password}start(){return this._dispatcher.start(this._options.showWelcome,this._options.configureMessaging)}_isUnsupportedError(e){return/(invalid kind| has no (quer(ies|y)|actions?)) /i.test(e.message)}handleParsedCommand(e,t={}){return this.stats.hit("sabrina-parsed-command"),this.emit("active"),this._debug&&console.log("Received pre-parsed assistant command"),"string"==typeof e&&(e=JSON.parse(e)),e.example_id&&this.thingpedia.clickExample(e.example_id).catch((e=>{console.error("Failed to record example click: "+e.message)})),this._errorWrap((async()=>{const n=await Intent.parse(e,this.schemas,this._getContext(null,t));return this._doHandleCommand(n,null,[],!0)}),t)}handleThingTalk(e,t={}){return this.stats.hit("sabrina-thingtalk-command"),this.emit("active"),this._debug&&console.log("Received ThingTalk program"),this._errorWrap((async()=>{const n=await Intent.parseThingTalk(e,this.schemas,this._getContext(null,t));return this._doHandleCommand(n,null,[],!0)}),t)}_doHandleCommand(e,t,n,s=!1){return e.isTrain||(this._lastCommand=t,this._lastCandidates=n),this._dispatcher.handle(e,s)}_getContext(e,t){return{command:e,previousCommand:this._lastCommand,previousCandidates:this._lastCandidates,platformData:t}}setContext(e,t={}){if(null===e)this._context={timeout:1/0,code:"null",entities:{}};else{let n=Date.now()+3e5;const s={};t.allocateEntities=!0;const i=ThingTalk.NNSyntax.toNN(e,"",s,t).join(" ");this._context={timeout:n,code:i,entities:s}}}async generateAnswer(e){const t=ThingTalk.NNSyntax.toNN(e,"",this._context.entities,{allocateEntities:!0}).join(" ");return(await this.parser.generateUtterance(this._context,t)).candidates[0].answer}_continueHandleCommand(e,t,n){return t.utterance=e,t.candidates.length>0?console.log("Analyzed message into "+t.candidates[0].code.join(" ")):console.log("Failed to analyze message"),Promise.all(t.candidates.map((async(s,i)=>{let r;try{r=await Intent.parse({code:s.code,entities:t.entities},this.schemas,this._getContext(e,n))}catch(e){if(console.log(`Failed to parse beam ${i}: ${e.message}`),!this._isUnsupportedError(e))return null;r=new Intent.Unsupported(n)}return{target:r,score:s.score}}))).then((e=>e.filter((e=>null!==e)))).then((s=>{if(s.length>0){let e=0,n=s[e];for(;e<s.length-1&&n.target.isUnsupported&&"Infinity"===n.score;)e++,n=s[e];this.stats.hit("sabrina-command-good");const i="Infinity"===n.score||"null"!==this._context.code;return this._doHandleCommand(n.target,t,t.candidates,i)}return this._lastCommand=t,this._lastCandidates=s,this.stats.hit("sabrina-failure"),this._dispatcher.handle(new Intent.Failed(e,n))}))}async _errorWrap(e,t){try{try{await e()}catch(e){if(!this._isUnsupportedError(e))throw e;await this._doHandleCommand(new Intent.Unsupported(t),null,[],!0)}}catch(e){"EHOSTUNREACH"===e.code||"ETIMEDOUT"===e.code?await this.sendReply("Sorry, I cannot contact the Almond service. Please check your Internet connection and try again later.",null):await this.sendReply(interpolate(this._("Sorry, I had an error processing your command: ${error}"),{error:e.message},{locale:this.platform.locale,timezone:this.platform.timezone}),null)}}handleCommand(e,t={},n){return this.stats.hit("sabrina-command"),this.emit("active"),this._debug&&console.log("Received assistant command "+e),this._errorWrap((async()=>{if(this._raw&&null!==e){const n=new ThingTalk.Ast.Value.String(e),s=new ThingTalk.Ast.Input.Bookkeeping(null,new ThingTalk.Ast.BookkeepingIntent.Answer(null,n));let i=Intent.fromThingTalk(s,this._getContext(e,t));return this._doHandleCommand(i,e,[],!0)}const s=await this.parser.sendUtterance(e,this._context,this._expecting,this._choices);return n&&n(s),this._continueHandleCommand(e,s,t)}))}presentExample(e,t){return Promise.resolve().then((()=>this._doHandleCommand(Intent.Example(e,t),null,[],!0))).catch((async e=>{await this.sendReply(interpolate(this._("Sorry, I had an error processing your command: ${error}."),{error:e.message},{locale:this.platform.locale,timezone:this.platform.timezone}),null),console.error(e.stack)}))}sendReply(e,t){return this._debug&&console.log("Almond Says: "+e),this._delegate.send(e,t)}sendPicture(e,t){return this._debug&&console.log("Almond sends picture: "+e),this._delegate.sendPicture(e,t)}sendRDL(e,t){return this._debug&&console.log("Almond sends RDL: "+e.callback),this._delegate.sendRDL(e,t)}sendChoice(e,t,n,s){return this._expecting!==ValueCategory.MultipleChoice&&console.log("UNEXPECTED: sendChoice while not expecting a MultipleChoice"),this._choices[e]={what:t,title:n,text:s},this._debug&&console.log("Almond sends multiple choice button: "+n),this._delegate.sendChoice(e,t,n,s)}resendChoices(){return this._expecting!==ValueCategory.MultipleChoice&&console.log("UNEXPECTED: sendChoice while not expecting a MultipleChoice"),Promise.all(this._choices.map(((e,t)=>this._delegate.sendChoice(t,e.what,e.title,e.text))))}sendButton(e,t){return this._debug&&console.log("Almond sends generic button: "+e),this._delegate.sendButton(e,t)}sendLink(e,t){return this._debug&&console.log("Almond sends link: "+t),this._delegate.sendLink(e,t)}async sendAskSpecial(){let e=ValueCategory.toAskSpecial(this._expecting);this._debug&&(null!==e&&"generic"!==e?console.log("Almond sends a special request"):null!==e&&console.log("Almond expects an answer")),await this._delegate.sendAskSpecial(e,this._context.code,this._context.entities,this._context.timeout)}sendResult(e,t){return this._delegate.sendResult(e,t)}},module.exports.Intent=Intent,module.exports.ParserClient=ParserClient,module.exports.Formatter=ThingTalk.Formatter;
//# sourceMappingURL=/sm/1b2fd9c0e642777456f21bae2e5b8174c9d76845fdc63ad76085c961ce403ad3.map