Heylock SDK
Integrate an AI agent with minimal setup. This guide walks you through installation, initialization, core methods, and lifecycle callbacks.
Install
Add the package to your project:
npm install heylock
Initialize
Create an instance with your agent key.
1import Heylock from 'heylock';
2
3const agent = new Heylock(process.env.HEYLOCK_AGENT_KEY, {
4 useStorage: false, // ignored in pure Node
5 useMessageHistory: true, // include prior messages by default
6 suppressWarnings: false, // whether to suppress warnings
7 agentId: "MAIN" // unique identifier for the agent's storage entry
8});
9
10agent.onInitialized(success => {
11 if (!success) return console.error('Failed to initialize');
12
13 console.log('Ready');
14});
Send a message
Use message() for single responses.
1const reply = await agent.message('Hello there');
2
3console.log('Agent:', reply);
By default, messages are appended to internal history when saveToMessageHistory is true.
Stream a response
Use messageStream() to incrementally consume tokens as an async generator.
1let full = '';
2
3for await (const chunk of agent.messageStream('Explain rate limiting simply')) {
4 full += chunk;
5
6 process.stdout.write(chunk);
7}
8
9console.log('\nFull:', full);
Context
Add session signals (user actions, page state) as context entries. Each entry has a timestamp.
getContextString() produces a compact narrative you can use for the API or internal logging.
1agent.addContextEntry('User opened pricing modal');
2agent.addContextEntry('User hovered over feature tooltip');
3
4console.log(agent.getContextString());
5
6// Output: User opened pricing modal now. User hovered over feature tooltip now.
See Context.
Message history
The SDK maintains an ordered array of prior turns (messageHistory).
1agent.addMessage('Hi', 'user'); // [{ role: 'user', content: 'Hi' }]
2
3agent.addMessage('Hello! How can I help?', 'assistant'); // [{ role: 'user', content: 'Hi' }, { role: 'assistant', content: 'Hello! How can I help?' }]
4
5console.log(agent.messageHistory.length); // 2
6
7agent.modifyMessage(0, 'Hi there'); // [{ role: 'user', content: 'Hi there' }, { role: 'assistant', content: 'Hello! How can I help?' }]
8
9agent.removeMessage(1); // [{ role: 'user', content: 'Hi there' }]
10
11agent.setMessageHistory([]); // []
Use callbacks to react to changes (update UI, persist externally).
Rewrite text
Use rewrite() to transform content according to optional instructions and context. Returns only the rewritten string.
1const rewritten = await agent.rewrite('pls help me i cant sync');
2
3console.log(rewritten); // Please help me, I'm having trouble syncing.
Sort items
Use sort() to order an array with reasoning. Provide guidance via instructions. The response includes the sorted array and index mapping.
1const products = [
2 { name: 'Eco Bottle', price: 12 },
3 { name: 'Steel Bottle', price: 25 },
4 { name: 'Plastic Bottle', price: 3 }
5];
6
7const response = await agent.sort(products, 'Order by likelihood of purchase');
8
9console.log(response.array, response.indexes);
Engagement decision
Use shouldEngage() to decide whether to proactively message the visitor.
1const decision = await agent.shouldEngage('Engage only if user shows checkout friction');
2
3if (decision.warning) console.warn(decision.warning);
4
5if (decision.shouldEngage) {
6 await agent.addMessage('Hello! Need help finishing checkout?', 'assistant');
7}
Balance
After initialization, read balanceRemaining or call fetchBalanceRemaining() to refresh the value from the server.
1await agent.fetchBalanceRemaining(); // fetch from the server
2
3console.log(agent.balanceRemaining); // e.g. 32.58
For more details, see API docs: Limits.
Callbacks
Register handlers for initialization, message history, and context changes.
1const unsubscribeInitialization = agent.onInitialized(success => console.log('Initialization:', success));
2const unsubscribeHistory = agent.onMessageHistoryChange(history => console.log('History size:', history.length));
3const unsubscribeContext = agent.onContextChange(context => console.log('Context entries:', context.length));
4
5// Later
6unsubscribeHistory();
Each returns an unsubscribe function. Catch errors in your handlers to avoid silent failures.
Error handling
SDK methods throw on validation or network errors. Wrap calls in try/catch. Examine message text or map errors to user-friendly states.
1try {
2 const reply = await agent.message('Explain concurrency');
3
4 console.log(reply);
5} catch (error) {
6 console.error('Message failed:', error);
7}
See SDK Errors and API Errors.
Types
TypeScript users get rich types via the included declaration file (types.d.ts). Import normally; no extra config.
See Types.