API Reference
classes
Perspectiveproxy

@coasys/ad4m / Exports / PerspectiveProxy

Class: PerspectiveProxy

PerspectiveProxy provides a high-level interface for working with AD4M Perspectives - agent-centric semantic graphs that store and organize links between expressions.

A Perspective is fundamentally a collection of links (subject-predicate-object triples) that represent an agent's view of their digital world. Through PerspectiveProxy, you can:

  • Add, remove, and query links
  • Work with Social DNA (subject classes and flows)
  • Subscribe to real-time updates
  • Share perspectives as Neighbourhoods
  • Execute Prolog queries for complex graph patterns

Example

// Create and work with links
const perspective = await ad4m.perspective.add("My Space");
await perspective.add({
  source: "did:key:alice",
  predicate: "knows",
  target: "did:key:bob"
});
 
// Query links
const friends = await perspective.get({
  source: "did:key:alice",
  predicate: "knows"
});
 
// Use Social DNA
await perspective.addSdna(todoClass, "subject_class");
const todo = await perspective.createSubject("Todo", "expression://123");
 
// Subscribe to changes
perspective.addListener("link-added", (link) => {
  console.log("New link added:", link);
});

Table of contents

Constructors

Properties

Accessors

Methods

Constructors

constructor

new PerspectiveProxy(handle, ad4m)

Creates a new PerspectiveProxy instance. Note: Don't create this directly, use ad4m.perspective.add() instead.

Parameters

NameType
handlePerspectiveHandle
ad4mPerspectiveClient

Defined in

perspectives/PerspectiveProxy.ts:246

Properties

#client

Private #client: PerspectiveClient

Defined in

perspectives/PerspectiveProxy.ts:236


#handle

Private #handle: PerspectiveHandle

Defined in

perspectives/PerspectiveProxy.ts:235


#perspectiveLinkAddedCallbacks

Private #perspectiveLinkAddedCallbacks: LinkCallback[]

Defined in

perspectives/PerspectiveProxy.ts:237


#perspectiveLinkRemovedCallbacks

Private #perspectiveLinkRemovedCallbacks: LinkCallback[]

Defined in

perspectives/PerspectiveProxy.ts:238


#perspectiveLinkUpdatedCallbacks

Private #perspectiveLinkUpdatedCallbacks: LinkCallback[]

Defined in

perspectives/PerspectiveProxy.ts:239


#perspectiveSyncStateChangeCallbacks

Private #perspectiveSyncStateChangeCallbacks: SyncStateChangeCallback[]

Defined in

perspectives/PerspectiveProxy.ts:240


name

name: string

Human-readable name of this perspective

Defined in

perspectives/PerspectiveProxy.ts:224


neighbourhood

neighbourhood: NeighbourhoodExpression

If this perspective is shared, this contains the Neighbourhood metadata

Defined in

perspectives/PerspectiveProxy.ts:230


sharedUrl

sharedUrl: string

If this perspective is shared as a Neighbourhood, this is its URL

Defined in

perspectives/PerspectiveProxy.ts:227


state

state: PerspectiveState

Current sync state if this perspective is shared

Defined in

perspectives/PerspectiveProxy.ts:233


uuid

uuid: string

Unique identifier of this perspective

Defined in

perspectives/PerspectiveProxy.ts:221

Accessors

ai

get ai(): AIClient

Returns a proxy object for working with AI capabilities.

Returns

AIClient

AIClient instance

Example

// Use AI to analyze perspective content
const summary = await perspective.ai.summarize();
 
// Generate new content
const suggestion = await perspective.ai.suggest("next action");

Defined in

perspectives/PerspectiveProxy.ts:1057

Methods

add

add(link, status?, batchId?): Promise<LinkExpression>

Adds a new link to the perspective.

Parameters

NameTypeDefault valueDescription
linkLinkundefinedThe link to add
statusLinkStatus'shared'Whether the link should be shared in a Neighbourhood
batchId?stringundefinedOptional batch ID to group this operation with others

Returns

Promise<LinkExpression>

The created LinkExpression

Example

// Add a simple relationship
await perspective.add({
  source: "did:key:alice",
  predicate: "follows",
  target: "did:key:bob"
});
 
// Add a local-only link
await perspective.add({
  source: "note://123",
  predicate: "tag",
  target: "private"
}, "local");

Defined in

perspectives/PerspectiveProxy.ts:405


addLinkExpression

addLinkExpression(link, status?, batchId?): Promise<LinkExpression>

Adds a pre-signed LinkExpression to the perspective.

Parameters

NameTypeDefault valueDescription
linkLinkExpressionundefinedThe signed LinkExpression to add
statusLinkStatus'shared'Whether the link should be shared
batchId?stringundefinedOptional batch ID to group this operation with others

Returns

Promise<LinkExpression>

The added LinkExpression

Defined in

perspectives/PerspectiveProxy.ts:453


addLinks

addLinks(links, status?, batchId?): Promise<LinkExpression[]>

Adds multiple links to the perspective in a single operation. More efficient than adding links one by one.

Parameters

NameTypeDefault valueDescription
linksLink[]undefinedArray of links to add
statusLinkStatus'shared'Whether the links should be shared
batchId?stringundefinedOptional batch ID to group this operation with others

Returns

Promise<LinkExpression[]>

Array of created LinkExpressions

Defined in

perspectives/PerspectiveProxy.ts:418


addListener

addListener(type, cb): Promise<void>

Subscribes to link changes in the perspective.

Parameters

NameTypeDescription
typePerspectiveListenerTypesType of change to listen for
cbLinkCallbackCallback function

Returns

Promise<void>

Example

// Listen for new links
perspective.addListener("link-added", (link) => {
  console.log("New link:", link);
});
 
// Listen for removed links
perspective.addListener("link-removed", (link) => {
  console.log("Link removed:", link);
});

Defined in

perspectives/PerspectiveProxy.ts:529


addSdna

addSdna(name, sdnaCode, sdnaType): Promise<boolean>

Adds the given Social DNA code to the perspective's SDNA code

Parameters

NameType
namestring
sdnaCodestring
sdnaType"subject_class" | "flow" | "custom"

Returns

Promise<boolean>

Defined in

perspectives/PerspectiveProxy.ts:719


addSyncStateChangeListener

addSyncStateChangeListener(cb): Promise<void>

Subscribes to sync state changes if this perspective is shared.

Parameters

NameTypeDescription
cbSyncStateChangeCallbackCallback function

Returns

Promise<void>

Example

perspective.addSyncStateChangeListener((state) => {
  console.log("Sync state:", state);
});

Defined in

perspectives/PerspectiveProxy.ts:551


availableFlows

availableFlows(exprAddr): Promise<string[]>

Returns all Social DNA flows that can be started from the given expression

Parameters

NameType
exprAddrstring

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:668


buildQueryFromTemplate

Private buildQueryFromTemplate(obj): string

Parameters

NameType
objobject

Returns

string

Defined in

perspectives/PerspectiveProxy.ts:912


commitBatch

commitBatch(batchId): Promise<LinkExpressionMutations>

Commits a batch of operations

Parameters

NameType
batchIdstring

Returns

Promise<LinkExpressionMutations>

Defined in

perspectives/PerspectiveProxy.ts:484


createBatch

createBatch(): Promise<string>

Creates a new batch for grouping operations

Returns

Promise<string>

Defined in

perspectives/PerspectiveProxy.ts:479


createExpression

createExpression(content, languageAddress): Promise<string>

Creates a new Expression in the specified Language.

Parameters

NameTypeDescription
contentanyContent for the new Expression
languageAddressstringAddress of the Language to use

Returns

Promise<string>

URI of the created Expression

Defined in

perspectives/PerspectiveProxy.ts:506


createSubject

createSubject<T, B>(subjectClass, exprAddr, initialValues?, batchId?): Promise<B extends undefined ? T : string>

Creates a new subject instance of the given subject class

Type parameters

NameType
TT
Bextends string = undefined

Parameters

NameTypeDescription
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class.
exprAddrstringThe address of the expression to be turned into a subject instance
initialValues?Record<string, any>Optional initial values for properties. If provided, these will be merged with constructor actions for better performance.
batchId?BOptional batch ID for grouping operations. If provided, returns the expression address instead of the subject proxy since the subject won't exist until the batch is committed.

Returns

Promise<B extends undefined ? T : string>

A proxy object for the created subject, or just the expression address if in batch mode

Defined in

perspectives/PerspectiveProxy.ts:758


ensureSDNASubjectClass

ensureSDNASubjectClass(jsClass): Promise<void>

Takes a JS class (its constructor) and assumes that it was decorated by the

Parameters

NameType
jsClassany

Returns

Promise<void>

Subject Class

etc. decorators. It then tests if there is a subject class already present in the perspective's SDNA that matches the given class. If there is no such class, it gets the JS class's SDNA by calling its static generateSDNA() function and adds it to the perspective's SDNA.

Defined in

perspectives/PerspectiveProxy.ts:1028


executeAction

executeAction(actions, expression, parameters, batchId?): Promise<boolean>

Executes a set of actions on an expression with optional parameters. Used internally by Social DNA flows and subject class operations.

Actions are specified as an array of commands that modify links in the perspective. Each action is an object with the following format:

{
  action: "addLink" | "removeLink" | "setSingleTarget" | "collectionSetter",
  source: string,    // Usually "this" to reference the current expression
  predicate: string, // The predicate URI
  target: string     // The target value or "value" for parameters
}

Available commands:

  • addLink: Creates a new link
  • removeLink: Removes an existing link
  • setSingleTarget: Removes all existing links with the same source/predicate and adds a new one
  • collectionSetter: Special command for setting collection properties

When used with parameters, the special value "value" in the target field will be replaced with the actual parameter value.

Parameters

NameTypeDescription
actionsanyArray of action objects to execute
expressionanyTarget expression address (replaces "this" in actions)
parametersParameter[]Optional parameters that replace "value" in actions
batchId?stringOptional batch ID to group this operation with others

Returns

Promise<boolean>

Example

// Add a state link and remove an old one
await perspective.executeAction([
  {
    action: "addLink",
    source: "this",
    predicate: "todo://state", 
    target: "todo://doing"
  },
  {
    action: "removeLink",
    source: "this",
    predicate: "todo://state",
    target: "todo://ready"
  }
], "expression://123");
 
// Set a property using a parameter
await perspective.executeAction([
  {
    action: "setSingleTarget",
    source: "this",
    predicate: "todo://title",
    target: "value"
  }
], "expression://123", [
  { name: "title", value: "New Title" }
]);

Defined in

perspectives/PerspectiveProxy.ts:324


expressionsInFlowState

expressionsInFlowState(flowName, flowState): Promise<string[]>

Returns all expressions in the given state of given Social DNA flow

Parameters

NameType
flowNamestring
flowStatenumber

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:682


flowActions

flowActions(flowName, exprAddr): Promise<string[]>

Returns available action names, with regard to Social DNA flow and expression's flow state

Parameters

NameType
flowNamestring
exprAddrstring

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:694


flowState

flowState(flowName, exprAddr): Promise<number>

Returns the given expression's flow state with regard to given Social DNA flow

Parameters

NameType
flowNamestring
exprAddrstring

Returns

Promise<number>

Defined in

perspectives/PerspectiveProxy.ts:688


get

get(query): Promise<LinkExpression[]>

Retrieves links from the perspective that match the given query.

Parameters

NameTypeDescription
queryLinkQueryQuery parameters to filter links

Returns

Promise<LinkExpression[]>

Array of matching LinkExpressions

Example

// Get all links where Alice knows someone
const links = await perspective.get({
  source: "did:key:alice",
  predicate: "knows"
});
 
// Get all comments on a post
const comments = await perspective.get({
  source: "post://123",
  predicate: "comment"
});

Defined in

perspectives/PerspectiveProxy.ts:349


getAllSubjectInstances

getAllSubjectInstances<T>(subjectClass): Promise<T[]>

Returns all subject instances of the given subject class as proxy objects.

Type parameters

Name
T

Parameters

NameTypeDescription
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class. In the latter case, all subject classes that match the given properties will be used.

Returns

Promise<T[]>

Defined in

perspectives/PerspectiveProxy.ts:874


getAllSubjectProxies

getAllSubjectProxies<T>(subjectClass): Promise<T[]>

Returns all subject proxies of the given subject class.

Type parameters

Name
T

Parameters

NameTypeDescription
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class. In the latter case, all subject classes that match the given properties will be used.

Returns

Promise<T[]>

Defined in

perspectives/PerspectiveProxy.ts:896


getExpression

getExpression(expressionURI): Promise<ExpressionRendered>

Retrieves and renders an Expression referenced in this perspective.

Parameters

NameTypeDescription
expressionURIstringURI of the Expression to retrieve

Returns

Promise<ExpressionRendered>

The rendered Expression

Defined in

perspectives/PerspectiveProxy.ts:495


getNeighbourhoodProxy

getNeighbourhoodProxy(): NeighbourhoodProxy

Returns

NeighbourhoodProxy

Defined in

perspectives/PerspectiveProxy.ts:1039


getSdna

getSdna(): Promise<string[]>

Returns the perspective's Social DNA code This will return all SDNA code elements in an array.

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:710


getSingleTarget

getSingleTarget(query): Promise<string | void>

Gets a single target value matching a query. Useful when you expect only one result.

Parameters

NameTypeDescription
queryLinkQueryQuery to find the target

Returns

Promise<string | void>

Target value or void if not found

Example

// Get a user's name
const name = await perspective.getSingleTarget({
  source: "did:key:alice",
  predicate: "name"
});

Defined in

perspectives/PerspectiveProxy.ts:621


getSubjectData

getSubjectData<T>(subjectClass, exprAddr): Promise<T>

Type parameters

Name
T

Parameters

NameType
subjectClassT
exprAddrstring

Returns

Promise<T>

Defined in

perspectives/PerspectiveProxy.ts:800


getSubjectProxy

getSubjectProxy<T>(base, subjectClass): Promise<T>

For an existing subject instance (existing in the perspective's links) this function returns a proxy object that can be used to access the subject's properties and methods.

Type parameters

Name
T

Parameters

NameTypeDescription
basestringURI of the subject's root expression
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class. In the latter case, the first subject class that matches the given properties will be used.

Returns

Promise<T>

Defined in

perspectives/PerspectiveProxy.ts:859


infer

infer(query): Promise<any>

Executes a Prolog query against the perspective's knowledge base. This is a powerful way to find complex patterns in the graph.

Parameters

NameTypeDescription
querystringProlog query string

Returns

Promise<any>

Query results or false if no results

Example

// Find friends of friends
const results = await perspective.infer(`
  triple(A, "knows", B),
  triple(B, "knows", C),
  A \= C
`);
 
// Find all active todos
const todos = await perspective.infer(`
  instance(Todo, "Todo"),
  property_getter("Todo", Todo, "state", "active")
`);

Defined in

perspectives/PerspectiveProxy.ts:376


isSubjectInstance

isSubjectInstance<T>(expression, subjectClass): Promise<boolean>

Checks if the given expression is a subject instance of the given subject class

Type parameters

Name
T

Parameters

NameTypeDescription
expressionstringThe expression to be checked
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class. In the latter case, the first subject class that matches the given properties will be used.

Returns

Promise<boolean>

Defined in

perspectives/PerspectiveProxy.ts:835


linkMutations

linkMutations(mutations, status?): Promise<LinkExpressionMutations>

Applies a set of link mutations (adds and removes) in a single operation. Useful for atomic updates to the perspective.

Parameters

NameTypeDefault valueDescription
mutationsLinkMutationsundefinedObject containing links to add and remove
statusLinkStatus'shared'Whether new links should be shared

Returns

Promise<LinkExpressionMutations>

Object containing results of the mutations

Defined in

perspectives/PerspectiveProxy.ts:441


loadSnapshot

loadSnapshot(snapshot): Promise<void>

Loads a perspective snapshot, replacing current content.

Parameters

NameTypeDescription
snapshotPerspectivePerspective snapshot to load

Returns

Promise<void>

Defined in

perspectives/PerspectiveProxy.ts:592


remove

remove(link, batchId?): Promise<boolean>

Removes a link from the perspective.

Parameters

NameTypeDescription
linkLinkExpressionInputThe link to remove
batchId?stringOptional batch ID to group this operation with others

Returns

Promise<boolean>

Defined in

perspectives/PerspectiveProxy.ts:474


removeLinks

removeLinks(links, batchId?): Promise<LinkExpression[]>

Removes multiple links from the perspective.

Parameters

NameTypeDescription
linksLinkExpressionInput[]Array of links to remove
batchId?stringOptional batch ID to group this operation with others

Returns

Promise<LinkExpression[]>

Array of removed LinkExpressions

Defined in

perspectives/PerspectiveProxy.ts:429


removeListener

removeListener(type, cb): Promise<void>

Unsubscribes from link changes.

Parameters

NameTypeDescription
typePerspectiveListenerTypesType of change to stop listening for
cbLinkCallbackThe callback function to remove

Returns

Promise<void>

Defined in

perspectives/PerspectiveProxy.ts:561


removeSubject

removeSubject<T>(subjectClass, exprAddr, batchId?): Promise<void>

Removes a subject instance by running its (SDNA defined) destructor, which means removing links around the given expression address

Type parameters

Name
T

Parameters

NameTypeDescription
subjectClassTEither a string with the name of the subject class, or an object with the properties of the subject class. In the latter case, the first subject class that matches the given properties will be used.
exprAddrstringThe address of the expression to be turned into a subject instance
batchId?stringOptional batch ID for grouping operations. If provided, the removal will be part of the batch and won't be executed until the batch is committed.

Returns

Promise<void>

Defined in

perspectives/PerspectiveProxy.ts:818


runFlowAction

runFlowAction(flowName, exprAddr, actionName): Promise<void>

Runs given Social DNA flow action

Parameters

NameType
flowNamestring
exprAddrstring
actionNamestring

Returns

Promise<void>

Defined in

perspectives/PerspectiveProxy.ts:700


sdnaFlows

sdnaFlows(): Promise<string[]>

Returns all the Social DNA flows defined in this perspective

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:662


setSingleTarget

setSingleTarget(link, status?): Promise<void>

Sets a single target value, removing any existing targets.

Parameters

NameTypeDefault valueDescription
linkLinkundefinedLink defining the new target
statusLinkStatus'shared'Whether the link should be shared

Returns

Promise<void>

Example

// Set a user's status
await perspective.setSingleTarget({
  source: "did:key:alice",
  predicate: "status",
  target: "online"
});

Defined in

perspectives/PerspectiveProxy.ts:646


snapshot

snapshot(): Promise<Perspective>

Creates a snapshot of the current perspective state. Useful for backup or sharing.

Returns

Promise<Perspective>

Perspective object containing all links

Defined in

perspectives/PerspectiveProxy.ts:583


startFlow

startFlow(flowName, exprAddr): Promise<void>

Starts the Social DNA flow

Parameters

NameTypeDescription
flowNamestringon the expression
exprAddrstring

Returns

Promise<void>

Defined in

perspectives/PerspectiveProxy.ts:674


stringOrTemplateObjectToSubjectClassName

stringOrTemplateObjectToSubjectClassName<T>(subjectClass): Promise<string>

Type parameters

Name
T

Parameters

NameType
subjectClassT

Returns

Promise<string>

Defined in

perspectives/PerspectiveProxy.ts:732


subjectClasses

subjectClasses(): Promise<string[]>

Returns all the Subject classes defined in this perspectives SDNA

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:724


subjectClassesByTemplate

subjectClassesByTemplate(obj): Promise<string[]>

Returns all subject classes that match the given template object. This function looks at the properties of the template object and its setters and collections to create a Prolog query that finds all subject classes that would be converted to a proxy object with exactly the same properties and collections.

Since there could be multiple subject classes that match the given criteria, this function returns a list of class names.

Parameters

NameTypeDescription
objobjectThe template object

Returns

Promise<string[]>

Defined in

perspectives/PerspectiveProxy.ts:1012


subscribeInfer

subscribeInfer(query): Promise<QuerySubscriptionProxy>

Creates a subscription for a Prolog query that updates in real-time.

Parameters

NameTypeDescription
querystringProlog query string

Returns

Promise<QuerySubscriptionProxy>

QuerySubscriptionProxy instance

Example

// Subscribe to active todos
const subscription = await perspective.subscribeInfer(`
  instance(Todo, "Todo"),
  property_getter("Todo", Todo, "state", "active")
`);
 
subscription.onResult((todos) => {
  console.log("Active todos:", todos);
});

Defined in

perspectives/PerspectiveProxy.ts:1080


update

update(oldLink, newLink, batchId?): Promise<LinkExpression>

Updates an existing link with new data.

Parameters

NameTypeDescription
oldLinkLinkExpressionInputThe existing link to update
newLinkLinkThe new link data
batchId?stringOptional batch ID to group this operation with others

Returns

Promise<LinkExpression>

Defined in

perspectives/PerspectiveProxy.ts:464