@transcend-io/cli 8.28.0 → 8.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/bin/bash-complete.cjs +1 -1
- package/dist/bin/cli.cjs +1 -1
- package/dist/bin/deprecated-command.cjs +2 -2
- package/dist/{chunk-THOOR2KA.cjs → chunk-4WBBQCOV.cjs} +4 -4
- package/dist/{chunk-THOOR2KA.cjs.map → chunk-4WBBQCOV.cjs.map} +1 -1
- package/dist/{chunk-I7PFP5VB.cjs → chunk-4Y7PZGF3.cjs} +2 -2
- package/dist/{chunk-I7PFP5VB.cjs.map → chunk-4Y7PZGF3.cjs.map} +1 -1
- package/dist/chunk-56COHDFT.cjs +3001 -0
- package/dist/chunk-56COHDFT.cjs.map +1 -0
- package/dist/{chunk-K4TIJ3VM.cjs → chunk-5IHV6OHB.cjs} +2 -2
- package/dist/{chunk-K4TIJ3VM.cjs.map → chunk-5IHV6OHB.cjs.map} +1 -1
- package/dist/{chunk-EYOQLGDV.cjs → chunk-A3GRLGNU.cjs} +2 -2
- package/dist/{chunk-EYOQLGDV.cjs.map → chunk-A3GRLGNU.cjs.map} +1 -1
- package/dist/{chunk-AEL3DOYI.cjs → chunk-BAQ45VZI.cjs} +2 -2
- package/dist/{chunk-AEL3DOYI.cjs.map → chunk-BAQ45VZI.cjs.map} +1 -1
- package/dist/{chunk-FER7XKVN.cjs → chunk-BKPEELIQ.cjs} +2 -2
- package/dist/{chunk-FER7XKVN.cjs.map → chunk-BKPEELIQ.cjs.map} +1 -1
- package/dist/{chunk-JFZPP4VV.cjs → chunk-BQSBPO63.cjs} +3 -3
- package/dist/{chunk-JFZPP4VV.cjs.map → chunk-BQSBPO63.cjs.map} +1 -1
- package/dist/{chunk-LCDYXJN6.cjs → chunk-FHUHBSLE.cjs} +2 -2
- package/dist/{chunk-LCDYXJN6.cjs.map → chunk-FHUHBSLE.cjs.map} +1 -1
- package/dist/{chunk-CQT5QQ3U.cjs → chunk-GNEZHNUR.cjs} +2 -2
- package/dist/{chunk-CQT5QQ3U.cjs.map → chunk-GNEZHNUR.cjs.map} +1 -1
- package/dist/chunk-J5ZSDYK2.cjs +4 -0
- package/dist/chunk-J5ZSDYK2.cjs.map +1 -0
- package/dist/{chunk-ECGHWDVP.cjs → chunk-LU3DKRNK.cjs} +2 -2
- package/dist/chunk-LU3DKRNK.cjs.map +1 -0
- package/dist/{chunk-4PQ4RHUG.cjs → chunk-OSRNUQQ5.cjs} +4 -4
- package/dist/{chunk-4PQ4RHUG.cjs.map → chunk-OSRNUQQ5.cjs.map} +1 -1
- package/dist/{chunk-Q7I37FJV.cjs → chunk-T3BBQIRY.cjs} +2 -2
- package/dist/chunk-T3BBQIRY.cjs.map +1 -0
- package/dist/{chunk-Y35YHYXP.cjs → chunk-U7B2ZKV5.cjs} +21 -21
- package/dist/{chunk-Y35YHYXP.cjs.map → chunk-U7B2ZKV5.cjs.map} +1 -1
- package/dist/{chunk-YKGS253B.cjs → chunk-XSKGXUIG.cjs} +6 -6
- package/dist/{chunk-YKGS253B.cjs.map → chunk-XSKGXUIG.cjs.map} +1 -1
- package/dist/{chunk-RNZ72QMS.cjs → chunk-XURR4JGE.cjs} +2 -2
- package/dist/{chunk-RNZ72QMS.cjs.map → chunk-XURR4JGE.cjs.map} +1 -1
- package/dist/{chunk-L7Z4PFRC.cjs → chunk-ZPCV7RA2.cjs} +2 -2
- package/dist/{chunk-L7Z4PFRC.cjs.map → chunk-ZPCV7RA2.cjs.map} +1 -1
- package/dist/{impl-YWJCIRTP.cjs → impl-5IZGOLMG.cjs} +2 -2
- package/dist/{impl-YWJCIRTP.cjs.map → impl-5IZGOLMG.cjs.map} +1 -1
- package/dist/impl-5KE7PF4S.cjs +2 -0
- package/dist/{impl-PXT7QNSR.cjs.map → impl-5KE7PF4S.cjs.map} +1 -1
- package/dist/{impl-ZTZHVQYY.cjs → impl-63RUFEPF.cjs} +2 -2
- package/dist/{impl-ZTZHVQYY.cjs.map → impl-63RUFEPF.cjs.map} +1 -1
- package/dist/{impl-MBEVWSPX.cjs → impl-CYS34PCP.cjs} +2 -2
- package/dist/{impl-MBEVWSPX.cjs.map → impl-CYS34PCP.cjs.map} +1 -1
- package/dist/{impl-IIIT5MSV.cjs → impl-DFC7R4VO.cjs} +2 -2
- package/dist/{impl-IIIT5MSV.cjs.map → impl-DFC7R4VO.cjs.map} +1 -1
- package/dist/{impl-55NL4KOI.cjs → impl-DLADC4DX.cjs} +2 -2
- package/dist/{impl-55NL4KOI.cjs.map → impl-DLADC4DX.cjs.map} +1 -1
- package/dist/{impl-W35DMTQV.cjs → impl-EA6F65XG.cjs} +2 -2
- package/dist/{impl-W35DMTQV.cjs.map → impl-EA6F65XG.cjs.map} +1 -1
- package/dist/{impl-ANXIZT7S.cjs → impl-ECHPUQTL.cjs} +2 -2
- package/dist/{impl-ANXIZT7S.cjs.map → impl-ECHPUQTL.cjs.map} +1 -1
- package/dist/{impl-3YAJ7ZV3.cjs → impl-EE3BM53W.cjs} +2 -2
- package/dist/{impl-3YAJ7ZV3.cjs.map → impl-EE3BM53W.cjs.map} +1 -1
- package/dist/{impl-SVEK74IU.cjs → impl-FLUPS5AF.cjs} +2 -2
- package/dist/{impl-SVEK74IU.cjs.map → impl-FLUPS5AF.cjs.map} +1 -1
- package/dist/{impl-NCUMPL6B.cjs → impl-HMJ3RSYJ.cjs} +4 -4
- package/dist/{impl-NCUMPL6B.cjs.map → impl-HMJ3RSYJ.cjs.map} +1 -1
- package/dist/impl-HS3DVOVZ.cjs +2 -0
- package/dist/{impl-AP2ZTYJK.cjs.map → impl-HS3DVOVZ.cjs.map} +1 -1
- package/dist/{impl-NISL4HZY.cjs → impl-J4AIXCOM.cjs} +2 -2
- package/dist/{impl-NISL4HZY.cjs.map → impl-J4AIXCOM.cjs.map} +1 -1
- package/dist/{impl-SDQ6LUZD.cjs → impl-KGPFOOKN.cjs} +2 -2
- package/dist/{impl-SDQ6LUZD.cjs.map → impl-KGPFOOKN.cjs.map} +1 -1
- package/dist/{impl-DDQQGOQ3.cjs → impl-L5C2RKOS.cjs} +2 -2
- package/dist/{impl-DDQQGOQ3.cjs.map → impl-L5C2RKOS.cjs.map} +1 -1
- package/dist/{impl-7B7QDZZJ.cjs → impl-MLVDLR4J.cjs} +2 -2
- package/dist/{impl-7B7QDZZJ.cjs.map → impl-MLVDLR4J.cjs.map} +1 -1
- package/dist/impl-NA2AMJMD.cjs +2 -0
- package/dist/{impl-PE52QYSI.cjs.map → impl-NA2AMJMD.cjs.map} +1 -1
- package/dist/impl-NNSUFZJQ.cjs +3 -0
- package/dist/{impl-LDOILOAQ.cjs.map → impl-NNSUFZJQ.cjs.map} +1 -1
- package/dist/{impl-A6W2KTYL.cjs → impl-O752JHWB.cjs} +2 -2
- package/dist/{impl-A6W2KTYL.cjs.map → impl-O752JHWB.cjs.map} +1 -1
- package/dist/{impl-YJ6UUT4D.cjs → impl-P2XOCDM2.cjs} +2 -2
- package/dist/{impl-YJ6UUT4D.cjs.map → impl-P2XOCDM2.cjs.map} +1 -1
- package/dist/{impl-UC5CCT6E.cjs → impl-PC5SSKN6.cjs} +3 -3
- package/dist/{impl-UC5CCT6E.cjs.map → impl-PC5SSKN6.cjs.map} +1 -1
- package/dist/impl-QHSBTADS.cjs +2 -0
- package/dist/{impl-LQEYNOZS.cjs.map → impl-QHSBTADS.cjs.map} +1 -1
- package/dist/{impl-DT5KLE2G.cjs → impl-QZYAF6M6.cjs} +3 -3
- package/dist/{impl-DT5KLE2G.cjs.map → impl-QZYAF6M6.cjs.map} +1 -1
- package/dist/{impl-D7R3HZEC.cjs → impl-R4LLNQUP.cjs} +5 -5
- package/dist/{impl-D7R3HZEC.cjs.map → impl-R4LLNQUP.cjs.map} +1 -1
- package/dist/{impl-YHBNKYSL.cjs → impl-SHD5SUBY.cjs} +2 -2
- package/dist/{impl-YHBNKYSL.cjs.map → impl-SHD5SUBY.cjs.map} +1 -1
- package/dist/{impl-DVE332P5.cjs → impl-THXX4NLG.cjs} +2 -2
- package/dist/{impl-DVE332P5.cjs.map → impl-THXX4NLG.cjs.map} +1 -1
- package/dist/{impl-XHO6WQ2I.cjs → impl-TMXHKQO3.cjs} +2 -2
- package/dist/{impl-XHO6WQ2I.cjs.map → impl-TMXHKQO3.cjs.map} +1 -1
- package/dist/{impl-AZYBYV3X.cjs → impl-TPG3AZ2K.cjs} +2 -2
- package/dist/{impl-AZYBYV3X.cjs.map → impl-TPG3AZ2K.cjs.map} +1 -1
- package/dist/{impl-SVPD3IHV.cjs → impl-TR2HDZHR.cjs} +2 -2
- package/dist/{impl-SVPD3IHV.cjs.map → impl-TR2HDZHR.cjs.map} +1 -1
- package/dist/{impl-LKJFVX7E.cjs → impl-ULIJEGGC.cjs} +2 -2
- package/dist/{impl-LKJFVX7E.cjs.map → impl-ULIJEGGC.cjs.map} +1 -1
- package/dist/{impl-BL4XQEFX.cjs → impl-UNS2BXR7.cjs} +2 -2
- package/dist/{impl-BL4XQEFX.cjs.map → impl-UNS2BXR7.cjs.map} +1 -1
- package/dist/impl-VUTJ4QIY.cjs +2 -0
- package/dist/{impl-ALROZNDJ.cjs.map → impl-VUTJ4QIY.cjs.map} +1 -1
- package/dist/{impl-DXAKJNLZ.cjs → impl-WX2ULFZZ.cjs} +2 -2
- package/dist/{impl-DXAKJNLZ.cjs.map → impl-WX2ULFZZ.cjs.map} +1 -1
- package/dist/impl-XDFFTHEP.cjs +2 -0
- package/dist/{impl-M5QGTDLF.cjs.map → impl-XDFFTHEP.cjs.map} +1 -1
- package/dist/{impl-VZ6NJDAV.cjs → impl-XGCU7DCJ.cjs} +2 -2
- package/dist/{impl-VZ6NJDAV.cjs.map → impl-XGCU7DCJ.cjs.map} +1 -1
- package/dist/{impl-OFRMKTX5.cjs → impl-XPEPCZ67.cjs} +2 -2
- package/dist/{impl-OFRMKTX5.cjs.map → impl-XPEPCZ67.cjs.map} +1 -1
- package/dist/impl-XTRGFE33.cjs +2 -0
- package/dist/{impl-B7ODYIUX.cjs.map → impl-XTRGFE33.cjs.map} +1 -1
- package/dist/impl-XZYXPW67.cjs +2 -0
- package/dist/{impl-BDPD5CCN.cjs.map → impl-XZYXPW67.cjs.map} +1 -1
- package/dist/{impl-IFDUZGZM.cjs → impl-YLR5VYIP.cjs} +2 -2
- package/dist/{impl-IFDUZGZM.cjs.map → impl-YLR5VYIP.cjs.map} +1 -1
- package/dist/{impl-H2BRV4GP.cjs → impl-YTBJQDU6.cjs} +2 -2
- package/dist/{impl-H2BRV4GP.cjs.map → impl-YTBJQDU6.cjs.map} +1 -1
- package/dist/{impl-UZPP5VK5.cjs → impl-ZAXHTVRF.cjs} +2 -2
- package/dist/{impl-UZPP5VK5.cjs.map → impl-ZAXHTVRF.cjs.map} +1 -1
- package/dist/{impl-JPVEFSJB.cjs → impl-ZXJQNHSF.cjs} +2 -2
- package/dist/{impl-JPVEFSJB.cjs.map → impl-ZXJQNHSF.cjs.map} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10867 -5
- package/package.json +1 -1
- package/dist/chunk-7PF5VVAF.cjs +0 -4
- package/dist/chunk-7PF5VVAF.cjs.map +0 -1
- package/dist/chunk-ECGHWDVP.cjs.map +0 -1
- package/dist/chunk-KUBXRT3V.cjs +0 -2979
- package/dist/chunk-KUBXRT3V.cjs.map +0 -1
- package/dist/chunk-Q7I37FJV.cjs.map +0 -1
- package/dist/impl-ALROZNDJ.cjs +0 -2
- package/dist/impl-AP2ZTYJK.cjs +0 -2
- package/dist/impl-B7ODYIUX.cjs +0 -2
- package/dist/impl-BDPD5CCN.cjs +0 -2
- package/dist/impl-LDOILOAQ.cjs +0 -3
- package/dist/impl-LQEYNOZS.cjs +0 -2
- package/dist/impl-M5QGTDLF.cjs +0 -2
- package/dist/impl-PE52QYSI.cjs +0 -2
- package/dist/impl-PXT7QNSR.cjs +0 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/cli/cli/dist/index.cjs","../src/lib/ai/TranscendPromptManager.ts","../src/lib/graphql/fetchLargeLanguageModels.ts","../src/lib/ai/getGitFilesThatChanged.ts"],"names":["PAGE_SIZE","fetchAllLargeLanguageModels","client","largeLanguageModels","offset","shouldContinue","nodes","makeGraphQLRequest","LARGE_LANGUAGE_MODELS","a","b","createRegexForTag","tagName","defineTranscendPrompts","prompts","jsonParseSafe","obj","TranscendPromptManager","handlebarsOptions","transcendUrl","DEFAULT_TRANSCEND_API","transcendApiKey","requireApproval","cacheDuration","defaultVariables","buildTranscendGraphQLClient","createHandlebarsWithHelpers","promptDefinitions","getValues","promptIds","id","x","promptTitles","title","agentNames","uniq_default","response","agents","fetchPromptsWithVariables","fetchAllAgents","keyBy_default","model","promptByTitle","promptById","acc","v","partial","apply","result","name","agent","remoteAgent","ts","thread","fetchAllPromptThreads","names","hasCache","missingCache","groupBy_default","cachedAgents","chunkedNames","chunk_default","remoteAgents","mapSeries","chunkedName","pageOfAgents","filterBy","fetchAllAgentFiles","largeLanguageModel","matching"],"mappings":"AAAA,6OAAiE,wDAA0F,wDAAkD,wDAA0C,wDAA0E,wDAAkG,wDAAkE,wDAAkE,wDAAknB,wDAAo/G,wDAAgD,gCAA6B,wDAAuL,wDAA4E,qDCOt9J,iEAkBA,2DAaA,ICtBDA,CAAAA,CAAY,EAAA,CAQlB,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CAC+B,CAC/B,IAAMC,CAAAA,CAA4C,CAAC,CAAA,CAC/CC,CAAAA,CAAS,CAAA,CAGTC,CAAAA,CAAiB,CAAA,CAAA,CACrB,EAAG,CACD,GAAM,CACJ,mBAAA,CAAqB,CAAE,KAAA,CAAAC,CAAM,CAC/B,CAAA,CAAI,MAAMC,kCAAAA,CAMPL,CAAQM,oBAAAA,CAAuB,CAChC,KAAA,CAAOR,CAAAA,CACP,MAAA,CAAAI,CACF,CAAC,CAAA,CACDD,CAAAA,CAAoB,IAAA,C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EAAA,GAAO2B,CAAAA,CACb3B,CAAAA,CAAM,IAAA,GAAS2B,CAAAA,CAAmB,IAAA,EAClC3B,CAAAA,CAAM,MAAA,GAAW2B,CAAAA,CAAmB,MAC1C,CAAA,CACA,EAAA,CAAI,CAACC,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,CAAA,+BAAA,EACE,OAAOD,CAAAA,EAAuB,QAAA,CAC1BA,CAAAA,CACA,IAAA,CAAK,SAAA,CAAUA,CAAkB,CACvC,CAAA,CAAA;AE1ZG;AAiBI;AA4Bf","file":"/home/runner/work/cli/cli/dist/index.cjs","sourcesContent":[null,"/* eslint-disable max-lines */\nimport {\n Optionalize,\n Requirize,\n apply,\n decodeCodec,\n getValues,\n} from '@transcend-io/type-utils';\nimport type { Handlebars } from '@transcend-io/handlebars-utils';\nimport { Secret } from '@transcend-io/secret-value';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport {\n Agent,\n AgentFile,\n AgentFileFilterBy,\n ReportPromptRunInput,\n buildTranscendGraphQLClient,\n fetchAllAgentFiles,\n fetchAllAgents,\n reportPromptRun,\n} from '../graphql';\nimport {\n HandlebarsInput,\n createHandlebarsWithHelpers,\n} from '@transcend-io/handlebars-utils';\nimport {\n TranscendPromptTemplated,\n TranscendPromptsAndVariables,\n fetchPromptsWithVariables,\n} from '../graphql/fetchPrompts';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n PromptStatus,\n ChatCompletionRole,\n PromptRunProductArea,\n QueueStatus,\n LargeLanguageModelClient,\n} from '@transcend-io/privacy-types';\nimport {\n LargeLanguageModel,\n fetchAllLargeLanguageModels,\n} from '../graphql/fetchLargeLanguageModels';\nimport { groupBy, keyBy, uniq, chunk } from 'lodash-es';\nimport { mapSeries } from 'bluebird';\nimport {\n PromptThread,\n fetchAllPromptThreads,\n} from '../graphql/fetchPromptThreads';\n\n/**\n * An LLM Prompt definition\n */\nexport type TranscendPrompt<\n TInputParams extends t.Any,\n TOutputCodec extends t.Any,\n> = (\n | {\n /** ID of the prompt */\n id: string;\n /** Title of the prompt */\n title?: string;\n }\n | {\n /** ID of the prompt */\n id?: string;\n /** Title of the prompt */\n title: string;\n }\n) & {\n /** The names of the agents that should be loaded along with the prompt */\n agentNames?: string[];\n /** Codec to validate runtime input shape */\n paramCodec: TInputParams;\n /** Codec to validate output response */\n outputCodec: TOutputCodec;\n /**\n * If the output that needs to be parsed is returned within a tag\n * e.g. <tag> or <json> - this is the name of the tag\n */\n extractFromTag?: string;\n};\n\nexport interface PromptRunResult {\n /** The ID of the prompt run created on Transcend */\n promptRunId: string;\n /** The URL of the prompt run on Transcend */\n promptRunUrl: string;\n}\n\n/**\n * Create a regex to extract data from a tag\n *\n * Input:\n * \"here is some data <tag>Data</tag>...\"\n *\n * @param tagName - Name of tag\n * @returns Data within the tag\n */\nexport function createRegexForTag(tagName: string): RegExp {\n return new RegExp(`<${tagName}>([\\\\s\\\\S]+?)<\\\\/${tagName}>`);\n}\n\n/**\n * Helper function to declare prompts\n *\n * @param prompts - Prompt config\n * @returns Prompts as identity function - but type enforced\n */\nexport function defineTranscendPrompts<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n>(prompts: TPrompts): TPrompts {\n return prompts;\n}\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptParamType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['paramCodec']>;\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptResponseType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n\n/**\n * Input for reporting a prompt run\n */\nexport interface ReportPromptRunOptions\n extends Optionalize<\n Omit<ReportPromptRunInput, 'status' | 'promptId' | 'largeLanguageModelId'>,\n 'name' | 'productArea'\n > {\n /** The large language model being run. Either the ID of the LLM or the client/name pairing */\n largeLanguageModel:\n | string\n | {\n /** Name of client */\n client: LargeLanguageModelClient;\n /** Name of the model */\n name: string;\n };\n}\n\nconst jsonParseSafe = (obj: string): unknown => {\n try {\n return JSON.parse(obj);\n } catch (e) {\n return obj;\n }\n};\n\n/**\n * A class that is capable of loading and insert variables into prompts from\n * Transcend's Prompt Manager\n */\nexport class TranscendPromptManager<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n> {\n /** Prompt definitions */\n public prompts: TPrompts;\n\n /** Options for configuring handlebars */\n public handlebarsOptions!: HandlebarsInput;\n\n /** Prompt name -> content map, populated by call to Transcend API */\n public promptContentMap?: { [k in TPromptNames]: TranscendPromptTemplated };\n\n /** The large language models that are registered to this organization for reporting */\n public largeLanguageModels: LargeLanguageModel[] = [];\n\n /** The agent definitions registered to this organization */\n private agentsByName: { [name in string]: Agent } = {};\n\n /** The agent definitions registered to this organization */\n private agentsByAgentId: { [id in string]: Agent } = {};\n\n /** The GraphQL client that can be used to call Transcend */\n public graphQLClient: GraphQLClient;\n\n /** The set of variables to expose in handlebars context specified at class initiation */\n public defaultVariables: { [k in string]: unknown };\n\n /**\n * The set of variables to expose in handlebars context,\n * merges defaults with calculated variables from the inventory\n */\n public variables: { [k in string]: unknown };\n\n /** Handlebars compiler */\n public handlebars: typeof Handlebars;\n\n /** The Transcend API key */\n public transcendApiKey: string | Secret<string>;\n\n /** API of Transcend to call */\n public transcendUrl: string;\n\n /** When true, throw an error if the prompt is not approved */\n public requireApproval: boolean;\n\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n public cacheDuration?: number;\n\n /**\n * The last time the metadata was fetched\n */\n public lastUpdatedAt?: Date;\n\n /**\n * Constructor\n *\n * @param options - Options\n */\n constructor({\n prompts,\n handlebarsOptions = {},\n transcendUrl = DEFAULT_TRANSCEND_API,\n transcendApiKey,\n requireApproval = true,\n cacheDuration,\n defaultVariables = {},\n }: {\n /** Prompt definitions to load */\n prompts: TPrompts;\n /** Options for configuring handlebars */\n handlebarsOptions?: HandlebarsInput;\n /** The Transcend API key */\n transcendApiKey: string | Secret<string>;\n /** API of Transcend to call */\n transcendUrl?: string;\n /** When true, throw an error if the prompt is not approved */\n requireApproval?: boolean;\n /** The set of variables to expose in handlebars context specified at class initiation */\n defaultVariables?: { [k in string]: unknown };\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n cacheDuration?: number;\n }) {\n this.prompts = prompts;\n this.transcendUrl = transcendUrl;\n this.transcendApiKey = transcendApiKey;\n this.variables = defaultVariables;\n this.defaultVariables = defaultVariables;\n this.graphQLClient = buildTranscendGraphQLClient(\n transcendUrl,\n typeof transcendApiKey === 'object'\n ? transcendApiKey.release()\n : transcendApiKey,\n );\n this.requireApproval = requireApproval;\n this.cacheDuration = cacheDuration;\n this.handlebarsOptions = handlebarsOptions;\n this.handlebars = createHandlebarsWithHelpers(handlebarsOptions);\n }\n\n /**\n * Fetch prompt metadata from Transcend and cache to the class definition\n *\n * @returns A function that can be used to call the prompt\n */\n async fetchPromptsAndMetadata(): Promise<TranscendPromptsAndVariables> {\n // Determine what to fetch\n const promptDefinitions = getValues(this.prompts) as TranscendPrompt<\n t.Any,\n t.Any\n >[];\n const promptIds = promptDefinitions\n .map(({ id }) => id)\n .filter((x): x is string => !!x);\n const promptTitles = promptDefinitions\n .map(({ title }) => title)\n .filter((x): x is string => !!x);\n const agentNames = uniq(\n promptDefinitions.map(({ agentNames }) => agentNames || []).flat(),\n );\n\n // Fetch prompts and data\n const [response, largeLanguageModels, agents] = await Promise.all([\n fetchPromptsWithVariables(this.graphQLClient, {\n promptIds,\n promptTitles,\n }),\n fetchAllLargeLanguageModels(this.graphQLClient),\n fetchAllAgents(this.graphQLClient, { names: agentNames }),\n ]);\n this.agentsByName = keyBy(agents, 'name');\n this.agentsByAgentId = keyBy(agents, 'agentId');\n this.largeLanguageModels = largeLanguageModels.filter(\n (model) => model.isTranscendHosted === false,\n );\n\n // Lookup prompts by id/title\n const promptByTitle = keyBy(response.prompts, 'title');\n const promptById = keyBy(response.prompts, 'id');\n\n // Update variables\n this.variables = {\n ...response.calculatedVariables.reduce(\n (acc, v) =>\n Object.assign(acc, {\n [v.name]: v.data ? JSON.parse(v.data) : v.data,\n }),\n {},\n ),\n ...this.defaultVariables,\n };\n\n // Update partials\n this.handlebars = createHandlebarsWithHelpers({\n ...this.handlebarsOptions,\n templates: [\n ...(this.handlebarsOptions.templates || []),\n ...response.promptPartials.map((partial) => ({\n name: partial.slug,\n content: partial.content,\n })),\n ],\n });\n\n // Create mapping from prompt to content\n this.promptContentMap = apply(this.prompts, ({ id, title }) => {\n const result = id\n ? promptById[id]\n : title\n ? promptByTitle[title]\n : undefined;\n if (!result) {\n throw new Error(\n `Failed to find prompt with title: \"${title}\" and id: \"${id}\"`,\n );\n }\n return result;\n });\n\n // For cache\n this.lastUpdatedAt = new Date();\n\n return response;\n }\n\n /**\n * Get an agent definition by name\n *\n * @param name - Name of the agent to grab\n * @returns Large language model configuration\n */\n async getAgentByName(name: string): Promise<Agent | undefined> {\n const agent = this.agentsByName[name];\n if (agent) {\n return agent;\n }\n const [remoteAgent] = await fetchAllAgents(this.graphQLClient, {\n names: [name],\n });\n if (!remoteAgent) {\n return undefined;\n }\n this.agentsByName[remoteAgent.name] = remoteAgent;\n this.agentsByAgentId[remoteAgent.agentId] = remoteAgent;\n return remoteAgent;\n }\n\n /**\n * Get a prompt thread by ts\n *\n * @param ts - the slack message timestamp to look up thread for\n * @returns Large language model configuration\n */\n async getPromptThreadBySlackTs(\n ts: string,\n ): Promise<PromptThread | undefined> {\n const [thread] = await fetchAllPromptThreads(this.graphQLClient, {\n slackMessageTs: [ts],\n });\n return thread;\n }\n\n /**\n * Get a list of agent definitions by name.\n * Pulls from cache and may return less agents\n * than requested if some are not found\n *\n * @param names - Names of agents to fetch\n * @returns The agents that were found matching the names\n */\n async getAgentsByName(names: string[]): Promise<Agent[]> {\n if (names.length < 1) {\n throw new Error('Expected at least one name to be provided');\n }\n const { hasCache = [], missingCache = [] } = groupBy(names, (name) =>\n this.agentsByName[name] ? 'hasCache' : 'missingCache',\n );\n const cachedAgents = hasCache.map((name) => this.agentsByName[name]);\n if (missingCache.length === 0) {\n return cachedAgents;\n }\n const chunkedNames = chunk(missingCache, 50);\n const remoteAgents: Agent[] = [];\n await mapSeries(chunkedNames, async (chunkedName) => {\n const pageOfAgents = await fetchAllAgents(this.graphQLClient, {\n names: chunkedName,\n });\n pageOfAgents.forEach((agent) => {\n this.agentsByName[agent.name] = agent;\n this.agentsByAgentId[agent.agentId] = agent;\n });\n remoteAgents.push(...pageOfAgents);\n });\n return [...cachedAgents, ...remoteAgents];\n }\n\n /**\n * Fetch metadata on agent files\n *\n * @param filterBy - Filter by parameters\n * @returns The files found matching the filter\n */\n getAgentFiles(filterBy: AgentFileFilterBy): Promise<AgentFile[]> {\n return fetchAllAgentFiles(this.graphQLClient, filterBy);\n }\n\n /**\n * Look up the large language model to report on\n *\n * @param largeLanguageModel - Input\n * @returns Large language model configuration\n */\n getLargeLanguageModel(\n largeLanguageModel: ReportPromptRunOptions['largeLanguageModel'],\n ): LargeLanguageModel {\n const matching = this.largeLanguageModels.find((model) =>\n typeof largeLanguageModel === 'string'\n ? model.id === largeLanguageModel\n : model.name === largeLanguageModel.name &&\n model.client === largeLanguageModel.client,\n );\n if (!matching) {\n throw new Error(\n `Failed to find model matching: ${\n typeof largeLanguageModel === 'string'\n ? largeLanguageModel\n : JSON.stringify(largeLanguageModel)\n }`,\n );\n }\n return matching;\n }\n\n /**\n * Get a prompt definition by name\n *\n * @param promptName - Prompt to compile\n * @returns Parsed content\n */\n async getPromptDefinition<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n ): Promise<TranscendPromptTemplated> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n // Lookup prompt\n const { promptContentMap } = this;\n if (!promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n const promptTemplate = promptContentMap[promptName];\n if (!promptTemplate) {\n throw new Error(\n `Expected this.promptContentMap[${promptName}] to be defined`,\n );\n }\n return promptTemplate;\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to compile\n * @param params - Runtime parameters\n * @returns Parsed content\n */\n async compilePrompt<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n params: t.TypeOf<TPrompts[TPromptName]['paramCodec']>,\n ): Promise<string> {\n // Grab the prompt\n const promptTemplate = await this.getPromptDefinition(promptName);\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure prompt is approved\n if (\n this.requireApproval &&\n promptTemplate.status !== PromptStatus.Approved\n ) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because its in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // If prompt is rejected, throw error\n if (promptTemplate.status === PromptStatus.Rejected) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because it's in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // Validate params\n decodeCodec(promptInput.paramCodec, params);\n\n // Compile prompt and template\n return this.handlebars.compile(promptTemplate.content)({\n // template in currentDate by default\n currentDate: new Date().toISOString(),\n ...this.variables,\n ...params,\n });\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to parse\n * @param response - AI response as string\n * @returns Parsed content\n */\n parseAiResponse<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n response: string,\n ): t.TypeOf<TPrompts[TPromptName]['outputCodec']> {\n // Look up prompt info\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Extract from tag if needed\n const extracted = promptInput.extractFromTag\n ? (createRegexForTag(promptInput.extractFromTag).exec(response) ||\n [])[1] || response\n : response;\n\n // Parse via codec\n return decodeCodec(\n promptInput.outputCodec,\n jsonParseSafe(extracted),\n false,\n );\n }\n\n /**\n * Parse the AI response and report back to Transcend\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportAndParsePromptRun<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n { largeLanguageModel, ...options }: ReportPromptRunOptions,\n ): Promise<\n PromptRunResult & {\n /** Resulting prompt run */\n result: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n }\n > {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n if (\n options.promptRunMessages[options.promptRunMessages.length - 1].role !==\n ChatCompletionRole.Assistant\n ) {\n throw new Error(\n `promptRunMessages[${\n options.promptRunMessages.length - 1\n }].role is expected to be = ${ChatCompletionRole.Assistant}`,\n );\n }\n const response =\n options.promptRunMessages[options.promptRunMessages.length - 1].content;\n\n let parsed: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n try {\n // Parse the response\n parsed = this.parseAiResponse(promptName, response);\n } catch (err) {\n await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n error: err.message,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n throw err;\n }\n\n // report successful run\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Resolved,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n result: parsed,\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n\n /**\n * Report an error for a particular prompt\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportPromptRunError<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n {\n largeLanguageModel,\n ...options\n }: Requirize<ReportPromptRunOptions, 'error'>,\n ): Promise<PromptRunResult> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n}\n/* eslint-enable max-lines */\n","import { GraphQLClient } from 'graphql-request';\nimport { LargeLanguageModelClient } from '@transcend-io/privacy-types';\nimport { LARGE_LANGUAGE_MODELS } from './gqls';\nimport { makeGraphQLRequest } from './makeGraphQLRequest';\n\nexport interface LargeLanguageModel {\n /** ID of prompts */\n id: string;\n /** The name of the large language model. */\n name: string;\n /** The content of the prompt template. */\n client: LargeLanguageModelClient;\n /** Whether hosted by Transcend or not */\n isTranscendHosted: boolean;\n}\n\nconst PAGE_SIZE = 20;\n\n/**\n * Fetch all LargeLanguageModels in the organization\n *\n * @param client - GraphQL client\n * @returns All LargeLanguageModels in the organization\n */\nexport async function fetchAllLargeLanguageModels(\n client: GraphQLClient,\n): Promise<LargeLanguageModel[]> {\n const largeLanguageModels: LargeLanguageModel[] = [];\n let offset = 0;\n\n // Whether to continue looping\n let shouldContinue = false;\n do {\n const {\n largeLanguageModels: { nodes },\n } = await makeGraphQLRequest<{\n /** LargeLanguageModels */\n largeLanguageModels: {\n /** List */\n nodes: LargeLanguageModel[];\n };\n }>(client, LARGE_LANGUAGE_MODELS, {\n first: PAGE_SIZE,\n offset,\n });\n largeLanguageModels.push(...nodes);\n offset += PAGE_SIZE;\n shouldContinue = nodes.length === PAGE_SIZE;\n } while (shouldContinue);\n\n return largeLanguageModels.sort((a, b) => a.name.localeCompare(b.name));\n}\n","import { difference } from 'lodash-es';\nimport fastGlob from 'fast-glob';\nimport { execSync } from 'child_process';\n\n/**\n * Function thats gets the git files that have changed\n * and returns the code\n *\n * @param options - Options\n * @returns Changes files and diffs\n */\nexport function getGitFilesThatChanged({\n baseBranch,\n rootDirectory,\n githubRepo,\n excludedGlob = [],\n fileBlockList = [],\n}: {\n /** Base branch */\n baseBranch: string;\n /** Github repo name */\n githubRepo: string;\n /** Root directory */\n rootDirectory: string;\n /** A glob that excludes files */\n excludedGlob?: string[];\n /** Block list of files to not process */\n fileBlockList?: string[];\n}): {\n /** The list of files that changed */\n changedFiles: string[];\n /** Github repo name */\n repoName: string;\n /** Current commit */\n commit: string;\n /** File diffs */\n fileDiffs: { [k in string]: string };\n} {\n // Pull base branch\n execSync(`git fetch origin ${baseBranch}`);\n\n // Latest commit on base branch. If we are on the base branch, we take the prior commit\n const latestBasedCommit = execSync(\n `git ls-remote ${githubRepo} \"refs/heads/${baseBranch}\" | cut -f 1`,\n { encoding: 'utf-8' },\n ).split('\\n')[0];\n\n // This commit\n const latestThisCommit = execSync('git rev-parse HEAD', {\n encoding: 'utf-8',\n }).split('\\n')[0];\n\n // Ensure commits are present\n if (!latestBasedCommit || !latestThisCommit) {\n throw new Error('FAILED TO FIND COMMIT RANGE');\n }\n\n // Get the diff between the given branch and base branch\n const diff = execSync(\n `git fetch && git diff --name-only \"${\n baseBranch || latestBasedCommit\n }...${latestThisCommit}\" -- ${rootDirectory}`,\n { encoding: 'utf-8' },\n );\n\n // Filter out block list\n const changedFiles = difference(\n diff.split('\\n').filter((f) => f),\n fileBlockList,\n );\n\n // Filter out globs\n const filteredChanges =\n excludedGlob.length > 0\n ? fastGlob.sync(changedFiles, { ignore: excludedGlob })\n : changedFiles;\n\n // Get the contents of only the changed files\n const fileDiffs: { [k in string]: string } = {};\n filteredChanges.forEach((file) => {\n const contents = execSync(`git show ${latestThisCommit}:${file}`, {\n encoding: 'utf-8',\n });\n fileDiffs[file] = contents;\n });\n\n // Pull the github repo name\n const repoName = githubRepo.split('/').pop()!.split('.')[0];\n\n return {\n changedFiles,\n fileDiffs,\n repoName,\n commit: latestThisCommit,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/cli/cli/dist/index.cjs","../src/lib/ai/TranscendPromptManager.ts","../src/lib/graphql/fetchLargeLanguageModels.ts","../src/lib/ai/getGitFilesThatChanged.ts"],"names":["PAGE_SIZE","fetchAllLargeLanguageModels","client","largeLanguageModels","offset","shouldContinue","nodes","makeGraphQLRequest","LARGE_LANGUAGE_MODELS","a","b","createRegexForTag","tagName","defineTranscendPrompts","prompts","jsonParseSafe","obj","TranscendPromptManager","handlebarsOptions","transcendUrl","DEFAULT_TRANSCEND_API","transcendApiKey","requireApproval","cacheDuration","defaultVariables","buildTranscendGraphQLClient","createHandlebarsWithHelpers","promptDefinitions","getValues","promptIds","id","x","promptTitles","title","agentNames","uniq_default","response","agents","fetchPromptsWithVariables","fetchAllAgents","keyBy_default","model","promptByTitle","promptById","acc","v","partial","apply","result","name","agent","remoteAgent","ts","thread","fetchAllPromptThreads","names","hasCache","missingCache","groupBy_default","cachedAgents","chunkedNames","chunk_default","remoteAgents","mapSeries","chunkedName","pageOfAgents","filterBy","fetchAllAgentFiles","largeLanguageModel","matching"],"mappings":"AAAA,6OAAiE,wDAA0F,wDAAkD,wDAA0C,wDAA0E,wDAAkG,wDAAkE,wDAAkE,wDAA2nB,wDAAsgH,wDAAgD,gCAA6B,wDAAuL,wDAA4E,qDCOj/J,iEAkBA,2DAaA,ICtBDA,CAAAA,CAAY,EAAA,CAQlB,MAAA,SAAsBC,CAAAA,CACpBC,CAAAA,CAC+B,CAC/B,IAAMC,CAAAA,CAA4C,CAAC,CAAA,CAC/CC,CAAAA,CAAS,CAAA,CAGTC,CAAAA,CAAiB,CAAA,CAAA,CACrB,EAAG,CACD,GAAM,CACJ,mBAAA,CAAqB,CAAE,KAAA,CAAAC,CAAM,CAC/B,CAAA,CAAI,MAAMC,kCAAAA,CAMPL,CAAQM,oBAAAA,CAAuB,CAChC,KAAA,CAAOR,CAAAA,CACP,MAAA,CAAAI,CACF,CAAC,CAAA,CACDD,CAAAA,CAAoB,IAAA,CAAK,GAAGG,CAAK,CAAA,CACjCF,CAAAA,EAAUJ,CAAAA,CACVK,CAAAA,CAAiBC,CAAAA,CAAM,MAAA,GAAWN,CACpC,CAAA,KAAA,CAASK,CAAAA,CAAAA,CAET,OAAOF,CAAAA,CAAoB,IAAA,CAAK,CAACM,CAAAA,CAAGC,CAAAA,CAAAA,EAAMD,CAAAA,CAAE,IAAA,CAAK,aAAA,CAAcC,CAAAA,CAAE,IAAI,CAAC,CACxE,CDPA,oCAA0B,SAuDVC,CAAAA,CAAkBC,CAAAA,CAAyB,CACzD,OAAO,IAAI,MAAA,CAAO,CAAA,CAAA,EAAIA,CAAO,CAAA,iBAAA,EAAoBA,CAAO,CAAA,CAAA,CAAG,CAC7D,CAQO,SAASC,EAAAA,CAGdC,CAAAA,CAA6B,CAC7B,OAAOA,CACT,CAqCA,IAAMC,CAAAA,CAAiBC,CAAAA,EAAyB,CAC9C,GAAI,CACF,OAAO,IAA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kCAAAA,IAAe,CAAK,aAAA,CAAe,CAC5D,KAAA,CAAOyB,CACT,CAAC,CAAA,CACDC,CAAAA,CAAa,OAAA,CAASf,CAAAA,EAAU,CAC9B,IAAA,CAAK,YAAA,CAAaA,CAAAA,CAAM,IAAI,CAAA,CAAIA,CAAAA,CAChC,IAAA,CAAK,eAAA,CAAgBA,CAAAA,CAAM,OAAO,CAAA,CAAIA,CACxC,CAAC,CAAA,CACDY,CAAAA,CAAa,IAAA,CAAK,GAAGG,CAAY,CACnC,CAAC,CAAA,CACM,CAAC,GAAGN,CAAAA,CAAc,GAAGG,CAAY,CAC1C,CAQA,aAAA,CAAcI,CAAAA,CAAmD,CAC/D,OAAOC,kCAAAA,IAAmB,CAAK,aAAA,CAAeD,CAAQ,CACxD,CAQA,qBAAA,CACEE,CAAAA,CACoB,CACpB,IAAMC,CAAAA,CAAW,IAAA,CAAK,mBAAA,CAAoB,IAAA,CAAM5B,CAAAA,EAC9C,OAAO2B,CAAAA,EAAuB,QAAA,CAC1B3B,CAAAA,CAAM,EAAA,GAAO2B,CAAAA,CACb3B,CAAAA,CAAM,IAAA,GAAS2B,CAAAA,CAAmB,IAAA,EAClC3B,CAAAA,CAAM,MAAA,GAAW2B,CAAAA,CAAmB,MAC1C,CAAA,CACA,EAAA,CAAI,CAACC,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,CAAA,+BAAA,EACE,OAAOD,CAAAA,EAAuB,QAAA,CAC1BA,CAAAA,CACA,IAAA,CAAK,SAAA,CAAUA,CAAkB,CACvC,CAAA,CAAA;AE1ZG;AAiBI;AA4Bf","file":"/home/runner/work/cli/cli/dist/index.cjs","sourcesContent":[null,"/* eslint-disable max-lines */\nimport {\n Optionalize,\n Requirize,\n apply,\n decodeCodec,\n getValues,\n} from '@transcend-io/type-utils';\nimport type { Handlebars } from '@transcend-io/handlebars-utils';\nimport { Secret } from '@transcend-io/secret-value';\nimport * as t from 'io-ts';\nimport { DEFAULT_TRANSCEND_API } from '../../constants';\nimport {\n Agent,\n AgentFile,\n AgentFileFilterBy,\n ReportPromptRunInput,\n buildTranscendGraphQLClient,\n fetchAllAgentFiles,\n fetchAllAgents,\n reportPromptRun,\n} from '../graphql';\nimport {\n HandlebarsInput,\n createHandlebarsWithHelpers,\n} from '@transcend-io/handlebars-utils';\nimport {\n TranscendPromptTemplated,\n TranscendPromptsAndVariables,\n fetchPromptsWithVariables,\n} from '../graphql/fetchPrompts';\nimport { GraphQLClient } from 'graphql-request';\nimport {\n PromptStatus,\n ChatCompletionRole,\n PromptRunProductArea,\n QueueStatus,\n LargeLanguageModelClient,\n} from '@transcend-io/privacy-types';\nimport {\n LargeLanguageModel,\n fetchAllLargeLanguageModels,\n} from '../graphql/fetchLargeLanguageModels';\nimport { groupBy, keyBy, uniq, chunk } from 'lodash-es';\nimport { mapSeries } from 'bluebird';\nimport {\n PromptThread,\n fetchAllPromptThreads,\n} from '../graphql/fetchPromptThreads';\n\n/**\n * An LLM Prompt definition\n */\nexport type TranscendPrompt<\n TInputParams extends t.Any,\n TOutputCodec extends t.Any,\n> = (\n | {\n /** ID of the prompt */\n id: string;\n /** Title of the prompt */\n title?: string;\n }\n | {\n /** ID of the prompt */\n id?: string;\n /** Title of the prompt */\n title: string;\n }\n) & {\n /** The names of the agents that should be loaded along with the prompt */\n agentNames?: string[];\n /** Codec to validate runtime input shape */\n paramCodec: TInputParams;\n /** Codec to validate output response */\n outputCodec: TOutputCodec;\n /**\n * If the output that needs to be parsed is returned within a tag\n * e.g. <tag> or <json> - this is the name of the tag\n */\n extractFromTag?: string;\n};\n\nexport interface PromptRunResult {\n /** The ID of the prompt run created on Transcend */\n promptRunId: string;\n /** The URL of the prompt run on Transcend */\n promptRunUrl: string;\n}\n\n/**\n * Create a regex to extract data from a tag\n *\n * Input:\n * \"here is some data <tag>Data</tag>...\"\n *\n * @param tagName - Name of tag\n * @returns Data within the tag\n */\nexport function createRegexForTag(tagName: string): RegExp {\n return new RegExp(`<${tagName}>([\\\\s\\\\S]+?)<\\\\/${tagName}>`);\n}\n\n/**\n * Helper function to declare prompts\n *\n * @param prompts - Prompt config\n * @returns Prompts as identity function - but type enforced\n */\nexport function defineTranscendPrompts<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n>(prompts: TPrompts): TPrompts {\n return prompts;\n}\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptParamType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['paramCodec']>;\n\n/**\n * Helper to get the type of the parameter for a given prompt\n */\nexport type GetPromptResponseType<\n TPromptName extends keyof TPrompts,\n TPrompts extends { [k in TPromptName]: TranscendPrompt<t.Any, t.Any> },\n> = t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n\n/**\n * Input for reporting a prompt run\n */\nexport interface ReportPromptRunOptions\n extends Optionalize<\n Omit<ReportPromptRunInput, 'status' | 'promptId' | 'largeLanguageModelId'>,\n 'name' | 'productArea'\n > {\n /** The large language model being run. Either the ID of the LLM or the client/name pairing */\n largeLanguageModel:\n | string\n | {\n /** Name of client */\n client: LargeLanguageModelClient;\n /** Name of the model */\n name: string;\n };\n}\n\nconst jsonParseSafe = (obj: string): unknown => {\n try {\n return JSON.parse(obj);\n } catch (e) {\n return obj;\n }\n};\n\n/**\n * A class that is capable of loading and insert variables into prompts from\n * Transcend's Prompt Manager\n */\nexport class TranscendPromptManager<\n TPromptNames extends string,\n TPrompts extends { [k in TPromptNames]: TranscendPrompt<t.Any, t.Any> },\n> {\n /** Prompt definitions */\n public prompts: TPrompts;\n\n /** Options for configuring handlebars */\n public handlebarsOptions!: HandlebarsInput;\n\n /** Prompt name -> content map, populated by call to Transcend API */\n public promptContentMap?: { [k in TPromptNames]: TranscendPromptTemplated };\n\n /** The large language models that are registered to this organization for reporting */\n public largeLanguageModels: LargeLanguageModel[] = [];\n\n /** The agent definitions registered to this organization */\n private agentsByName: { [name in string]: Agent } = {};\n\n /** The agent definitions registered to this organization */\n private agentsByAgentId: { [id in string]: Agent } = {};\n\n /** The GraphQL client that can be used to call Transcend */\n public graphQLClient: GraphQLClient;\n\n /** The set of variables to expose in handlebars context specified at class initiation */\n public defaultVariables: { [k in string]: unknown };\n\n /**\n * The set of variables to expose in handlebars context,\n * merges defaults with calculated variables from the inventory\n */\n public variables: { [k in string]: unknown };\n\n /** Handlebars compiler */\n public handlebars: typeof Handlebars;\n\n /** The Transcend API key */\n public transcendApiKey: string | Secret<string>;\n\n /** API of Transcend to call */\n public transcendUrl: string;\n\n /** When true, throw an error if the prompt is not approved */\n public requireApproval: boolean;\n\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n public cacheDuration?: number;\n\n /**\n * The last time the metadata was fetched\n */\n public lastUpdatedAt?: Date;\n\n /**\n * Constructor\n *\n * @param options - Options\n */\n constructor({\n prompts,\n handlebarsOptions = {},\n transcendUrl = DEFAULT_TRANSCEND_API,\n transcendApiKey,\n requireApproval = true,\n cacheDuration,\n defaultVariables = {},\n }: {\n /** Prompt definitions to load */\n prompts: TPrompts;\n /** Options for configuring handlebars */\n handlebarsOptions?: HandlebarsInput;\n /** The Transcend API key */\n transcendApiKey: string | Secret<string>;\n /** API of Transcend to call */\n transcendUrl?: string;\n /** When true, throw an error if the prompt is not approved */\n requireApproval?: boolean;\n /** The set of variables to expose in handlebars context specified at class initiation */\n defaultVariables?: { [k in string]: unknown };\n /**\n * The cache duration in ms for how long prompts and associated metadata should be cached\n * When undefined - prompts are cached indefinitely unless explicitly re-requested\n * When 0, prompts and metadata are fetched every time (not recommended)\n * Setting this to be an hour is a good rate that optimizes for performance and keeping up to date\n */\n cacheDuration?: number;\n }) {\n this.prompts = prompts;\n this.transcendUrl = transcendUrl;\n this.transcendApiKey = transcendApiKey;\n this.variables = defaultVariables;\n this.defaultVariables = defaultVariables;\n this.graphQLClient = buildTranscendGraphQLClient(\n transcendUrl,\n typeof transcendApiKey === 'object'\n ? transcendApiKey.release()\n : transcendApiKey,\n );\n this.requireApproval = requireApproval;\n this.cacheDuration = cacheDuration;\n this.handlebarsOptions = handlebarsOptions;\n this.handlebars = createHandlebarsWithHelpers(handlebarsOptions);\n }\n\n /**\n * Fetch prompt metadata from Transcend and cache to the class definition\n *\n * @returns A function that can be used to call the prompt\n */\n async fetchPromptsAndMetadata(): Promise<TranscendPromptsAndVariables> {\n // Determine what to fetch\n const promptDefinitions = getValues(this.prompts) as TranscendPrompt<\n t.Any,\n t.Any\n >[];\n const promptIds = promptDefinitions\n .map(({ id }) => id)\n .filter((x): x is string => !!x);\n const promptTitles = promptDefinitions\n .map(({ title }) => title)\n .filter((x): x is string => !!x);\n const agentNames = uniq(\n promptDefinitions.map(({ agentNames }) => agentNames || []).flat(),\n );\n\n // Fetch prompts and data\n const [response, largeLanguageModels, agents] = await Promise.all([\n fetchPromptsWithVariables(this.graphQLClient, {\n promptIds,\n promptTitles,\n }),\n fetchAllLargeLanguageModels(this.graphQLClient),\n fetchAllAgents(this.graphQLClient, { names: agentNames }),\n ]);\n this.agentsByName = keyBy(agents, 'name');\n this.agentsByAgentId = keyBy(agents, 'agentId');\n this.largeLanguageModels = largeLanguageModels.filter(\n (model) => model.isTranscendHosted === false,\n );\n\n // Lookup prompts by id/title\n const promptByTitle = keyBy(response.prompts, 'title');\n const promptById = keyBy(response.prompts, 'id');\n\n // Update variables\n this.variables = {\n ...response.calculatedVariables.reduce(\n (acc, v) =>\n Object.assign(acc, {\n [v.name]: v.data ? JSON.parse(v.data) : v.data,\n }),\n {},\n ),\n ...this.defaultVariables,\n };\n\n // Update partials\n this.handlebars = createHandlebarsWithHelpers({\n ...this.handlebarsOptions,\n templates: [\n ...(this.handlebarsOptions.templates || []),\n ...response.promptPartials.map((partial) => ({\n name: partial.slug,\n content: partial.content,\n })),\n ],\n });\n\n // Create mapping from prompt to content\n this.promptContentMap = apply(this.prompts, ({ id, title }) => {\n const result = id\n ? promptById[id]\n : title\n ? promptByTitle[title]\n : undefined;\n if (!result) {\n throw new Error(\n `Failed to find prompt with title: \"${title}\" and id: \"${id}\"`,\n );\n }\n return result;\n });\n\n // For cache\n this.lastUpdatedAt = new Date();\n\n return response;\n }\n\n /**\n * Get an agent definition by name\n *\n * @param name - Name of the agent to grab\n * @returns Large language model configuration\n */\n async getAgentByName(name: string): Promise<Agent | undefined> {\n const agent = this.agentsByName[name];\n if (agent) {\n return agent;\n }\n const [remoteAgent] = await fetchAllAgents(this.graphQLClient, {\n names: [name],\n });\n if (!remoteAgent) {\n return undefined;\n }\n this.agentsByName[remoteAgent.name] = remoteAgent;\n this.agentsByAgentId[remoteAgent.agentId] = remoteAgent;\n return remoteAgent;\n }\n\n /**\n * Get a prompt thread by ts\n *\n * @param ts - the slack message timestamp to look up thread for\n * @returns Large language model configuration\n */\n async getPromptThreadBySlackTs(\n ts: string,\n ): Promise<PromptThread | undefined> {\n const [thread] = await fetchAllPromptThreads(this.graphQLClient, {\n slackMessageTs: [ts],\n });\n return thread;\n }\n\n /**\n * Get a list of agent definitions by name.\n * Pulls from cache and may return less agents\n * than requested if some are not found\n *\n * @param names - Names of agents to fetch\n * @returns The agents that were found matching the names\n */\n async getAgentsByName(names: string[]): Promise<Agent[]> {\n if (names.length < 1) {\n throw new Error('Expected at least one name to be provided');\n }\n const { hasCache = [], missingCache = [] } = groupBy(names, (name) =>\n this.agentsByName[name] ? 'hasCache' : 'missingCache',\n );\n const cachedAgents = hasCache.map((name) => this.agentsByName[name]);\n if (missingCache.length === 0) {\n return cachedAgents;\n }\n const chunkedNames = chunk(missingCache, 50);\n const remoteAgents: Agent[] = [];\n await mapSeries(chunkedNames, async (chunkedName) => {\n const pageOfAgents = await fetchAllAgents(this.graphQLClient, {\n names: chunkedName,\n });\n pageOfAgents.forEach((agent) => {\n this.agentsByName[agent.name] = agent;\n this.agentsByAgentId[agent.agentId] = agent;\n });\n remoteAgents.push(...pageOfAgents);\n });\n return [...cachedAgents, ...remoteAgents];\n }\n\n /**\n * Fetch metadata on agent files\n *\n * @param filterBy - Filter by parameters\n * @returns The files found matching the filter\n */\n getAgentFiles(filterBy: AgentFileFilterBy): Promise<AgentFile[]> {\n return fetchAllAgentFiles(this.graphQLClient, filterBy);\n }\n\n /**\n * Look up the large language model to report on\n *\n * @param largeLanguageModel - Input\n * @returns Large language model configuration\n */\n getLargeLanguageModel(\n largeLanguageModel: ReportPromptRunOptions['largeLanguageModel'],\n ): LargeLanguageModel {\n const matching = this.largeLanguageModels.find((model) =>\n typeof largeLanguageModel === 'string'\n ? model.id === largeLanguageModel\n : model.name === largeLanguageModel.name &&\n model.client === largeLanguageModel.client,\n );\n if (!matching) {\n throw new Error(\n `Failed to find model matching: ${\n typeof largeLanguageModel === 'string'\n ? largeLanguageModel\n : JSON.stringify(largeLanguageModel)\n }`,\n );\n }\n return matching;\n }\n\n /**\n * Get a prompt definition by name\n *\n * @param promptName - Prompt to compile\n * @returns Parsed content\n */\n async getPromptDefinition<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n ): Promise<TranscendPromptTemplated> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n // Lookup prompt\n const { promptContentMap } = this;\n if (!promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n const promptTemplate = promptContentMap[promptName];\n if (!promptTemplate) {\n throw new Error(\n `Expected this.promptContentMap[${promptName}] to be defined`,\n );\n }\n return promptTemplate;\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to compile\n * @param params - Runtime parameters\n * @returns Parsed content\n */\n async compilePrompt<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n params: t.TypeOf<TPrompts[TPromptName]['paramCodec']>,\n ): Promise<string> {\n // Grab the prompt\n const promptTemplate = await this.getPromptDefinition(promptName);\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure prompt is approved\n if (\n this.requireApproval &&\n promptTemplate.status !== PromptStatus.Approved\n ) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because its in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // If prompt is rejected, throw error\n if (promptTemplate.status === PromptStatus.Rejected) {\n throw new Error(\n `Assessment \"${promptTemplate.title}\" cannot be used because it's in status: \"${promptTemplate.status}\"`,\n );\n }\n\n // Validate params\n decodeCodec(promptInput.paramCodec, params);\n\n // Compile prompt and template\n return this.handlebars.compile(promptTemplate.content)({\n // template in currentDate by default\n currentDate: new Date().toISOString(),\n ...this.variables,\n ...params,\n });\n }\n\n /**\n * Validate the shape of the response from AI\n *\n * @param promptName - Prompt to parse\n * @param response - AI response as string\n * @returns Parsed content\n */\n parseAiResponse<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n response: string,\n ): t.TypeOf<TPrompts[TPromptName]['outputCodec']> {\n // Look up prompt info\n const promptInput = this.prompts[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Extract from tag if needed\n const extracted = promptInput.extractFromTag\n ? (createRegexForTag(promptInput.extractFromTag).exec(response) ||\n [])[1] || response\n : response;\n\n // Parse via codec\n return decodeCodec(\n promptInput.outputCodec,\n jsonParseSafe(extracted),\n false,\n );\n }\n\n /**\n * Parse the AI response and report back to Transcend\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportAndParsePromptRun<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n { largeLanguageModel, ...options }: ReportPromptRunOptions,\n ): Promise<\n PromptRunResult & {\n /** Resulting prompt run */\n result: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n }\n > {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n if (\n options.promptRunMessages[options.promptRunMessages.length - 1].role !==\n ChatCompletionRole.Assistant\n ) {\n throw new Error(\n `promptRunMessages[${\n options.promptRunMessages.length - 1\n }].role is expected to be = ${ChatCompletionRole.Assistant}`,\n );\n }\n const response =\n options.promptRunMessages[options.promptRunMessages.length - 1].content;\n\n let parsed: t.TypeOf<TPrompts[TPromptName]['outputCodec']>;\n try {\n // Parse the response\n parsed = this.parseAiResponse(promptName, response);\n } catch (err) {\n await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n error: err.message,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n throw err;\n }\n\n // report successful run\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Resolved,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n result: parsed,\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n\n /**\n * Report an error for a particular prompt\n *\n * @param promptName - Prompt to parse\n * @param options - Options for reporting\n * @returns Parsed content\n */\n async reportPromptRunError<TPromptName extends TPromptNames>(\n promptName: TPromptName,\n {\n largeLanguageModel,\n ...options\n }: Requirize<ReportPromptRunOptions, 'error'>,\n ): Promise<PromptRunResult> {\n // Determine if prompts need to be fetched\n if (\n // never been fetched\n !this.lastUpdatedAt ||\n // fetch every run\n this.cacheDuration === 0 ||\n // If cache duration met\n (this.cacheDuration &&\n Date.now() - this.lastUpdatedAt.getTime() > this.cacheDuration)\n ) {\n await this.fetchPromptsAndMetadata();\n }\n\n const name =\n options.name ||\n `@transcend-io/cli-prompt-run-${new Date().toISOString()}`;\n\n if (!this.promptContentMap) {\n throw new Error('Expected this.promptContentMap to be defined');\n }\n // Look up prompt info\n const promptInput = this.promptContentMap[promptName];\n if (!promptInput) {\n throw new Error(`Expected this.prompts[${promptName}] to be defined`);\n }\n\n // Ensure the first message in `promptRunMessages` is of type=system\n if (options.promptRunMessages.length === 0) {\n throw new Error('promptRunMessages is expected to have length > 0');\n }\n if (options.promptRunMessages[0].role !== ChatCompletionRole.System) {\n throw new Error(\n `promptRunMessages[0].role is expected to be = ${ChatCompletionRole.System}`,\n );\n }\n\n const promptRunId = await reportPromptRun(this.graphQLClient, {\n productArea: PromptRunProductArea.PromptManager,\n ...options,\n name,\n status: QueueStatus.Error,\n ...(typeof largeLanguageModel === 'string'\n ? { largeLanguageModelId: largeLanguageModel }\n : {\n largeLanguageModelName: largeLanguageModel.name,\n largeLanguageModelClient: largeLanguageModel.client,\n }),\n promptId: promptInput.id,\n promptRunMessages: options.promptRunMessages.map((message, ind) => ({\n ...message,\n ...(ind === 0 ? { template: promptInput.content } : {}),\n })),\n });\n\n return {\n promptRunId,\n promptRunUrl: `https://app.transcend.io/prompts/runs/${promptRunId}`,\n };\n }\n}\n/* eslint-enable max-lines */\n","import { GraphQLClient } from 'graphql-request';\nimport { LargeLanguageModelClient } from '@transcend-io/privacy-types';\nimport { LARGE_LANGUAGE_MODELS } from './gqls';\nimport { makeGraphQLRequest } from './makeGraphQLRequest';\n\nexport interface LargeLanguageModel {\n /** ID of prompts */\n id: string;\n /** The name of the large language model. */\n name: string;\n /** The content of the prompt template. */\n client: LargeLanguageModelClient;\n /** Whether hosted by Transcend or not */\n isTranscendHosted: boolean;\n}\n\nconst PAGE_SIZE = 20;\n\n/**\n * Fetch all LargeLanguageModels in the organization\n *\n * @param client - GraphQL client\n * @returns All LargeLanguageModels in the organization\n */\nexport async function fetchAllLargeLanguageModels(\n client: GraphQLClient,\n): Promise<LargeLanguageModel[]> {\n const largeLanguageModels: LargeLanguageModel[] = [];\n let offset = 0;\n\n // Whether to continue looping\n let shouldContinue = false;\n do {\n const {\n largeLanguageModels: { nodes },\n } = await makeGraphQLRequest<{\n /** LargeLanguageModels */\n largeLanguageModels: {\n /** List */\n nodes: LargeLanguageModel[];\n };\n }>(client, LARGE_LANGUAGE_MODELS, {\n first: PAGE_SIZE,\n offset,\n });\n largeLanguageModels.push(...nodes);\n offset += PAGE_SIZE;\n shouldContinue = nodes.length === PAGE_SIZE;\n } while (shouldContinue);\n\n return largeLanguageModels.sort((a, b) => a.name.localeCompare(b.name));\n}\n","import { difference } from 'lodash-es';\nimport fastGlob from 'fast-glob';\nimport { execSync } from 'child_process';\n\n/**\n * Function thats gets the git files that have changed\n * and returns the code\n *\n * @param options - Options\n * @returns Changes files and diffs\n */\nexport function getGitFilesThatChanged({\n baseBranch,\n rootDirectory,\n githubRepo,\n excludedGlob = [],\n fileBlockList = [],\n}: {\n /** Base branch */\n baseBranch: string;\n /** Github repo name */\n githubRepo: string;\n /** Root directory */\n rootDirectory: string;\n /** A glob that excludes files */\n excludedGlob?: string[];\n /** Block list of files to not process */\n fileBlockList?: string[];\n}): {\n /** The list of files that changed */\n changedFiles: string[];\n /** Github repo name */\n repoName: string;\n /** Current commit */\n commit: string;\n /** File diffs */\n fileDiffs: { [k in string]: string };\n} {\n // Pull base branch\n execSync(`git fetch origin ${baseBranch}`);\n\n // Latest commit on base branch. If we are on the base branch, we take the prior commit\n const latestBasedCommit = execSync(\n `git ls-remote ${githubRepo} \"refs/heads/${baseBranch}\" | cut -f 1`,\n { encoding: 'utf-8' },\n ).split('\\n')[0];\n\n // This commit\n const latestThisCommit = execSync('git rev-parse HEAD', {\n encoding: 'utf-8',\n }).split('\\n')[0];\n\n // Ensure commits are present\n if (!latestBasedCommit || !latestThisCommit) {\n throw new Error('FAILED TO FIND COMMIT RANGE');\n }\n\n // Get the diff between the given branch and base branch\n const diff = execSync(\n `git fetch && git diff --name-only \"${\n baseBranch || latestBasedCommit\n }...${latestThisCommit}\" -- ${rootDirectory}`,\n { encoding: 'utf-8' },\n );\n\n // Filter out block list\n const changedFiles = difference(\n diff.split('\\n').filter((f) => f),\n fileBlockList,\n );\n\n // Filter out globs\n const filteredChanges =\n excludedGlob.length > 0\n ? fastGlob.sync(changedFiles, { ignore: excludedGlob })\n : changedFiles;\n\n // Get the contents of only the changed files\n const fileDiffs: { [k in string]: string } = {};\n filteredChanges.forEach((file) => {\n const contents = execSync(`git show ${latestThisCommit}:${file}`, {\n encoding: 'utf-8',\n });\n fileDiffs[file] = contents;\n });\n\n // Pull the github repo name\n const repoName = githubRepo.split('/').pop()!.split('.')[0];\n\n return {\n changedFiles,\n fileDiffs,\n repoName,\n commit: latestThisCommit,\n };\n}\n"]}
|