@deliverd/sdk 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ import { approveAndRun, type MuseToolApprovalOptions, type MuseToolRunner } from "./muse-spark.js";
2
+ import { askAboutCall } from "./shared.js";
3
+
4
+ /**
5
+ * Perplexity's Agent API: a person decides the tool calls a run asks to make.
6
+ *
7
+ * The Agent API (`POST https://api.perplexity.ai/v1/agent`, also served at
8
+ * `/v1/responses` for the OpenAI SDK) runs the agent loop itself: search,
9
+ * fetch, any model through one key, remote MCP servers and the connectors a
10
+ * Project administrator set up. It stops for a person in two places, and this
11
+ * answers both:
12
+ *
13
+ * - **MCP servers and connectors with `require_approval`.** The call does not
14
+ * run; the response's `output` carries an `mcp_approval_request` instead,
15
+ * and the next request answers it with an `mcp_approval_response`. Perplexity
16
+ * runs MCP and connector calls without asking unless `require_approval` is
17
+ * set, unlike OpenAI's default, so set it on every server that can change
18
+ * something.
19
+ * - **Your own functions.** A `function_call` in `output` is a call your code
20
+ * makes, so your code is where a person comes in: only approved calls run,
21
+ * and a declined one answers the model with the person's reason.
22
+ *
23
+ * ```ts
24
+ * import Perplexity from "@perplexity-ai/perplexity_ai";
25
+ * import { Deliverd } from "@deliverd/sdk";
26
+ * import { runPerplexityWithDeliverd } from "@deliverd/sdk/adapters";
27
+ *
28
+ * const response = await runPerplexityWithDeliverd(new Perplexity(), {
29
+ * model: "openai/gpt-5.6-sol",
30
+ * input: "Close the stale issues in our tracker",
31
+ * tools: [{ type: "connector", id: "connector_linear", server_label: "linear", require_approval: "always" }],
32
+ * }, { deliverd: new Deliverd(), approvers: ["platform-team"] });
33
+ * ```
34
+ *
35
+ * Every call is keyed by its id (`perplexity:<id>`), so a retried round, or a
36
+ * process restarted mid-wait, finds the request it already made. Shapes are
37
+ * from Perplexity's Agent API reference (MCP tool, connectors, custom
38
+ * functions); nothing from `@perplexity-ai/perplexity_ai` is imported.
39
+ */
40
+
41
+ const PREFIX = "perplexity:";
42
+
43
+ /** An MCP or connector call waiting for an answer. It has not run. */
44
+ export interface PerplexityApprovalRequest {
45
+ type: "mcp_approval_request";
46
+ id: string;
47
+ name: string;
48
+ /** JSON-encoded on the wire. */
49
+ arguments?: string;
50
+ server_label?: string;
51
+ /** Set when the call came from a connector set up in the API Console. */
52
+ connector_id?: string | null;
53
+ }
54
+
55
+ /** The answer to one `mcp_approval_request`, sent as an `input` item of the next request. */
56
+ export interface PerplexityApprovalResponse {
57
+ type: "mcp_approval_response";
58
+ approval_request_id: string;
59
+ approve: boolean;
60
+ /** Read by the model when a call was declined. */
61
+ reason?: string;
62
+ }
63
+
64
+ export interface PerplexityApprovalOptions extends MuseToolApprovalOptions {
65
+ /** Put the person's reason on a declined answer, where the model reads it. Default true. */
66
+ sendReason?: boolean;
67
+ }
68
+
69
+ export interface PerplexityApprovals {
70
+ /** One answer per request, in the order they were asked: the next request's `input`. */
71
+ responses: PerplexityApprovalResponse[];
72
+ /** Why each declined call was declined, by request id, for your logs. */
73
+ reasons: Record<string, string>;
74
+ }
75
+
76
+ /**
77
+ * Ask about every `mcp_approval_request` in a response's `output`, and build
78
+ * the answers. A call `when` does not select is approved without asking.
79
+ * Other items are ignored.
80
+ */
81
+ export async function answerPerplexityApprovals(
82
+ output: readonly { type?: string }[] | null | undefined,
83
+ options: PerplexityApprovalOptions
84
+ ): Promise<PerplexityApprovals> {
85
+ const result: PerplexityApprovals = { responses: [], reasons: {} };
86
+ for (const request of approvalRequests(output)) {
87
+ const input = parseArguments(request.arguments);
88
+ let approve = true;
89
+ let reason: string | undefined;
90
+ if (!options.when || (await options.when(request.name, input))) {
91
+ const outcome = await askAboutCall(request.name, input, `${PREFIX}${request.id}`, {
92
+ ...options,
93
+ metadata: {
94
+ ...options.metadata,
95
+ ...(request.server_label ? { server: request.server_label } : {}),
96
+ ...(request.connector_id ? { connector: request.connector_id } : {}),
97
+ },
98
+ });
99
+ approve = outcome.allowed;
100
+ if (!outcome.allowed) reason = outcome.reason;
101
+ }
102
+ const answer: PerplexityApprovalResponse = { type: "mcp_approval_response", approval_request_id: request.id, approve };
103
+ if (reason) {
104
+ result.reasons[request.id] = reason;
105
+ if (options.sendReason !== false) answer.reason = reason;
106
+ }
107
+ result.responses.push(answer);
108
+ }
109
+ return result;
110
+ }
111
+
112
+ /** A function call the model asked for in an Agent API response. */
113
+ export interface PerplexityFunctionCall {
114
+ type: "function_call";
115
+ call_id: string;
116
+ name: string;
117
+ arguments: string;
118
+ }
119
+
120
+ /** The result of one function call, sent as an `input` item of the next request. */
121
+ export interface PerplexityFunctionCallOutput {
122
+ type: "function_call_output";
123
+ call_id: string;
124
+ output: string;
125
+ }
126
+
127
+ /**
128
+ * Ask about, and run, every `function_call` in a response's `output`. Only
129
+ * approved calls run; a declined one's output tells the model a person said
130
+ * no, and why. Every call gets an output, because the run cannot continue
131
+ * without one.
132
+ */
133
+ export async function runPerplexityFunctionCalls(
134
+ output: readonly { type?: string }[] | null | undefined,
135
+ run: MuseToolRunner,
136
+ options: PerplexityApprovalOptions
137
+ ): Promise<PerplexityFunctionCallOutput[]> {
138
+ const results: PerplexityFunctionCallOutput[] = [];
139
+ for (const item of output ?? []) {
140
+ if (item.type !== "function_call") continue;
141
+ const call = item as PerplexityFunctionCall;
142
+ results.push({
143
+ type: "function_call_output",
144
+ call_id: call.call_id,
145
+ output: await approveAndRun(call.name, call.arguments, call.call_id, run, options, PREFIX),
146
+ });
147
+ }
148
+ return results;
149
+ }
150
+
151
+ /** Perplexity's client, or the OpenAI SDK pointed at `https://api.perplexity.ai/v1`. */
152
+ export interface PerplexityClient {
153
+ responses: { create(params: Record<string, unknown>): Promise<PerplexityResponse> | PromiseLike<PerplexityResponse> };
154
+ }
155
+
156
+ /** The parts of an Agent API response this reads. */
157
+ export interface PerplexityResponse {
158
+ id: string;
159
+ status?: string;
160
+ output?: { type?: string }[] | null;
161
+ }
162
+
163
+ export interface PerplexityRunOptions extends PerplexityApprovalOptions {
164
+ /** Makes your own function calls. Without it, a response asking for one is returned to you as it is. */
165
+ run?: MuseToolRunner;
166
+ /**
167
+ * Resend the conversation in `input` instead of chaining with
168
+ * `previous_response_id`. For accounts under zero data retention, which
169
+ * cannot use `previous_response_id`; each response's output, and the
170
+ * answers, are sent back unchanged.
171
+ */
172
+ replay?: boolean;
173
+ /** Stop after this many rounds of answers. Default 10. */
174
+ maxRounds?: number;
175
+ }
176
+
177
+ /**
178
+ * Create a response, and keep answering its approval requests and running its
179
+ * function calls until it asks for nothing more.
180
+ *
181
+ * Each follow-up carries everything in `params` (`model`, `tools`,
182
+ * `instructions`) except `input`, which becomes the answers and outputs, with
183
+ * the last response's id as `previous_response_id`; or, with `replay`, the
184
+ * whole conversation so far. The `tools` array goes unchanged, as Perplexity
185
+ * requires. Non-streaming, foreground responses only.
186
+ */
187
+ export async function runPerplexityWithDeliverd(
188
+ client: PerplexityClient,
189
+ params: Record<string, unknown>,
190
+ options: PerplexityRunOptions
191
+ ): Promise<PerplexityResponse> {
192
+ const { input: firstInput, previous_response_id: _chain, ...carried } = params;
193
+ void _chain;
194
+ let response = await client.responses.create(params);
195
+ let history: unknown[] = toItems(firstInput);
196
+ const maxRounds = options.maxRounds ?? 10;
197
+ for (let round = 0; ; round++) {
198
+ const output = response.output ?? [];
199
+ const asking = approvalRequests(output).length > 0;
200
+ const calling = !!options.run && output.some((item) => item.type === "function_call");
201
+ if (!asking && !calling) return response;
202
+ if (round >= maxRounds) {
203
+ throw new Error(`The run was still asking for decisions after ${maxRounds} rounds. Raise maxRounds if that is expected.`);
204
+ }
205
+ const { responses } = await answerPerplexityApprovals(output, options);
206
+ const results = options.run ? await runPerplexityFunctionCalls(output, options.run, options) : [];
207
+ const answers = [...responses, ...results];
208
+ if (options.replay) {
209
+ history = [...history, ...output, ...answers];
210
+ response = await client.responses.create({ ...carried, input: history });
211
+ } else {
212
+ response = await client.responses.create({ ...carried, input: answers, previous_response_id: response.id });
213
+ }
214
+ }
215
+ }
216
+
217
+ function approvalRequests(output: readonly { type?: string }[] | null | undefined): PerplexityApprovalRequest[] {
218
+ return (output ?? []).filter(
219
+ (item): item is PerplexityApprovalRequest => item.type === "mcp_approval_request" && !!(item as PerplexityApprovalRequest).id
220
+ );
221
+ }
222
+
223
+ function toItems(input: unknown): unknown[] {
224
+ if (input === undefined || input === null) return [];
225
+ if (typeof input === "string") return [{ type: "message", role: "user", content: input }];
226
+ return Array.isArray(input) ? [...input] : [input];
227
+ }
228
+
229
+ function parseArguments(raw: string | undefined): unknown {
230
+ if (!raw) return {};
231
+ try {
232
+ return JSON.parse(raw);
233
+ } catch {
234
+ return raw;
235
+ }
236
+ }
@@ -9,7 +9,7 @@ import type { ApprovalFactor, ApprovalRisk, Decision, FieldChange } from "../typ
9
9
  * The adapters are written against each framework's own hook — the Claude
10
10
  * Agent SDK's `canUseTool`, the AI SDK's `toolApproval`, the OpenAI Agents
11
11
  * SDK's interruptions, LangGraph's `interrupt`, Mastra's suspended tool
12
- * approvals, the function calls in a Muse Spark response — by shape rather than by
12
+ * approvals, OpenRouter's `PermissionRequest` hook and paused calls, the function calls in a Muse Spark response — by shape rather than by
13
13
  * import, so `@deliverd/sdk` keeps its promise of no dependencies. Each
14
14
  * shape was taken from that framework's published type definitions and is
15
15
  * checked against them in this package's tests.
package/src/governance.ts CHANGED
@@ -18,6 +18,7 @@ import type {
18
18
  GovernanceSummaryInput,
19
19
  IctRegister,
20
20
  ListIncidentsInput,
21
+ UsePolicy,
21
22
  ModelChangeInput,
22
23
  ModelChangeResult,
23
24
  RegisterAiSystemInput,
@@ -192,6 +193,15 @@ export class AiGovernance {
192
193
  return this.http.request<IctRegister>({ method: "GET", path: "/governance/ict-register", signal });
193
194
  }
194
195
 
196
+ /**
197
+ * The AI use policy: which data may go into which kind of AI tool. Read
198
+ * only; a person changes it in the app (Governance → AI use policy).
199
+ */
200
+ async aiUsePolicy(signal?: AbortSignal): Promise<UsePolicy> {
201
+ const { policy } = await this.http.request<{ policy: UsePolicy }>({ method: "GET", path: "/governance/ai-use-policy", signal });
202
+ return policy;
203
+ }
204
+
195
205
  /** The organisation's AI governance in counts, optionally narrowed. Never a compliance percentage. */
196
206
  summary(input: GovernanceSummaryInput = {}, signal?: AbortSignal): Promise<GovernanceSummary> {
197
207
  return this.http.request<GovernanceSummary>({