Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ts/packages/agentSdk/src/agentInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ export type GrammarContent = {
sourceMap?: string | undefined;
};

export type ActionEffect = "read-only" | "state-changing" | "unknown";

export type ActionPolicy = {
// Omission is unknown, never an exemption from effect confirmation.
effects?: ActionEffect;
// Even a read-only action can explicitly require confirmation.
confirmation?: "required";
};

export type SchemaManifest = {
description: string;
schemaType: string | SchemaTypeNames; // string if there are only action schemas
Expand All @@ -83,6 +92,8 @@ export type SchemaManifest = {
injected?: boolean; // whether the translator is injected into other domains, default is false
cached?: boolean; // whether the translator's action should be cached, default is true
streamingActions?: string[];
// Exact action names. Applies to structured invocation, not NL routing.
actionPolicies?: Record<string, ActionPolicy>;
};

export type ActionManifest = {
Expand Down
2 changes: 2 additions & 0 deletions ts/packages/agentSdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export {
SchemaContent,
SchemaFormat,
SchemaManifest,
ActionEffect,
ActionPolicy,
AppAgent,
AppAgentEvent,
AgentMessageKind,
Expand Down
17 changes: 17 additions & 0 deletions ts/packages/dispatcher/dispatcher/src/context/appAgentManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,23 @@ export class AppAgentManager implements ActionConfigProvider {
return this.readiness.get(appAgentName) ?? { state: "ready" };
}

public getReadinessSnapshot(appAgentName: string): {
source: "cached" | "not-supported" | "uninitialized" | "not-checked";
report?: ReadinessReport;
} {
const record = this.getRecord(appAgentName);
if (record.sessionContext === undefined) {
return { source: "uninitialized" };
}
const report = this.readiness.get(appAgentName);
if (report !== undefined) {
return { source: "cached", report: { ...report } };
}
return record.appAgent?.checkReadiness === undefined
? { source: "not-supported", report: { state: "ready" } }
: { source: "not-checked" };
}

// True iff this agent has been observed to implement checkReadiness
// at any point this session AND we currently don't have a cached
// report for it. In practice this means: the agent was enabled at
Expand Down
15 changes: 15 additions & 0 deletions ts/packages/dispatcher/dispatcher/src/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ import {
import { randomUUID } from "node:crypto";
import { context as otelContext } from "@opentelemetry/api";
import { getAgentSchemas } from "./context/system/describe/agentSchemaInfo.js";
import {
StructuredActionDiscovery,
type StructuredActionAccess,
} from "./structuredAction/discovery.js";

async function getDynamicDisplay(
context: CommandHandlerContext,
Expand Down Expand Up @@ -200,7 +204,12 @@ export function createDispatcherFromContext(
context: CommandHandlerContext,
connectionId?: ConnectionId,
closeFn?: () => Promise<void>,
structuredActionAccess?: StructuredActionAccess,
): Dispatcher {
const structuredActions = new StructuredActionDiscovery(
context,
structuredActionAccess,
);
const submitInput = (
command: string,
clientRequestId: unknown,
Expand Down Expand Up @@ -389,6 +398,12 @@ export function createDispatcherFromContext(
async getAgentSchemas(agentName?: string) {
return getAgentSchemas(context, agentName);
},
async searchActions(request) {
return structuredActions.searchActions(request);
},
async getActionContract(identity) {
return structuredActions.getActionContract(identity);
},
async cancelCommand(requestId: string): Promise<CancelResult> {
const kind = context.requestQueue.classifyCancel(requestId, "user");
if (kind === "queued") {
Expand Down
1 change: 1 addition & 0 deletions ts/packages/dispatcher/dispatcher/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

// Internal exports for agent server
export { createDispatcherFromContext } from "./dispatcher.js";
export type { StructuredActionAccess } from "./structuredAction/discovery.js";
export {
closeCommandHandlerContext,
initializeCommandHandlerContext,
Expand Down
179 changes: 179 additions & 0 deletions ts/packages/dispatcher/dispatcher/src/structuredAction/contract.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { createHash } from "node:crypto";
import {
generateSchemaTypeDefinition,
getActionDescription,
toJSONParsedActionSchema,
} from "@typeagent/action-schema";
import type {
ActionSchemaTypeDefinition,
SchemaType,
} from "@typeagent/action-schema";
import {
structuredActionProtocolVersion,
type ActionAvailability,
type ActionContract,
type ActionExecutionPolicy,
type ActionIdentity,
} from "@typeagent/dispatcher-types";
import type { ActionConfig } from "../translation/actionConfig.js";

function executionType(type: SchemaType): unknown {
switch (type.type) {
case "object":
return {
type: type.type,
fields: Object.fromEntries(
Object.entries(type.fields).map(([name, field]) => [
name,
{
optional: field.optional === true,
type: executionType(field.type),
},
]),
),
};
case "array":
return {
type: type.type,
elementType: executionType(type.elementType),
};
case "type-union":
return { type: type.type, types: type.types.map(executionType) };
case "string-union":
return { type: type.type, typeEnum: type.typeEnum };
case "type-reference":
return { type: type.type, name: type.name };
default:
return { type: type.type };
}
}

function canonicalize(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(canonicalize);
}
if (value !== null && typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.filter(([, item]) => item !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, item]) => [key, canonicalize(item)]),
);
}
return value;
}

function getPolicy(
config: ActionConfig,
actionName: string,
): ActionExecutionPolicy {
if (
config.actionPolicies !== undefined &&
(config.actionPolicies === null ||
typeof config.actionPolicies !== "object" ||
Array.isArray(config.actionPolicies))
) {
throw new Error(
`Invalid structured action policies for '${config.schemaName}'`,
);
}
const declaration = Object.prototype.hasOwnProperty.call(
config.actionPolicies ?? {},
actionName,
)
? config.actionPolicies?.[actionName]
: undefined;
if (
declaration !== undefined &&
(declaration === null ||
typeof declaration !== "object" ||
Array.isArray(declaration))
) {
throw new Error(
`Invalid structured action policy for '${config.schemaName}.${actionName}'`,
);
}
const effects =
declaration?.effects === undefined ? "unknown" : declaration.effects;
if (
(effects !== "unknown" &&
effects !== "read-only" &&
effects !== "state-changing") ||
(declaration?.confirmation !== undefined &&
declaration.confirmation !== "required")
) {
throw new Error(
`Invalid structured action policy for '${config.schemaName}.${actionName}'`,
);
}
return {
effects,
confirmation:
effects === "read-only" && declaration?.confirmation !== "required"
? "not-required"
: "required",
};
}

export function createActionContract(
identity: ActionIdentity,
definition: ActionSchemaTypeDefinition,
config: ActionConfig,
availability: ActionAvailability,
): ActionContract {
const policy = getPolicy(config, identity.actionName);
const output: ActionContract["output"] = {
envelope: "ActionResult",
optional: true,
resultValue: { type: "unknown", optional: true },
resultEntity: { type: "Entity", optional: true },
entities: { type: "Entity[]", optional: true },
};
const interactions: ActionContract["interactions"] = {
mode: "may-require-interaction",
kinds: ["question", "choice", "form", "action-proposal"],
};
// Reuse the serializer's dependency closure, including recursive references.
const serialized = toJSONParsedActionSchema({
entry: { action: definition },
actionSchemas: new Map([[identity.actionName, definition]]),
});
const executionContract = {
protocolVersion: structuredActionProtocolVersion,
identity,
entry: serialized.entry,
types: Object.fromEntries(
Object.entries(serialized.types).map(([name, def]) => [
name,
executionType(def.type),
]),
),
paramSpecs: definition.paramSpecs,
policy,
output,
interactions,
errorReasoning: config.errorReasoning,
streaming:
config.streamingActions?.includes(identity.actionName) ?? false,
};
const fingerprint = createHash("sha256")
.update(JSON.stringify(canonicalize(executionContract)))
.digest("hex");
return {
...identity,
description: getActionDescription(definition) ?? "",
availability,
fingerprint,
input: {
format: "typescript",
typeName: definition.name,
schemaText: generateSchemaTypeDefinition(definition),
},
policy,
output,
interactions,
};
}
Loading
Loading