Tools
A tool is a function that HADAL can call. HADAL gets the name, the description, and the parameters of each tool with each request, and calls a tool when its task needs it.
Define a tool
Section titled “Define a tool”Use defineTool from @earendil-works/pi-durable, and give the tool to your extension:
const wordCount = defineTool({ name: "my_word_count", description: "Count the words in a text.", parameters: obj({ text: str({ description: "The text to count" }) }), replay: "safe", execute: async (args) => ({ output: [{ type: "text" as const, text: `${countWords(args.text)} words` }], }),});
// It returns `output`, so it needs version 2 of the extension API: HADAL 0.18 says so, and does not load it.export const pocketApi = 2;
export default function createMyWords() { return defineExtension({ name: "my-words", tools: [wordCount] });}namemust be different from the name of each other tool (Names). Use a prefix of your own.descriptionandparametersgo to the model with each request. Keep them short and exact.deferred: truekeeps a tool out of the requests until HADAL loads it withtool_search, which only the Tool search module offers: while it is off, HADAL cannot load the tool. Use it for a tool that few conversations need, or for a large set of tools.test/prompt-budget.test.tskeeps HADAL’s own prompt and tools under 14,000 characters (about 5,000 tokens) in a plain session, a guard against growth by accident: a rule that makes the work better is worth its tokens.parametersis a JSON Schema object. Build it with the builders of@earendil-works/pi-schema:obj,str,num,int,bool,arr,union, andoptfor a property that can be left out.objmakes a closed object (additionalProperties: false);obj(properties, { open: true })lets other properties through. Pi Durable checks the arguments against the schema beforeexecuteruns. Since HADAL 1.5 (HADAL 0.28.0), pi-schema does the check, and the model gets its messages, such as- path: missing. A drop-in written before can keep TypeBox’sTypefrom@earendil-works/pi-ai(API versions).execute(args, api, context)does the work.
Return a result
Section titled “Return a result”- Return
{ output: [{ type: "text", text }] }. The model reads the text. - Pi Durable 1.2 renamed the result field
contenttooutput. HADAL still readscontentfrom whatexecuteof a drop-in’s tool returns, but new code must useoutput. A hook (afterTool) or a wrap (wrapTool) that reads or returns a result must useoutputtoo. A module that returnsoutputexportspocketApi = 2(API versions): HADAL 0.18 then refuses it with a clear message. - To give the model an error, throw an
Error. The model gets its message as an error result. api.output(text)streams output while the tool runs. Whenexecutereturns nooutput, this output becomes the result.
Restarts and replays
Section titled “Restarts and replays”A restart of the server can stop a tool call while it runs. Then the call is replayed: it runs again, or the model gets “interrupted”.
- Set
replay: "safe"only when it does no harm to run the call two times. For example, the tool only reads, or it does an action with a key, so that a second run finds the result of the first. - Without
replay: "safe", the tool is unsafe to replay. A call that a restart stops comes back to the model as interrupted, and does not run again. This is the default. api.memo(name, context)reads a value that is kept with this call.api.memo(name, value, context)stores it. A replay after a restart finds the value. Use a memo for work that must not occur two times, for example a message that you send.api.conversationId,api.taskId, andapi.callIdidentify the call. The key${api.taskId}:${api.callId}stays the same when the call runs again.
Plan mode
Section titled “Plan mode”annotations: { readOnlyHint: true }, as in the terminal app’s tool definitions, says that the tool does not change files or other state. Plan mode lets such a tool run. HADAL does not check this: it is your promise. A tool that only changes the conversation, such as context management, can also use it. Plan mode ignores the hint on a built-in tool, so a wrap cannot let a built-in tool run in plan mode.
Pi Durable’s type for defineTool does not have annotations yet. TypeScript reports it as an unknown property, but the module loads and works, because Node does not check types. To keep the type checker quiet, add it after defineTool:
const lookup = Object.assign(defineTool({ … }), { annotations: { readOnlyHint: true } });Files, documents, and the session
Section titled “Files, documents, and the session”api.envgives the files and the shell of the call: the session’s folder, or an SSH host’s when the call named one. Use it, notnode:fsorhost.envFor, for anything about the file a call names, so the tool works on a host too.(await api.agent(context)).cwdis the folder.api.snapshot(Doc, api.conversationId, context)reads a document, for example one of HADAL’s insrc/server/docs.ts.
Call a model
Section titled “Call a model”A tool can ask a model itself, for example to choose each step of a browser run. Use the session’s model, through Pi Durable:
if (host.heldBack(api.conversationId) !== undefined) { throw new Error("A spend limit holds this session back.");}
const chosen = (await api.agent(context)).model;const model = chosen && api.models.getModel(chosen.provider, chosen.modelId);
if (model === undefined) { throw new Error("This session has no model.");}
const reply = await api.models.completeSimple(model, { messages: [ { role: "user", content: [{ type: "text", text: question }], timestamp: Date.now() }, ],});- The provider’s request limits apply, as to HADAL’s own requests.
- The session’s spend does not count this reply by itself. Add
reply.usageto Pi Durable’sUsageDocfor the session, in acommit, as HADAL’s titles do (titles.ts). Checkhost.heldBackbefore each call, so a spend limit stops your tool too. - Say in your tool’s result what the model decided, so HADAL and the people can follow it.
See also
Section titled “See also”- Your first extension makes a tool, step by step.
- examples/clock.ts is a tool that reads a document of its own.
- How tool calls show tells how to show your tool’s calls in words.
- Pi Durable’s README (
node_modules/@earendil-works/pi-durable/README.md) tells all about tools.
These pages describe HADAL 0.29.0. Your copy has the pages of its own version in its docs/ folder.