/** * Thin HTTP client for the DKG daemon API (localhost:9200 by default). * * All adapter modules (channel, memory) use this client instead of * embedding a second DKGAgent. The daemon owns the agent, triple store, * and Node UI. */ /** * Typed daemon HTTP error. Carries the response `status` and the parsed JSON * `body` (when the daemon returned JSON) so callers can branch structurally * (e.g. a 409 `UNSEALED_SHARE_BLOCKED` recovery hint) instead of re-parsing * JSON out of the message string. The human-readable `message` is preserved * verbatim (`DKG daemon responded : `) for back-compat * with the existing `responded NNN` substring checks (e.g. the chat-turns 404 * probe and the `wm/import-file` 404 path). */ export declare class DkgDaemonHttpError extends Error { readonly status: number; readonly body?: unknown; constructor(message: string, status: number, body?: unknown); } export interface DkgClientOptions { /** Base URL of the DKG daemon (default: "http://127.0.0.1:9200"). */ baseUrl?: string; /** Bearer token for daemon API auth. If omitted, tries `/auth.token`. */ apiToken?: string; /** * T70 -- DKG home directory used to read `auth.token` when `apiToken` is * not supplied. Caller (typically `DkgNodePlugin.register`) passes the * runtime-resolved home (`resolveDkgHome({daemonUrl})`) so the constructor * fallback reads from the right place when the active daemon is in * `~/.dkg-dev` (monorepo) vs `~/.dkg` (npm). Without this, an absent * `auth.token` in the resolved home would silently fall through to the * default `~/.dkg/auth.token`, picking up a stale npm-side token while * the live daemon is at `~/.dkg-dev` (the very bug T70 set out to fix). */ dkgHome?: string; /** Request timeout in ms (default: 30 000). */ timeoutMs?: number; } export interface OpenClawAttachmentRef { assertionUri: string; assertionName?: string; fileHash: string; contextGraphId: string; fileName: string; detectedContentType?: string; extractionStatus?: 'completed'; tripleCount?: number; rootEntity?: string; mdIntermediateHash?: string; markdownHash?: string; markdownForm?: string; } export interface ImportedArtifactRequest { contextGraphId: string; assertionUri: string; assertionName?: string; fileHash?: string; subGraphName?: string; } export interface ImportedArtifactResolution { contextGraphId: string; assertionUri: string; assertionName?: string; assertionAgentAddress?: string; subGraphName?: string; fileHash: string; sourceFileHash: string; detectedContentType: string; sourceContentType: string; extractionStatus: 'completed'; extractionMethod?: string; rootEntity?: string; sourceFileName?: string; tripleCount?: number; structuralTripleCount?: number; semanticTripleCount?: number; mdIntermediateHash?: string; markdownForm?: string; markdownHash?: string; canReadMarkdown: boolean; ownerGuardRelaxed?: boolean; } export interface SemanticEnrichmentWriteRequest extends ImportedArtifactRequest { semanticQuads: Array<{ subject: string; predicate: string; object: string; }>; generationMethod?: string; agentIdentity?: string; generatedAt?: string; } export interface ChatTurnStoreStatus { hasAnyChatTurnData: boolean; existingSessionIds: string[]; } export interface LocalAgentIntegrationCapabilities { localChat?: boolean; connectFromUi?: boolean; installNode?: boolean; dkgPrimaryMemory?: boolean; wmImportPipeline?: boolean; nodeServedSkill?: boolean; chatAttachments?: boolean; } export interface LocalAgentIntegrationTransport { kind?: string; bridgeUrl?: string; gatewayUrl?: string; healthUrl?: string; } export interface LocalAgentIntegrationManifest { packageName?: string; version?: string; setupEntry?: string; } export interface LocalAgentIntegrationRuntime { status?: 'disconnected' | 'configured' | 'connecting' | 'ready' | 'degraded' | 'error'; ready?: boolean; lastError?: string | null; updatedAt?: string; } export interface LocalAgentIntegrationPayload { id: string; name?: string; description?: string; enabled?: boolean; transport?: LocalAgentIntegrationTransport; capabilities?: LocalAgentIntegrationCapabilities; manifest?: LocalAgentIntegrationManifest; setupEntry?: string; metadata?: Record; runtime?: LocalAgentIntegrationRuntime; } export interface LocalAgentIntegrationRecord extends LocalAgentIntegrationPayload { status?: string; connectedAt?: string; updatedAt?: string; } /** * T63 -- Shape of `/api/agent/identity` response. * * Mirrors the daemon route handler at * `packages/cli/src/daemon/routes/agent-chat.ts:391`. `agentAddress` is the * canonical EIP-55 form (set from `verifyWallet.address` at agent * registration). The adapter trusts this verbatim and never re-checksums. */ export interface AgentIdentity { agentAddress: string; agentDid: string; name: string; framework?: string; peerId: string; nodeIdentityId: string; } export declare function normalizeContextGraphId(value: string): string; /** * Author attestation produced by an external signer. Mirrors the * `packages/cli/src/api-client.ts` reference so the finalize/create KA flows * can carry a pre-built EIP-712 attestation instead of signing on the daemon. */ export interface PreSignedAuthorAttestationPayload { address: string; /** * OT-RFC-43 Section F2 -- the packed reservedKaId the author signed the * AuthorAttestation over, as a decimal string (uint256-safe over JSON). * Required: the daemon binds it into the digest and honours the reserved slot. */ reservedKaId: string; signature: { r: string; vs: string; }; } /** * VM-publish controls for the finalized-assertion publish path. Mirrors * `KnowledgeAssetFinalizedPublishOptions` in `packages/cli/src/api-client.ts` * verbatim so every first-party client exposes the same surface. */ export interface KnowledgeAssetFinalizedPublishOptions { /** * SDK-friendly spelling for the finalized publish cleanup flag. The * knowledge-assets daemon route forwards `clearSharedMemoryAfter` to * `publishFromFinalizedAssertion`, so the client translates before POST. */ clearAfter?: boolean; publishEpochs?: number; publisherNodeIdentityIdOverride?: bigint; } export declare class DkgDaemonClient { readonly baseUrl: string; private readonly timeoutMs; private readonly apiToken; constructor(opts?: DkgClientOptions); private static loadTokenFromFile; private authHeaders; getAuthToken(): string | undefined; getStatus(): Promise<{ ok: boolean; peerId?: string; error?: string; }>; /** * Probe the daemon's `/api/agent/identity` route using the client's normal * constructor-loaded node-level Bearer token. * * The daemon resolves unknown node-level tokens to its default agent address, * so the response is the canonical WM identity the adapter should cache. * Failure shape mirrors `getStatus()`: `{ ok: false, error }` for transport, * 401, and 5xx responses so the probe site can branch without try/catch. */ getAgentIdentity(): Promise<{ ok: boolean; identity?: AgentIdentity; error?: string; }>; /** * Run a SPARQL query against the daemon. Forwards the full V10 field set * the `/api/query` route accepts -- `view` (`'working-memory' | 'shared-working-memory' | 'verifiable-memory'`), * `agentAddress` (required for WM reads), `assertionName` (scopes WM reads * to a single per-agent assertion), `subGraphName`, `verifiedGraph`, * `graphSuffix`, `includeSharedMemory`. */ query(sparql: string, opts?: { contextGraphId?: string; graphSuffix?: string; includeSharedMemory?: boolean; view?: 'working-memory' | 'shared-working-memory' | 'verifiable-memory'; agentAddress?: string; assertionName?: string; subGraphName?: string; verifiedGraph?: string; /** * P-13: minimum trust level. Only meaningful for * `view: "verifiable-memory"`; ignored (silently) on WM/SWM views. * * The daemon implements only `SelfAttested` / `Endorsed` today -- * higher tiers (Q-1 follow-up) are rejected with HTTP 400, so the * public client surface only advertises the implementable values. * See `packages/query/src/query-engine.ts QueryOptions.minTrust`. */ minTrust?: 'SelfAttested' | 'Endorsed' | 0 | 1; }): Promise; /** * Read saved profile query catalog entries for a context graph. * * The daemon stores these as local profile metadata in * `did:dkg:context-graph:/meta/query-catalog`; callers usually run the * returned `prof:sparqlQuery` text through `query()`. */ readQueryCatalog(contextGraphId: string): Promise>; /** * Append profile query catalog triples for a context graph. * * The daemon ignores caller-supplied graph names and writes into the * context graph's local `meta/query-catalog` profile graph. */ writeQueryCatalog(contextGraphId: string, quads: Array<{ subject: string; predicate: string; object: string; graph?: string; }>): Promise>; /** * Create a per-agent Working Memory assertion graph inside a context graph. * Idempotent on the client side: 400 `"already exists"` errors from the * daemon are swallowed and returned as `{ assertionUri: null, alreadyExists: true }`. * Any other error surfaces normally. */ createAssertion(contextGraphId: string, name: string, opts?: { subGraphName?: string; }): Promise<{ assertionUri: string | null; alreadyExists: boolean; }>; /** * Append quads into an existing Working Memory assertion. The assertion * must have been created first -- callers that create-then-write in a * single call should use `ensureAssertion` + `writeAssertion` together, * with `createAssertion` swallowing duplicates. */ writeAssertion(contextGraphId: string, name: string, quads: Array<{ subject: string; predicate: string; object: string; graph?: string; }>, opts?: { subGraphName?: string; }): Promise<{ written: number; }>; /** Atomically seal and share a complete Working Memory Knowledge Asset. */ promoteAssertion(contextGraphId: string, name: string, opts?: { entities?: string[] | 'all'; subGraphName?: string; }): Promise>; /** * Discard a Working Memory assertion without promoting it. Returns * `{ discarded: true }` on success; the daemon surfaces 400 for invalid * names or missing assertions. */ discardAssertion(contextGraphId: string, name: string, opts?: { subGraphName?: string; }): Promise<{ discarded: boolean; }>; /** * Dump all quads from a single Working Memory assertion's graph. This is * not a SPARQL endpoint -- the daemon returns every quad in the assertion * as `{ quads, count }`. For ad-hoc SPARQL use `query()` with * `view: 'working-memory'` + `assertionName` instead. */ queryAssertion(contextGraphId: string, name: string, opts?: { subGraphName?: string; }): Promise<{ quads: unknown[]; count: number; }>; /** * Resolve deterministic import metadata for a completed attachment ref. * This does not read arbitrary paths; it only returns graph/file-store * metadata already attached to the imported assertion. */ resolveImportArtifact(request: ImportedArtifactRequest): Promise<{ artifact: ImportedArtifactResolution; }>; /** * Read the Markdown source for a completed imported assertion. The daemon * resolves the markdown hash from deterministic import metadata and reads * the content-addressed file store; callers never supply filesystem paths. */ readImportArtifactMarkdown(request: ImportedArtifactRequest & { maxBytes?: number; }): Promise<{ artifact: ImportedArtifactResolution; markdownHash: string; contentType: 'text/markdown'; bytes: number; markdown: string; }>; /** * Append model-derived semantic triples into the completed imported assertion * with provenance. The daemon intentionally does not promote or publish. */ writeSemanticEnrichment(request: SemanticEnrichmentWriteRequest): Promise>; /** * Fetch the lifecycle descriptor for an assertion (creation time, author, * latest extraction status, promotion state). Throws a 404-bearing error * when no record exists for the given (contextGraphId, name, agentAddress). */ getAssertionHistory(contextGraphId: string, name: string, opts?: { agentAddress?: string; subGraphName?: string; }): Promise>; /** * Import a document (markdown, PDF, etc.) into a Working Memory assertion * via multipart/form-data. The daemon runs its extraction pipeline and * writes the resulting triples into the assertion's graph. * * Callers pass raw file bytes (Buffer/Uint8Array) and a filename; the * client constructs the multipart form locally using Node 18+ globals * (`FormData`, `Blob`). When `contentType` is supplied, the daemon's * `normalizeDetectedContentType` picks it up from the explicit form field; * otherwise the daemon falls back to the file part's Content-Type header * (set here from the Blob's `type`). */ importAssertionFile(contextGraphId: string, name: string, fileBuffer: Buffer | Uint8Array, fileName: string, opts?: { contentType?: string; ontologyRef?: string; subGraphName?: string; }): Promise>; /** * Create a named sub-graph inside a context graph. Sub-graphs partition a * CG into organizational regions that assertions can target at * create/write/import time. */ createSubGraph(contextGraphId: string, subGraphName: string): Promise<{ created: string; contextGraphId: string; }>; /** * List all registered sub-graphs for a context graph, with best-effort * per-sub-graph entity / triple counts. */ listSubGraphs(contextGraphId: string): Promise<{ contextGraphId: string; subGraphs: Array<{ name: string; uri: string; description?: string; createdBy?: string; createdAt?: string; entityCount: number; tripleCount: number; }>; }>; getChatTurnStoreStatus(sessionIds: string[]): Promise; /** * Persist a chat turn through the daemon's `/api/openclaw-channel/persist-turn` * route, which delegates to `ChatMemoryManager.storeChatExchange`. As of * v1 of the openclaw-dkg-primary-memory work the downstream writer targets * the `'chat-turns'` Working Memory assertion of the `'agent-context'` * context graph via `agent.assertion.write`, not `agent.share`. */ storeChatTurn(sessionId: string, userMessage: string, assistantReply: string, opts?: { turnId?: string; toolCalls?: Array<{ name: string; args: Record; result: unknown; }>; attachmentRefs?: OpenClawAttachmentRef[]; persistenceState?: 'stored' | 'failed' | 'pending'; failureReason?: string | null; }): Promise; getMemoryStats(): Promise<{ initialized: boolean; messageCount: number; totalTriples: number; }>; getFullStatus(): Promise>; registerAdapter(id: string): Promise; connectLocalAgentIntegration(payload: LocalAgentIntegrationPayload): Promise>; getLocalAgentIntegration(id: string): Promise; updateLocalAgentIntegration(id: string, payload: Omit): Promise>; inviteToContextGraph(contextGraphId: string, peerId: string): Promise<{ invited: string; contextGraphId: string; }>; addParticipant(contextGraphId: string, agentAddress: string): Promise<{ ok: boolean; contextGraphId: string; agentAddress: string; }>; removeParticipant(contextGraphId: string, agentAddress: string): Promise<{ ok: boolean; contextGraphId: string; agentAddress: string; }>; listParticipants(contextGraphId: string): Promise<{ contextGraphId: string; allowedAgents: string[]; }>; listJoinRequests(contextGraphId: string): Promise<{ contextGraphId: string; requests: Array<{ agentAddress: string; status: string; timestamp?: string; agentName?: string; }>; }>; approveJoinRequest(contextGraphId: string, agentAddress: string): Promise<{ ok: boolean; status: string; agentAddress: string; }>; rejectJoinRequest(contextGraphId: string, agentAddress: string): Promise<{ ok: boolean; status: string; agentAddress: string; }>; getAgents(filter?: { framework?: string; skill_type?: string; }): Promise<{ agents: any[]; }>; getSkills(filter?: { skillType?: string; }): Promise<{ skills: any[]; }>; sendChat(to: string, text: string): Promise; getMessages(opts?: { peer?: string; limit?: number; since?: number; }): Promise<{ messages: any[]; }>; listContextGraphs(): Promise<{ contextGraphs: any[]; }>; createContextGraph(id: string, name: string, description?: string, opts?: { accessPolicy?: number; allowedAgents?: string[]; }): Promise<{ created: string; uri: string; }>; registerContextGraph(id: string, opts?: { accessPolicy?: number; }): Promise<{ registered: string; onChainId: string; txHash?: string; hint?: string; }>; subscribe(contextGraphId: string, opts?: { includeSharedMemory?: boolean; }): Promise<{ subscribed: string; catchup: { jobId: string; status: string; includeSharedMemory: boolean; }; }>; getWalletBalances(): Promise<{ wallets: string[]; balances: Array<{ address: string; eth: string; trac: string; symbol: string; }>; chainId: string | null; rpcUrl: string | null; error?: string; }>; invokeSkill(peerId: string, skillUri: string, input?: string): Promise; getWallets(): Promise<{ wallets: string[]; }>; private get; private post; private put; /** * Create a KA + open its WM draft. Pass `quads` to atomically write+seal. * #1116 D5: this combined CLIENT function defaults `alsoShareSwm` to true when * the draft will seal (quads present and `finalize !== false`), so the * one-shot seals AND shares to SWM. Pass `alsoShareSwm: false` to stop at a * sealed WM draft, or `finalize: false` to keep an unsealed editable WM draft. * (The bare daemon route is a primitive -- seal-only -- and never auto-shares; * the default-share lives here in the client.) */ createKnowledgeAsset(contextGraphId: string, name: string, opts?: { subGraphName?: string; quads?: Array<{ subject: string; predicate: string; object: string; graph: string; }>; /** * Seal the draft after writing `quads` (default true). `false` keeps an * editable WM draft that never touches the chain -- the only lifecycle * available to local-only / on-chain-unregistered CGs. Cannot be combined * with `alsoShareSwm`/`alsoPublishVm` (those require a sealed assertion). */ finalize?: boolean; authorAgentAddress?: string; preSignedAuthorAttestation?: PreSignedAuthorAttestationPayload; schemeVersion?: number; alsoShareSwm?: boolean; alsoPublishVm?: boolean | KnowledgeAssetFinalizedPublishOptions; }): Promise>; /** GET a KA's per-layer lifecycle state by name. */ getKnowledgeAsset(contextGraphId: string, name: string, opts?: { subGraphName?: string; }): Promise>; /** Append quads to the KA's WM draft (git add/edit). */ knowledgeAssetWrite(contextGraphId: string, name: string, quads: Array<{ subject: string; predicate: string; object: string; graph?: string; }>, opts?: { subGraphName?: string; }): Promise<{ written: number; }>; /** Seal the WM draft -- computes the merkle root + signs the seal (git commit). */ knowledgeAssetFinalize(contextGraphId: string, name: string, opts?: { subGraphName?: string; authorAgentAddress?: string; preSignedAuthorAttestation?: PreSignedAuthorAttestationPayload; schemeVersion?: number; /** @deprecated Only WM finalization is supported. `swm` fails read-only. */ layer?: 'wm' | 'swm'; }): Promise<{ merkleRoot: string; eip712Digest: string; }>; /** Discard the open WM draft (git checkout -- .). */ knowledgeAssetDiscard(contextGraphId: string, name: string, opts?: { subGraphName?: string; }): Promise<{ discarded: boolean; }>; /** Seed a fresh WM draft from the file's current SWM/VM state (git checkout). */ knowledgeAssetPullFrom(contextGraphId: string, name: string, layer: 'swm' | 'vm', opts?: { subGraphName?: string; onConflict?: 'reject' | 'replace'; }): Promise>; /** Advance the SWM pointer (WM -> SWM; git push origin ). */ knowledgeAssetShare(contextGraphId: string, name: string, opts?: { subGraphName?: string; /** @deprecated Root selection is unsupported. */ entities?: string[] | 'all'; /** @deprecated Unsealed shares are unsupported. */ skipSeal?: boolean; }): Promise<{ swmShared: boolean; promotedCount: number; sealed: boolean; publishReady: boolean; }>; /** Publish to VM -- mint or update on chain (git push origin main). */ knowledgeAssetPublish(contextGraphId: string, name: string, opts?: { subGraphName?: string; } & KnowledgeAssetFinalizedPublishOptions): Promise>; } //# sourceMappingURL=dkg-client.d.ts.map