export type JsonValue = string | number | boolean | null | JsonValue[] | { [name: string]: JsonValue };

export interface ArtifactReceiptInput {
  bytes: Uint8Array;
  sizeBytes: number;
  sha256: string;
}

/** Compare the exact byte count and lowercase SHA-256 digest of the supplied view. */
export function verifyArtifactReceipt(input: ArtifactReceiptInput): boolean;

export interface ToolContext {
  readonly taskId: string;
  readonly tool: string;
}

/** A trusted in-process handler. Return plain JSON data or a promise for that data. */
export type ToolHandler<Input = unknown> = {
  handle(input: Input, context: ToolContext): unknown;
}['handle'];

type ToolRegistry = Record<string, ToolHandler>;

export interface ToolMetadata {
  description: string;
  /** Describes the expected input. The handler validates inputs at execution time. */
  inputSchema?: { [keyword: string]: JsonValue };
}

export interface ListedTool extends Partial<ToolMetadata> {
  name: string;
}

export interface LocalAgentOptions<Tools extends ToolRegistry = ToolRegistry> {
  tools: Tools;
  toolMetadata?: Partial<Record<keyof Tools, ToolMetadata>>;
  allowedTools: readonly string[];
  blockedTools?: readonly string[];
  /** Optional local profile identifier recorded in policy receipts. */
  profileId?: string;
  /** Number of terminal records retained in completion order. Defaults to 100. */
  historyLimit?: number;
}

interface TaskIdentity {
  id: string;
  tool: string;
}

export type TaskRecord = TaskIdentity & (
  | { status: 'running'; result: null; error: null }
  | { status: 'completed'; result: JsonValue; error: null }
  | { status: 'blocked'; result: null; error: { code: 'tool_blocked' } }
  | { status: 'failed'; result: null; error: { code: 'tool_failed' | 'invalid_result' } }
);

export type FinishedTask = Exclude<TaskRecord, { status: 'running' }>;

export type ToolPolicyDecision =
  | { readonly decision: 'allow'; readonly reason: 'in_allowlist' }
  | { readonly decision: 'deny'; readonly reason: 'explicitly_blocked' | 'not_in_allowlist' | 'not_registered' };

export type TaskReceipt = TaskRecord & {
  readonly policy: ToolPolicyDecision & {
    /** Local profile identifier supplied by the caller, if any. */
    readonly profile: string | null;
    /** SHA-256 of the sorted, deduplicated allowed and blocked tool lists. */
    readonly rulesSha256: string;
  };
};

export interface TaskRun {
  readonly id: string;
  readonly policy: ToolPolicyDecision;
  readonly done: Promise<FinishedTask>;
}

export type ModelMessage =
  | { role: 'user'; text: string }
  | { role: 'tool'; taskId: string; name: string; input: JsonValue; result: JsonValue };

export interface ModelTurn {
  messages: ModelMessage[];
  tools: ListedTool[];
}

export type ModelDecision =
  | { type: 'final'; text: string }
  | { type: 'tool_call'; name: string; input: JsonValue };

/** Return one tool request or a final answer for the current conversation. */
export type ModelAdapter = (turn: ModelTurn) => ModelDecision | Promise<ModelDecision>;

export interface ModelRunOptions {
  /** Maximum executed tool calls. Defaults to 4, accepts integers from 0 to 16. */
  maxToolCalls?: number;
}

export type FinishedTaskReceipt = Exclude<TaskReceipt, { status: 'running' }>;

export type ModelRunResult = { receipts: FinishedTaskReceipt[] } & (
  | { status: 'completed'; text: string }
  | { status: 'blocked'; error: { code: 'tool_blocked' } }
  | { status: 'failed'; error: { code: 'tool_failed' | 'invalid_result' |
        'model_failed' | 'invalid_model_response' | 'tool_limit_reached' } }
);

type ToolInput<Tools extends ToolRegistry, Name extends string> =
  Name extends keyof Tools ? Parameters<Tools[Name]> extends [] ? unknown : Parameters<Tools[Name]>[0] : unknown;

export class LocalAgent<Tools extends ToolRegistry = ToolRegistry> {
  constructor(options: LocalAgentOptions<Tools>);
  /** Detached catalog of registered tools permitted by the agent's policy. */
  listTools(): ListedTool[];
  start<Name extends string>(tool: Name, input: ToolInput<Tools, Name>): TaskRun;
  run<Name extends string>(tool: Name, input: ToolInput<Tools, Name>): Promise<FinishedTask>;
  /** Run a caller-supplied model with this agent's tool policy and return per-call receipts. */
  runWithModel(prompt: string, model: ModelAdapter, options?: ModelRunOptions): Promise<ModelRunResult>;
  get(taskId: string): TaskRecord | undefined;
  /** Detached snapshot for a running or retained task on this LocalAgent instance. */
  getReceipt(taskId: string): TaskReceipt | undefined;
}
