import type { NativeMemoryViewBinding } from "./native-memory-view-provider.js"; import type { HostMemoryBindingV1, MemoryCapabilityV1, MemorySearchResultV1 } from "../memory/memoryCapability.js"; import type { EvidenceEvent } from "./evidence.js"; import type { DesktopVerificationScope, DesktopVerificationReceipt } from "./rapid-computer-use/desktop-verification.js"; import type { PdfNativeTables } from "./tools/pdf-native-tables.js"; import type { FeatureWorkflowOperationBinding, FeatureWorkflowInputArtifact, FeatureWorkflowChildReceipt, FeatureWorkflowCard } from "../schemas/feature-workflow.js"; /** * What was actually materialized by a successful tool call. `success` says * the tool completed; this record says whether the returned bytes are a * canonical artifact or only a recoverable prefix/head-tail capture. */ export interface ArtifactMaterialization { schema: "omnius.artifact-materialization.v1"; status: "canonical" | "partial"; kind: "file_read" | "tool_output" | "branch_extract"; /** Path of the source artifact when the producing tool knows it. */ sourcePath?: string; /** Full-source hash for canonical file reads. */ sourceHash?: string; /** Selected source range, inclusive and 1-based. */ sourceRange?: { startLine: number; endLine: number | null; }; /** Bytes and lines actually observed before any output cap. */ observedBytes: number; observedLines: number; /** Present only when output was capped or capture stopped early. */ truncation?: { reason: "output_cap" | "capture_cap" | "line_cap"; capBytes?: number; savedPaths?: string[]; narrowingHint: string; }; } /** * Trusted execution facts emitted by a local command runner. This is * deliberately separate from `output`: display text can be truncated, * decorated, or quoted by another tool, while completion decisions need the * command identity and process outcome that the runner actually observed. */ export interface CommandEvidenceReceipt { schema: "omnius.command-evidence-receipt.v1"; command: string; /** Stable command form for evidence grouping; never inferred from output. */ canonicalCommand: string; cwd: string; /** * Effective outcome used by Omnius after its narrowly-scoped executor * policies (for example an exact trailing `EXIT=$?` reporter). The raw * runner outcome and the primary-command outcome remain separately * inspectable below; consumers must not infer either from display output. */ exitCode?: number | null; /** The command segment whose status this receipt is asserting. */ primaryCommand?: string; /** Status of `primaryCommand`, distinct from wrapper/process status. */ primaryExitCode?: number | null; /** How `primaryExitCode` was obtained. */ primaryExitProvenance?: "runner_process" | "trailing_exit_reporter"; /** Actual status returned by the local command runner before policy logic. */ runnerExitCode?: number | null; pipefail: boolean; timedOut: boolean; /** Actual process-local shell run, never reconstructed from command/output. */ shellRunId?: string; timeoutMs?: number | null; cancelled?: boolean; signal?: string | null; startedAtIso: string; finishedAtIso: string; /** Executor-classified negative search result, never parsed from stdout. */ observation?: { kind: "search_no_match"; }; /** Optional immutable pointer to a spilled full command transcript. */ outputRef?: string; /** Exact explicit task artifacts observed by this local command, when the * controller can attest the relationship. This is never inferred from * display output and never grants verification authority by itself. */ observedPaths?: string[]; artifactHashes?: Array<{ path: string; sha256: string; }>; /** * Explicit Omnius verifier protocol observed in the command output. This is * a process result signal, not a replacement for the process exit code. */ declaredVerification?: { protocol: "OMNIUS_VERIFICATION_RESULT"; outcome: "pass" | "fail"; }; } /** * Evidence emitted by the native PDF reader. It is deliberately structured * so the agent loop can distinguish an observed negative query result from a * parser, capability, or OCR failure without reverse-engineering prose. */ export interface DocumentExtractionReceipt { schema: "omnius.document-extraction.v1"; kind: "pdf"; /** Stable SHA-256 of the source bytes; never infer identity from a path. */ documentHash: string; sourcePath: string; pageCount?: number; requestedPages: number[]; extractedPages: number[]; /** A page may combine native text with OCR for an image/table-only page. */ backend: "native_text" | "selective_ocr" | "mixed" | "none"; outcome: "text_extracted" | "query_not_found" /** A query miss where one or more selected pages/layers were not searched. */ | "query_inconclusive" | "visual_markdown_unavailable" | "visual_markdown_failed" | "ocr_required" | "dependency_unavailable" | "encrypted" | "malformed" | "not_found" | "invalid_request" | "timeout" | "ocr_failed"; retry: "never" | "after_capability_change" | "with_different_pages" | "with_query_or_visual_review"; nextAction: string; nativeCharacters: number; ocrCharacters: number; query?: string; queryMatchedPages?: number[]; /** Query coverage is explicit so a bounded OCR fallback cannot imply absence. */ queryCoverage?: { nativeSearchedPages: number[]; ocrCandidatePages: number[]; ocrSearchedPages: number[]; unsearchedPages: number[]; complete: boolean; }; truncated?: boolean; /** Pages whose text was extracted but omitted from model output by the character cap. */ outputOmittedPages?: number[]; cacheHit?: boolean; generatedArtifacts?: string[]; /** Literal native word geometry; column associations are explicitly advisory. */ nativeTables?: PdfNativeTables[]; /** Optional page-attributed visual Markdown stage; it never overwrites native/OCR evidence. */ visualMarkdown?: { backend: string; model?: string; promptRevision: string; pages: Array<{ page: number; renderedArtifact: string; renderHash: string; outcome: "transcribed" | "failed" | "truncated"; markdownHash?: string; error?: string; }>; }; pageStats: Array<{ page: number; source: "native_text" | "ocr" | "mixed" | "none"; characters: number; queryMatched?: boolean; nativeAttempted?: boolean; ocrAttempted?: boolean; ocrSucceeded?: boolean; ocrError?: string; }>; } /** * Explicit identity and isolation contract for a stateful tool runtime. * * Browser automation is particularly easy to misuse: Playwright and the * legacy Selenium helper can both be alive while holding different cookies, * pages, focus, and permissions. This receipt makes that boundary data, not * an easily-truncated sentence in a tool description. */ export interface ToolRuntimeSession { schema: "omnius.tool-runtime-session.v1"; runtime: string; state: "active" | "closed" | "unavailable"; /** Opaque runtime-owned identifier; omitted when the runtime is closed. */ sessionId?: string; persistentAcrossCalls: boolean; /** Runtimes whose page state, cookies, and permissions are NOT shared. */ isolatedFrom: string[]; /** True when this call intentionally started/restarted a runtime session. */ boundaryChanged?: boolean; nextAction?: string; } /** * Host-owned identity for tools whose durable state is scoped to one runner. * The host binds this once before execution. Model arguments cannot replace * it. `taskEpoch` is diagnostic identity; stores that are session-wide may * use only `sessionId`. */ export interface ToolExecutionScope { nativeMemoryViews?: NativeMemoryViewBinding; /** Host-only memory authority; model arguments cannot supply or widen it. */ memory?: HostMemoryBindingV1; sessionId: string; taskEpoch?: number; ownerId?: string; } export interface CorpusInputExposureConfirmation { schema: "omnius.corpus-input-exposure.v1"; executionScope: ToolExecutionScope; claimId: string; inputId: string; /** Local offsets into the exact input, not an inferred document range. */ inputCharStart: number; inputCharEnd: number; textSha256: string; /** Exact successful host request messages, not an echoed model token. */ requestSha256: string; } export interface CorpusPreparedInputRead { schema: "omnius.corpus-input-read.v1"; executionScope: ToolExecutionScope; corpusId: string; operationId?: string; claimId?: string; inputId: string; inputCharStart: number; inputCharEnd: number; textSha256: string; text: string; kind: "source_segment" | "derived_children"; /** Exact immutable page channel; OCR output is never labelled native text. */ sourceChannel?: string; /** Current host lease duration, used only for transport-time renewal. */ leaseMs?: number; } /** Per-invocation authority supplied by the host, never parsed from tool args. */ /** Host-issued opaque identity; only the issuing runner can recognize it. */ export interface AuxiliaryOperationBinding { readonly __auxiliaryOperationBinding?: never; } export interface ToolInvocationContext { /** Original host child-dispatch identity; preserve by reference through adapters. */ nativeChildInvocation?: Readonly; nativeOperationInvocation?: Readonly; /** Native FileWrite result correlation only; never supplied by model arguments. */ nativeFileWriteInvocation?: Readonly; /** Preserve this exact host identity while composing cell-local guards. JSON copies grant nothing. */ auxiliaryOperationBinding?: AuxiliaryOperationBinding; /** Current native work-mode permission fence, never model arguments. */ workModeFileGuard?: import("./work-mode-capability.js").WorkModeFileGuard; signal?: AbortSignal; /** Host-owned operation fence. Late work must check before publishing artifacts. */ assertCurrent?: () => void; /** Host-authored correlation for one actual process; never model arguments. */ shellRun?: import("./shell-runs.js").ShellRunInvocation; /** Current runner-owned task context for bounded UI policy requests. Never tool/page input. */ uiTaskContext?: { goal: string; runId: string; taskEpoch: number; assertCurrent: () => void; }; /** Host physical-window allocation for this exact returned read slice. * Applied before durable read progress; never supplied by model args. */ corpusReadAllocation?: { maxChars: number; contextWindowTokens: number; }; /** * Host-authored semantic identity for the exact external effect admitted by * the orchestrator. Tools may bind a provider receipt to this identity, but * command output and model arguments cannot create or replace it. */ objectiveEffectIntent?: ToolExternalEffectIntent; /** * Host-owned authority for classifying a structured local EACCES/EPERM as * an elevation candidate. Tool arguments and command output cannot create * this authority. The command must exactly match the admitted invocation. */ elevationAuthority?: { allowed: true; source: "local_admin" | "trusted_tool"; command: string; }; /** Trusted surface decision; remote/public surfaces always use `deny`. */ elevationPolicy?: { mode: "native" | "deny"; surface: "local_admin" | "telegram" | "background" | "api"; toolName: string; }; featureWorkflow?: { binding: FeatureWorkflowOperationBinding; inputArtifacts: FeatureWorkflowInputArtifact[]; card: FeatureWorkflowCard; outputSlotIds: string[]; allowedToolNames: string[]; parentToolProfile?: { name?: string; allow?: string[]; deny?: string[]; }; }; } export type ToolObjectiveEvidenceKind = "visible_response" | "observation" | "mutation" | "verification" | "delivery" | "external_effect" | "provider_registration" | "transport" | "authenticated_session" | "human_input"; export interface ToolExternalEffectIntent { effectKind: string; semanticTarget: string; idempotencyKey: string; criterionIds: string[]; } export interface ToolExternalEffectReceipt { schema: "omnius.external-effect-receipt.v1"; effectKind: string; semanticTarget: string; idempotencyKey: string; effectState: "pending" | "applied" | "absent" | "unknown"; artifactRevision?: string; evidenceId: string; criterionIds: string[]; evidenceKinds?: ToolObjectiveEvidenceKind[]; destination?: { url: string; provider: string; }; } export interface ToolVerificationReceipt { schema: "omnius.verification-receipt.v1"; evidenceId: string; criterionId: string; artifactEvidenceId: string; artifactRevision?: string; verifierMethod: string; outcome: "passed" | "artifact_failed" | "verifier_invalid" | "downstream_auth_required" | "inconclusive"; evidenceIds: string[]; evidenceKinds?: ToolObjectiveEvidenceKind[]; } /** Exact accepted child response and the host receipt that owns its bytes. */ export interface FeatureWorkflowChildOutput { receipt: FeatureWorkflowChildReceipt; reportText: string; } /** Host-issued monotonic private work cursor; preparation, never source/delivery evidence. */ export interface DurableToolWorkProgress { /** Fixed host producer for the separate Telegram acquisition database. Never a job/model ID. */ producerId?: "telegram_native_manifest" | "telegram_export_review" | "telegram_source_review"; /** Cold SQL revalidation admits one retry; never a progress/result credit. */ intentOnly?: true; schema: "omnius.durable-tool-work-progress.v1"; executionScope: ToolExecutionScope; workId: string; /** Zero is admission-only for a genuine pending job before its first progress event. */ sequence: number; stateSha256: string; pending: boolean; } export interface Tool { name: string; aliases?: string[]; description: string; /** * Bounded, model-facing operating contract for tools whose correct use * cannot be preserved by truncating the first sentence of `description`. */ modelFacingSummary?: string; /** * Optional compact schema exposed to the model. Runtime validation and * execution continue to use `parameters`; this only prevents a large, * well-known tool from being evicted by the model-facing schema budget. */ modelFacingParameters?: Record; parameters: Record; /** Host capability: request invocation-scoped cancellation even outside a workflow. */ acceptsInvocationContext?: boolean; /** This tool validates and settles its own explicit deadline, including null. */ ownsInvocationDeadline?: boolean; execute(args: Record, context?: ToolInvocationContext): Promise; /** * Receive the names of every tool actually registered beside this one and * return the matching description, so guidance never names an absent tool. */ setAvailableTools?: (names: ReadonlySet) => string; /** Bind durable tool state to one host-owned runner identity. */ bindExecutionScope?: (scope: ToolExecutionScope) => void; /** Side-effect-free descriptors from the adapter's current lifecycle snapshot. */ getMemoryCapabilities?: () => MemoryCapabilityV1[]; /** Accept only this adapter's current host-issued result, never lookalike JSON. */ readIssuedMemoryResult?: (data: unknown) => MemorySearchResultV1 | undefined; readIssuedMemoryModelView?: (data: unknown) => string | undefined; setMemorySourceArchive?: (archive: import("../memory/memorySourceResolver.js").MemorySourceArchive) => void; setMemoryTopicPolicy?: (policy: { namespace: string; storeRef: string; scopeRef: string; topicPrefix: string; }) => void; /** Verify an actual returned read against private scoped immutable inputs. */ prepareCorpusInputExposure?: (data: unknown) => CorpusPreparedInputRead | Promise; /** Host-only successful model-transport exposure; never a callable tool. */ confirmCorpusInputExposure?: (input: CorpusInputExposureConfirmation) => void | Promise; /** Hold an already issued read claim while its current model request runs. */ renewCorpusInputExposure?: (input: { executionScope: ToolExecutionScope; claimId: string; }) => void | Promise; /** Host-only bounded exact numeric inputs for independent field review. */ reopenCorpusAggregateInputs?: (input: { executionScope: ToolExecutionScope; corpusId: string; operationId: string; field: string; pageSize?: number; cursor?: string; }) => unknown | Promise; /** Host-only reopen of an immutable actor-attested field ordering handle. */ reopenCorpusOrderedSources?: (input: { executionScope: ToolExecutionScope; corpusId: string; operationId: string; orderId: string; pageSize?: number; cursor?: string; }) => unknown | Promise; /** Host-only cold restart proof; never a model-callable action or progress event. */ prepareDurableWorkIntent?: (args: Record, context?: ToolInvocationContext) => Promise; /** Private SQL/cursor proof; callable only by the owning runtime, never the model. */ getDurableWorkProgress?: (args: Record, result?: { success: boolean; data?: unknown; }) => DurableToolWorkProgress | null; /** Host-only provenance seam; never reconstructed from model arguments or output. */ getSourceCorpusDatabaseIdentity?: () => { path: string; workingRoot: string; scopeId: string; } | null; /** * Best-effort cancellation hook for work that outlives a JavaScript promise. * ToolExecutor calls this when its deadline expires so persistent workers and * child processes are not left running after the client has received a * timeout response. */ cancel?: () => void | Promise; /** Explicit owner class for pause/stop accounting; never inferred from text. */ interruptionKind?: "model" | "read_tool" | "mutating_tool" | "delivery" | "browser" | "media" | "scheduled_action" | "background_cognition" | "sub_agent" | "process"; inputSchema?: unknown; /** Pure host-owned canonicalization before schema, permission and execution. * Return an argument object; reject conflicting or unsupported inputs. */ normalizeInput?: (args: Record) => Record; prompt?: (context: { modelTier: string; taskGoal: string; }) => Promise; executeStream?: (args: Record, context?: ToolInvocationContext) => AsyncGenerator; /** Optional value-level validation after schema parsing and before execute(). */ validateInput?: (args: Record, context?: { toolName: string; workingDir: string; }) => { result: true; } | { result: false; message: string; errorCode?: number; } | Promise<{ result: true; } | { result: false; message: string; errorCode?: number; }>; /** Parsed-input concurrency metadata, used by the orchestrator scheduler. */ isConcurrencySafe?: (args: Record) => boolean; isReadOnly?: (args: Record) => boolean; /** * The call can only observe: even if it fails it changed nothing. Completion evidence only; never * permission, concurrency, lease or history authority, which `isReadOnly` keeps. */ isObservationOnly?: (args: Record) => boolean; /** Private execution-time identity for encoding historical observations only. */ getHistoryObservationIdentity?: (args: Record, result: ToolResult) => string | null; /** Exact native command result custody, including failures; model JSON cannot issue it. */ getCommandExecutionObservation?: (args: Record, result: ToolResult) => unknown; readIssuedOperationObservation?: (args: Record, result: ToolResult) => unknown; returnedHttpSourceConsumer?: Readonly<{ selector: 'source_ref'; }>; /** Original native FileWrite result proof; JSON/copies cannot issue it. */ getNativeFileWriteObservation?: (args: Record, result: ToolResult) => unknown; /** Original producer result custody; returned JSON never grants child evidence. */ readIssuedChildEvidence?: (result: ToolResult) => readonly import("./native-child-evidence.js").NativeChildEvidenceV1[]; /** Current provider desktop/session identity. Host-only; unavailable is fail-closed. */ getDesktopVerificationScope?: () => DesktopVerificationScope | undefined; /** Host-owned semantic identity evaluated before external-effect dispatch. */ objectiveEffectIntent?: (args: Record, context: { runId: string; taskEpoch: number; }) => ToolExternalEffectIntent | null; /** Optional per-tool cap before oversized result triage offloads output. */ maxResultSizeChars?: number; } /** Executor facts for recovery routing; display prose is not the contract. */ export interface ToolFailureFact { kind: "hash_conflict" | "text_mismatch" | "schema_validation" | "filesystem_not_found" | "compiler" | "module_resolution" | "syntax" | "type"; path?: string; expectedHash?: string; actualHash?: string; field?: string; expectedField?: string; } export interface ToolResult { success: boolean; failure?: ToolFailureFact; /** Host-issued observation origin, independent of runtime-authored presentation. */ evidenceOrigin?: "executed" | "reused" | "control"; /** Actual process-local shell identity, including a still-running background start. */ shellRunId?: string; /** Native producer bytes retained independently of a bounded display transcript. * Observation custody only; never process success or effect authority. */ outputCoverage?: import("./tool-output-spool.js").ToolOutputCoverage; /** Observation/dispatch custody only, never external-effect or task-success proof. */ desktopVerificationReceipt?: DesktopVerificationReceipt; /** * User-facing display content. Always populated. * This is what gets shown to the user (TUI, logs, memex archive). */ output: string; /** * Optional model-facing content. When set, this is what the LLM sees * in the tool result message (instead of `output`). Tools opt in to * provide a token-optimized representation for the model while keeping * rich display content in `output`. * * Inspired by Qwen Code's ToolResult.llmContent vs returnDisplay split. * Keeps backward compat: tools that don't set this fall back to `output`. */ llmContent?: string; /** Complete captured operator transcript when inline/model output was spilled. * Observation only; consumers must opt in and redact before displaying. */ operatorDetail?: { output: string; }; error?: string; durationMs: number; /** * Machine-readable tool payload. `output` remains the backwards-compatible * display string; integrations should consume this field when a tool exposes * a stable schema. */ data?: unknown; /** Host-issued complete web response; never reconstructed from preview text. */ nativeWebSource?: import("./web-source.js").NativeWebSource; /** Issued complete HTTP response with immutable file-backed views and bounded range reads. */ nativeStreamedWebSource?: import("./streamed-web-source.js").NativeStreamedWebSource; /** Host-issued complete page/element/evaluation observation, without HTTP or effect authority. */ nativePageContentSource?: import("./page-content-source.js").NativePageContentSource; /** True only when this tool call actually changed project files on disk. */ mutated?: boolean; /** Project file paths changed by this tool call. Empty for dry-runs/no-ops. */ mutatedFiles?: string[]; /** Compact patch/diff preview for provenance and context repair. */ diff?: string; /** True when the tool intentionally previewed without writing. */ dryRun?: boolean; /** True when the requested write matched current disk state and was skipped. */ noop?: boolean; /** * True when the requested replacement was already present on disk while the * requested old text was absent. This is stronger than a generic no-op: the * edit's desired postcondition is already satisfied, so stale-edit recovery * state may be retired without treating the call as a failure. */ alreadyApplied?: boolean; /** True when only part of a requested multi-edit batch landed. */ partial?: boolean; /** Exact vs partial provenance for the bytes this call made available. */ artifactMaterialization?: ArtifactMaterialization; /** SHA-256 of the file content before the action, when applicable. */ beforeHash?: string; /** SHA-256 of the file content after the action, when applicable. */ afterHash?: string; /** Runtime evidence events produced by visual/browser/desktop tools. */ evidenceEvents?: EvidenceEvent[]; /** Trusted process-level facts for a local shell execution, when available. */ executionReceipt?: CommandEvidenceReceipt; /** Actual per-command receipts from a multi-step invocation, in execution order. */ executionReceipts?: CommandEvidenceReceipt[]; /** Typed document extraction provenance for page-aware document tools. */ documentExtraction?: DocumentExtractionReceipt; /** Typed stateful-runtime identity and isolation information. */ runtimeSession?: ToolRuntimeSession; /** Runtime-owned child completion provenance; ordinary output is not proof. */ featureWorkflowChildOutput?: FeatureWorkflowChildOutput; /** Provider acknowledgement bound to the host-admitted effect identity. */ externalEffectReceipt?: ToolExternalEffectReceipt; /** Protocol verification bound to the exact provider artifact/revision. */ verificationReceipt?: ToolVerificationReceipt; } export interface ExecutionConfig { workingDir: string; timeout: number; allowedCommands?: string[]; blockedPaths?: string[]; maxOutputSize: number; }