All files / kernel-agents/src task.ts

90% Statements 9/10
100% Branches 3/3
75% Functions 3/4
90% Lines 9/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                    2x 3x   2x 4x           5x   5x                                             4x           4x 4x                        
import { makeCounter } from '@metamask/kernel-utils';
 
import type { Task, CapabilityRecord } from './types.ts';
 
/**
 * A trivial judgment that always returns true.
 *
 * @param _result - The result to judge.
 * @returns True.
 */
export const defaultJudgment = <Result>(_result: unknown): _result is Result =>
  true;
 
const formatTaskId = (count: number): string =>
  `t${count.toString().padStart(3, '0')}`;
 
/**
 * Manages the creation and tracking of tasks for agents.
 */
export class TaskManager<ResultBase = unknown> {
  readonly #tasks: Task<ResultBase>[] = [];
 
  readonly #taskCounter = makeCounter();
 
  /**
   * Specify a task.
   *
   * @param args - The arguments to specify the task.
   * @param args.intent - A specification of the task to be performed, or a query to be answered.
   * @param args.judgment - The function to determine if the task is complete.
   * @param args.capabilities - The capabilities available to the task - revocable.
   * @param args.knowledge - The knowledge available to the task - irrevocable.
   * @returns A task.
   */
  makeTask<Result extends ResultBase = ResultBase>({
    intent,
    judgment = defaultJudgment<Result>,
    capabilities = {},
    knowledge = {},
  }: {
    intent: string;
    judgment?: (result: unknown) => result is Result;
    capabilities?: CapabilityRecord;
    knowledge?: Record<string, unknown>;
  }): Task<Result> {
    const task: Task<Result> = {
      id: formatTaskId(this.#taskCounter()),
      objective: { intent, judgment },
      context: { knowledge, capabilities },
      attempts: [],
    };
    this.#tasks.push(task);
    return task;
  }
 
  /**
   * Get the tasks managed by the task manager.
   *
   * @returns The tasks.
   */
  get tasks(): Task<ResultBase>[] {
    return [...this.#tasks];
  }
}