Skip to content

Commit

Permalink
0.0.4 - fix a bunch of shell junk
Browse files Browse the repository at this point in the history
  • Loading branch information
lalalune committed Feb 14, 2024
1 parent d6c44a0 commit dbd35c5
Show file tree
Hide file tree
Showing 5 changed files with 293 additions and 130 deletions.
15 changes: 6 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "bgent",
"version": "0.0.3",
"version": "0.0.4",
"private": false,
"description": "bgent. because agent was taken.",
"type": "module",
Expand All @@ -13,19 +13,16 @@
"jsnext:main": "dist/index.esm.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rollup -c",
"build": "rollup -c && npm run build:types",
"build:types": "tsc --declaration --emitDeclarationOnly --declarationDir dist",
"lint": "eslint --ext .ts --ext .js . --fix",
"shell": "node --no-warnings scripts/shell.mjs",
"dev": "wrangler dev",
"shell:dev": "node --no-warnings scripts/shell.mjs --dev",
"concat": "node ./scripts/concat.mjs",
"dev": "wrangler dev --log-level error & npm run shell:dev",
"shell:cloud": "node --no-warnings scripts/shell.mjs",
"test": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest",
"test:dev": "jest --watchAll",
"test:coverage": "jest --coverage",
"dev:logs": "wrangler dev",
"deploy": "wrangler deploy",
"start": "wrangler dev"
"reset-profile": "rm ~/.cjrc",
"deploy": "wrangler deploy"
},
"bin": {
"bgent": "./scripts/shell.mjs"
Expand Down
123 changes: 84 additions & 39 deletions scripts/shell.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const getSupabase = (access_token) => {
return supabase
}

export const getMe = async (session) => {
const getMe = async (session) => {
const {
data: { user },
error
Expand All @@ -67,18 +67,99 @@ export const getMe = async (session) => {
}
}

// Main application logic
// Main application logic
const checkAndUpdateAccount = async (user) => {
console.log('checkAndUpdateAccount', user)
const supabase = getSupabase(user.access_token)
const response = await supabase
.from('accounts')
.select('*')
.eq('id', user.id)
console.log('response', response)
let { data: accounts, error: accountsError } = response
if (accountsError) {
console.error(chalk.red(`Failed to fetch accounts: ${accountsError.message}`))
return
}

if (accounts.length === 0) {
const { name } = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Enter your name:',
validate: (input) => input.trim() !== '' || 'Name cannot be empty.'
}
])

const { error: insertError } = await supabase
.from('accounts')
.insert([{ id: user.id, name, email: user.email, register_complete: true }])

if (insertError) {
console.error(chalk.red(`Failed to create account: ${insertError.message}`))
} else {
console.log(chalk.green('Account created successfully.'))
}
}
}

async function loginUser(retry = false) {
if (retry) {
console.log(chalk.yellow('Incorrect email or password. Please try again.'))
}

const credentials = await inquirer.prompt([
{
type: 'input',
name: 'email',
message: 'Enter your email:',
validate: (input) => input.includes('@') || 'Please enter a valid email address.'
},
{
type: 'password',
name: 'password',
message: 'Enter your password:',
mask: '*'
}
])

const supabase = getSupabase()

const {data, error} = await supabase.auth.signInWithPassword({
email: credentials.email,
password: credentials.password
})

console.log('response.data', data)

const { session } = data;

if (error) {
await loginUser(true) // Recursively call loginUser to retry
} else {
console.log('session', session)
fs.writeFileSync(configFile, JSON.stringify({ session }))
console.log(chalk.green('Login successful! Configuration saved.'))
await startApplication() // Start the application after login
}
}


async function startApplication () {
console.log(chalk.green('Starting application...'))

// Assuming session information is stored in the .cjrc file
const userData = JSON.parse(fs.readFileSync(configFile).toString())
const session = userData?.session
await checkAndUpdateAccount(session.user) // Check and update account after login

const supabase = getSupabase(session?.access_token)


const userId = session.user?.id

console.log('userId', userId)

// get all entries from 'rooms' where there are two particants (entries in the partipants table) where the user and agent ids match the participant user_id field
// this will require a join between the rooms and participants table
const { data, error } = await supabase
Expand Down Expand Up @@ -230,42 +311,6 @@ async function handleUserInteraction () {
}
}

// Function to log in the user
async function loginUser () {
const credentials = await inquirer.prompt([
{
type: 'input',
name: 'email',
message: 'Enter your email:',
validate: (input) =>
input.includes('@') ? true : 'Please enter a valid email address.'
},
{
type: 'password',
name: 'password',
message: 'Enter your password:',
mask: '*'
}
])

const supabase = getSupabase()

try {
const { data, error } = await supabase.auth.signInWithPassword({
email: credentials.email,
password: credentials.password
})

if (error) throw error

fs.writeFileSync(configFile, JSON.stringify({ session: data.session }))
console.log(chalk.green('Login successful! Configuration saved.'))
await startApplication() // Start the application after login
} catch (error) {
console.error(chalk.red(`Login failed: ${error.message}`))
}
}

// Function to sign up the user
async function signupUser () {
const credentials = await inquirer.prompt([
Expand Down
103 changes: 99 additions & 4 deletions src/lib/actions/__test__/wait.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,100 @@
describe("Wait", () => {
// 1. prepare test before all and after all
// 2. Load 3 conversations, 2 where the agent should continue, and 1 where the agent should not continue
// 3. Run tests
import { type User } from "@supabase/supabase-js";
import { type UUID } from "crypto";
import dotenv from "dotenv";
import { getCachedEmbedding, writeCachedEmbedding } from "../../../test/cache";
import { createRuntime } from "../../../test/createRuntime";
import { GetTellMeAboutYourselfConversation1 } from "../../../test/data";
import { getRelationship } from "../../relationships";
import { type BgentRuntime } from "../../runtime";
import { type Message } from "../../types";
import action from "../wait"; // Import the wait action

dotenv.config();

const zeroUuid = "00000000-0000-0000-0000-000000000000";

describe("Wait Action Behavior", () => {
let user: User | null;
let runtime: BgentRuntime;
let room_id: UUID | null;

afterAll(async () => {
await cleanup();
});

beforeAll(async () => {
const setup = await createRuntime(process.env as Record<string, string>);
user = setup.user;
runtime = setup.runtime;

const data = await getRelationship({
supabase: runtime.supabase,
userA: user?.id as UUID,
userB: zeroUuid,
});

room_id = data?.room_id;

await cleanup();
});

async function cleanup() {
await runtime.reflectionManager.removeAllMemoriesByUserIds([
user?.id as UUID,
zeroUuid,
]);
await runtime.messageManager.removeAllMemoriesByUserIds([
user?.id as UUID,
zeroUuid,
]);
}

async function populateMemories(
conversations: Array<
(user_id: string) => Array<{ user_id: string; content: string }>
>,
) {
for (const conversation of conversations) {
for (const c of conversation(user?.id as UUID)) {
const existingEmbedding = getCachedEmbedding(c.content);
const bakedMemory = await runtime.messageManager.addEmbeddingToMemory({
user_id: c.user_id as UUID,
user_ids: [user?.id as UUID, zeroUuid],
content: {
content: c.content,
},
room_id: room_id as UUID,
embedding: existingEmbedding,
});
await runtime.messageManager.createMemory(bakedMemory);
if (!existingEmbedding) {
writeCachedEmbedding(c.content, bakedMemory.embedding as number[]);
await new Promise((resolve) => setTimeout(resolve, 200));
}
}
}
}

test("Test wait action behavior", async () => {
const message: Message = {
senderId: zeroUuid as UUID,
agentId: zeroUuid,
userIds: [user?.id as UUID, zeroUuid],
content: {
content: "Please wait a moment, I need to think about this...",
action: "wait",
},
room_id: room_id as UUID,
};

const handler = action.handler!;

await populateMemories([GetTellMeAboutYourselfConversation1]);

const result = (await handler(runtime, message)) as string[];
// Expectation depends on the implementation of the wait action.
// For instance, it might be that there's no immediate output,
// or the output indicates waiting, so adjust the expectation accordingly.
expect(result).toEqual(expect.anything()); // Update this line based on the expected behavior of the wait action
}, 60000);
});
Loading

0 comments on commit dbd35c5

Please sign in to comment.