sarvam-agents-client 0.5.0 → 0.5.2
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.
- package/dist/compat/core/agents.d.ts +53 -0
- package/dist/compat/core/agents.js +338 -0
- package/dist/compat/core/data.d.ts +10 -0
- package/dist/compat/core/data.js +275 -0
- package/dist/compat/core/errors.d.ts +37 -0
- package/dist/compat/core/errors.js +155 -0
- package/dist/compat/core/events.d.ts +107 -0
- package/dist/compat/core/events.js +160 -0
- package/dist/compat/core/files.d.ts +65 -0
- package/dist/compat/core/files.js +851 -0
- package/dist/compat/core/history.d.ts +9 -0
- package/dist/compat/core/history.js +112 -0
- package/dist/compat/core/http.d.ts +112 -0
- package/dist/compat/core/http.js +753 -0
- package/dist/compat/core/ids.d.ts +4 -0
- package/dist/compat/core/ids.js +36 -0
- package/dist/compat/core/index.d.ts +14 -0
- package/dist/compat/core/index.js +30 -0
- package/dist/compat/core/models.d.ts +20 -0
- package/dist/compat/core/models.js +75 -0
- package/dist/compat/core/paging.d.ts +14 -0
- package/dist/compat/core/paging.js +124 -0
- package/dist/compat/core/refusals.d.ts +9 -0
- package/dist/compat/core/refusals.js +25 -0
- package/dist/compat/core/sessions.d.ts +65 -0
- package/dist/compat/core/sessions.js +317 -0
- package/dist/compat/core/toolResults.d.ts +43 -0
- package/dist/compat/core/toolResults.js +208 -0
- package/dist/compat/core/turns.d.ts +104 -0
- package/dist/compat/core/turns.js +504 -0
- package/dist/compat/core/warnings.d.ts +6 -0
- package/dist/compat/core/warnings.js +26 -0
- package/dist/compat/index.d.ts +3 -0
- package/dist/compat/index.js +9 -0
- package/dist/compat/openai/client.d.ts +62 -0
- package/dist/compat/openai/client.js +108 -0
- package/dist/compat/openai/errors.d.ts +72 -0
- package/dist/compat/openai/errors.js +150 -0
- package/dist/compat/openai/index.d.ts +14 -0
- package/dist/compat/openai/index.js +42 -0
- package/dist/compat/openai/pages.d.ts +19 -0
- package/dist/compat/openai/pages.js +39 -0
- package/dist/compat/openai/resources/agents.d.ts +36 -0
- package/dist/compat/openai/resources/agents.js +549 -0
- package/dist/compat/openai/resources/events.d.ts +23 -0
- package/dist/compat/openai/resources/events.js +485 -0
- package/dist/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/compat/openai/resources/sessions.js +283 -0
- package/dist/compat/openai/stream.d.ts +40 -0
- package/dist/compat/openai/stream.js +585 -0
- package/dist/compat/openai/types.d.ts +125 -0
- package/dist/compat/openai/types.js +98 -0
- package/dist/compose/agent.d.ts +2 -0
- package/dist/compose/agent.js +27 -0
- package/dist/compose/functionTool.d.ts +2 -0
- package/dist/compose/functionTool.js +46 -0
- package/dist/compose/output.d.ts +2 -0
- package/dist/compose/output.js +15 -7
- package/dist/esm/compat/core/agents.d.ts +53 -0
- package/dist/esm/compat/core/agents.js +334 -0
- package/dist/esm/compat/core/data.d.ts +10 -0
- package/dist/esm/compat/core/data.js +272 -0
- package/dist/esm/compat/core/errors.d.ts +37 -0
- package/dist/esm/compat/core/errors.js +146 -0
- package/dist/esm/compat/core/events.d.ts +107 -0
- package/dist/esm/compat/core/events.js +156 -0
- package/dist/esm/compat/core/files.d.ts +65 -0
- package/dist/esm/compat/core/files.js +829 -0
- package/dist/esm/compat/core/history.d.ts +9 -0
- package/dist/esm/compat/core/history.js +109 -0
- package/dist/esm/compat/core/http.d.ts +112 -0
- package/dist/esm/compat/core/http.js +746 -0
- package/dist/esm/compat/core/ids.d.ts +4 -0
- package/dist/esm/compat/core/ids.js +30 -0
- package/dist/esm/compat/core/index.d.ts +14 -0
- package/dist/esm/compat/core/index.js +14 -0
- package/dist/esm/compat/core/models.d.ts +20 -0
- package/dist/esm/compat/core/models.js +71 -0
- package/dist/esm/compat/core/paging.d.ts +14 -0
- package/dist/esm/compat/core/paging.js +118 -0
- package/dist/esm/compat/core/refusals.d.ts +9 -0
- package/dist/esm/compat/core/refusals.js +21 -0
- package/dist/esm/compat/core/sessions.d.ts +65 -0
- package/dist/esm/compat/core/sessions.js +312 -0
- package/dist/esm/compat/core/toolResults.d.ts +43 -0
- package/dist/esm/compat/core/toolResults.js +203 -0
- package/dist/esm/compat/core/turns.d.ts +104 -0
- package/dist/esm/compat/core/turns.js +497 -0
- package/dist/esm/compat/core/warnings.d.ts +6 -0
- package/dist/esm/compat/core/warnings.js +20 -0
- package/dist/esm/compat/index.d.ts +3 -0
- package/dist/esm/compat/index.js +3 -0
- package/dist/esm/compat/openai/client.d.ts +62 -0
- package/dist/esm/compat/openai/client.js +104 -0
- package/dist/esm/compat/openai/errors.d.ts +72 -0
- package/dist/esm/compat/openai/errors.js +130 -0
- package/dist/esm/compat/openai/index.d.ts +14 -0
- package/dist/esm/compat/openai/index.js +17 -0
- package/dist/esm/compat/openai/pages.d.ts +19 -0
- package/dist/esm/compat/openai/pages.js +35 -0
- package/dist/esm/compat/openai/resources/agents.d.ts +36 -0
- package/dist/esm/compat/openai/resources/agents.js +540 -0
- package/dist/esm/compat/openai/resources/events.d.ts +23 -0
- package/dist/esm/compat/openai/resources/events.js +479 -0
- package/dist/esm/compat/openai/resources/sessions.d.ts +33 -0
- package/dist/esm/compat/openai/resources/sessions.js +278 -0
- package/dist/esm/compat/openai/stream.d.ts +40 -0
- package/dist/esm/compat/openai/stream.js +579 -0
- package/dist/esm/compat/openai/types.d.ts +125 -0
- package/dist/esm/compat/openai/types.js +91 -0
- package/dist/esm/compose/agent.d.ts +2 -0
- package/dist/esm/compose/agent.js +28 -2
- package/dist/esm/compose/functionTool.d.ts +2 -0
- package/dist/esm/compose/functionTool.js +45 -0
- package/dist/esm/compose/output.d.ts +2 -0
- package/dist/esm/compose/output.js +14 -7
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -1
- package/package.json +53 -11
- package/src/compat/core/agents.ts +437 -0
- package/src/compat/core/data.ts +283 -0
- package/src/compat/core/errors.ts +162 -0
- package/src/compat/core/events.ts +198 -0
- package/src/compat/core/files.ts +913 -0
- package/src/compat/core/history.ts +116 -0
- package/src/compat/core/http.ts +827 -0
- package/src/compat/core/ids.ts +35 -0
- package/src/compat/core/index.ts +14 -0
- package/src/compat/core/models.ts +85 -0
- package/src/compat/core/paging.ts +119 -0
- package/src/compat/core/refusals.ts +31 -0
- package/src/compat/core/sessions.ts +358 -0
- package/src/compat/core/toolResults.ts +235 -0
- package/src/compat/core/turns.ts +622 -0
- package/src/compat/core/warnings.ts +23 -0
- package/src/compat/index.ts +3 -0
- package/src/compat/openai/client.ts +177 -0
- package/src/compat/openai/errors.ts +165 -0
- package/src/compat/openai/index.ts +65 -0
- package/src/compat/openai/pages.ts +55 -0
- package/src/compat/openai/resources/agents.ts +603 -0
- package/src/compat/openai/resources/events.ts +523 -0
- package/src/compat/openai/resources/sessions.ts +369 -0
- package/src/compat/openai/stream.ts +599 -0
- package/src/compat/openai/types.ts +217 -0
- package/src/compose/agent.ts +30 -3
- package/src/compose/functionTool.ts +44 -0
- package/src/compose/output.ts +14 -8
- package/src/index.ts +3 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Deterministic IDs shared across live streams and stored history. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
export const ENVIRONMENT_ID = "env_sarvam_default";
|
|
5
|
+
|
|
6
|
+
const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
|
|
7
|
+
|
|
8
|
+
function toBase32(bytes: Uint8Array): string {
|
|
9
|
+
let out = "";
|
|
10
|
+
let bits = 0;
|
|
11
|
+
let value = 0;
|
|
12
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
13
|
+
value = (value << 8) | bytes[i];
|
|
14
|
+
bits += 8;
|
|
15
|
+
while (bits >= 5) {
|
|
16
|
+
out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
|
17
|
+
bits -= 5;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function itemId(responseId: string, partIndex: number): string {
|
|
25
|
+
return `${responseId}:${partIndex}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function eventId(responseId: string, partIndex: number, kind: string): string {
|
|
29
|
+
const digest = createHash("sha256").update(`${responseId}|${partIndex}|${kind}`, "utf8").digest();
|
|
30
|
+
return `evt_${toBase32(digest).slice(0, 26)}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function inlineAgentName(fingerprintHex: string): string {
|
|
34
|
+
return `sdk-inline-${fingerprintHex.slice(0, 12)}`;
|
|
35
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Provider-neutral translation core for sarvam-agents-client/compat. */
|
|
2
|
+
export * from "./errors.js";
|
|
3
|
+
export * from "./refusals.js";
|
|
4
|
+
export * from "./warnings.js";
|
|
5
|
+
export * from "./http.js";
|
|
6
|
+
export * from "./models.js";
|
|
7
|
+
export * from "./ids.js";
|
|
8
|
+
export * from "./paging.js";
|
|
9
|
+
export * from "./agents.js";
|
|
10
|
+
export * from "./sessions.js";
|
|
11
|
+
export * from "./events.js";
|
|
12
|
+
export * from "./turns.js";
|
|
13
|
+
export * from "./toolResults.js";
|
|
14
|
+
export * from "./history.js";
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Model catalog lookup and provider-model substitution (R2). */
|
|
2
|
+
import { ModelsApi } from "../../apis/ModelsApi.js";
|
|
3
|
+
import { Http } from "./http.js";
|
|
4
|
+
import { refuse } from "./refusals.js";
|
|
5
|
+
import { warnOnce } from "./warnings.js";
|
|
6
|
+
|
|
7
|
+
const PROVIDER_MODEL_RE = /^(gpt-|o\d|chatgpt-|claude-)/i;
|
|
8
|
+
|
|
9
|
+
export interface ResolvedModel {
|
|
10
|
+
sarvamId: string | null;
|
|
11
|
+
requested: string | null;
|
|
12
|
+
substituted: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function envModelMap(): Record<string, string> {
|
|
16
|
+
const raw = typeof process !== "undefined" ? process.env["SARVAM_MODEL_MAP"] : undefined;
|
|
17
|
+
if (!raw) return {};
|
|
18
|
+
try {
|
|
19
|
+
const parsed = JSON.parse(raw);
|
|
20
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
21
|
+
const out: Record<string, string> = {};
|
|
22
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
23
|
+
if (typeof v === "string") out[k] = v;
|
|
24
|
+
}
|
|
25
|
+
return out;
|
|
26
|
+
} catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class ModelResolver {
|
|
32
|
+
private readonly map: Record<string, string>;
|
|
33
|
+
private readonly strict: boolean;
|
|
34
|
+
private readonly provider: string;
|
|
35
|
+
private catalog: Set<string> | null = null;
|
|
36
|
+
|
|
37
|
+
constructor(
|
|
38
|
+
private readonly http: Http,
|
|
39
|
+
opts: { modelMap?: Record<string, string>; strict?: boolean; provider?: string } = {},
|
|
40
|
+
) {
|
|
41
|
+
this.map = opts.modelMap ? { ...opts.modelMap } : envModelMap();
|
|
42
|
+
this.strict = opts.strict ?? false;
|
|
43
|
+
this.provider = opts.provider ?? "openai";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private async getCatalog(): Promise<Set<string>> {
|
|
47
|
+
if (this.catalog === null) {
|
|
48
|
+
const resp = await this.http.call(() => new ModelsApi(this.http.sdkConfig).listModels(), { idempotent: true });
|
|
49
|
+
const names = new Set<string>();
|
|
50
|
+
for (const m of resp.data ?? []) {
|
|
51
|
+
if (typeof m.name === "string" && m.name) names.add(m.name);
|
|
52
|
+
}
|
|
53
|
+
this.catalog = names;
|
|
54
|
+
}
|
|
55
|
+
return this.catalog;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async resolve(requested: string | null | undefined): Promise<ResolvedModel> {
|
|
59
|
+
if (requested === null || requested === undefined) {
|
|
60
|
+
return { sarvamId: null, requested: null, substituted: false };
|
|
61
|
+
}
|
|
62
|
+
if (Object.prototype.hasOwnProperty.call(this.map, requested)) {
|
|
63
|
+
return { sarvamId: this.map[requested], requested, substituted: false };
|
|
64
|
+
}
|
|
65
|
+
const catalog = await this.getCatalog();
|
|
66
|
+
if (catalog.has(requested)) {
|
|
67
|
+
return { sarvamId: requested, requested, substituted: false };
|
|
68
|
+
}
|
|
69
|
+
if (PROVIDER_MODEL_RE.test(requested)) {
|
|
70
|
+
if (this.strict) {
|
|
71
|
+
refuse(this.provider, "model", {
|
|
72
|
+
reason: `model ${JSON.stringify(requested)} is not in the Sarvam catalog (strictModels=true)`,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
warnOnce(
|
|
76
|
+
"model_substituted",
|
|
77
|
+
`Provider model ${JSON.stringify(requested)} is running on the Sarvam default model; pass a Sarvam model ID or set modelMap / SARVAM_MODEL_MAP.`,
|
|
78
|
+
);
|
|
79
|
+
return { sarvamId: null, requested, substituted: true };
|
|
80
|
+
}
|
|
81
|
+
refuse(this.provider, "model", {
|
|
82
|
+
reason: `unknown model ${JSON.stringify(requested)} is not in the Sarvam model catalog`,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Cursor pagination and opaque page tokens over Panja's offset lists. */
|
|
2
|
+
import { CoreAPIError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
const LIMIT_MIN = 1;
|
|
5
|
+
const LIMIT_MAX = 100;
|
|
6
|
+
const BATCH_SIZE = 100;
|
|
7
|
+
|
|
8
|
+
export function encodePageToken(offset: number): string {
|
|
9
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
10
|
+
throw new CoreAPIError("page offset must be >= 0", {
|
|
11
|
+
status: 400,
|
|
12
|
+
code: "invalid_request_error",
|
|
13
|
+
param: "page",
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return Buffer.from(`o:${offset}`, "utf8").toString("base64");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function decodePageToken(token: string): number {
|
|
20
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(token) || token.length % 4 !== 0) {
|
|
21
|
+
throw new CoreAPIError("Invalid page token", { status: 400, code: "invalid_request_error", param: "page" });
|
|
22
|
+
}
|
|
23
|
+
const raw = Buffer.from(token, "base64").toString("utf8");
|
|
24
|
+
if (!raw.startsWith("o:")) {
|
|
25
|
+
throw new CoreAPIError("Invalid page token", { status: 400, code: "invalid_request_error", param: "page" });
|
|
26
|
+
}
|
|
27
|
+
const numStr = raw.slice(2);
|
|
28
|
+
if (!/^\d+$/.test(numStr)) {
|
|
29
|
+
throw new CoreAPIError("Invalid page token", { status: 400, code: "invalid_request_error", param: "page" });
|
|
30
|
+
}
|
|
31
|
+
return Number(numStr);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class CursorPager<T> {
|
|
35
|
+
constructor(
|
|
36
|
+
private readonly fetch: (offset: number, limit: number) => Promise<[T[], boolean]>,
|
|
37
|
+
private readonly idOf: (item: T) => string,
|
|
38
|
+
) {}
|
|
39
|
+
|
|
40
|
+
async page(opts: { after?: string; limit?: number; order?: string } = {}): Promise<[T[], boolean]> {
|
|
41
|
+
const limit = opts.limit ?? 20;
|
|
42
|
+
const order = opts.order ?? "desc";
|
|
43
|
+
const after = opts.after;
|
|
44
|
+
if (!Number.isInteger(limit) || limit < LIMIT_MIN || limit > LIMIT_MAX) {
|
|
45
|
+
throw new CoreAPIError(`limit must be an integer between ${LIMIT_MIN} and ${LIMIT_MAX}`, {
|
|
46
|
+
status: 400,
|
|
47
|
+
code: "invalid_request_error",
|
|
48
|
+
param: "limit",
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
if (order !== "asc" && order !== "desc") {
|
|
52
|
+
throw new CoreAPIError("order must be 'asc' or 'desc'", {
|
|
53
|
+
status: 400,
|
|
54
|
+
code: "invalid_request_error",
|
|
55
|
+
param: "order",
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (order === "asc") {
|
|
60
|
+
const all = await this.fetchAll();
|
|
61
|
+
all.reverse();
|
|
62
|
+
return this.sliceAfter(all, after, limit);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let foundAfter = after === undefined;
|
|
66
|
+
const collected: T[] = [];
|
|
67
|
+
let offset = 0;
|
|
68
|
+
for (;;) {
|
|
69
|
+
const batchLimit = after !== undefined ? Math.max(limit + 1, BATCH_SIZE) : Math.min(limit + 1, BATCH_SIZE);
|
|
70
|
+
const [items, hasMore] = await this.fetch(offset, batchLimit);
|
|
71
|
+
if (items.length === 0) break;
|
|
72
|
+
for (const item of items) {
|
|
73
|
+
if (!foundAfter) {
|
|
74
|
+
if (this.idOf(item) === after) foundAfter = true;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
collected.push(item);
|
|
78
|
+
if (collected.length > limit) return [collected.slice(0, limit), true];
|
|
79
|
+
}
|
|
80
|
+
offset += items.length;
|
|
81
|
+
if (!hasMore) break;
|
|
82
|
+
}
|
|
83
|
+
if (!foundAfter) {
|
|
84
|
+
throw new CoreAPIError(`No item found with id ${JSON.stringify(after)} for 'after' cursor.`, {
|
|
85
|
+
status: 400,
|
|
86
|
+
code: "invalid_request_error",
|
|
87
|
+
param: "after",
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return [collected.slice(0, limit), collected.length > limit];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
private async fetchAll(): Promise<T[]> {
|
|
94
|
+
const out: T[] = [];
|
|
95
|
+
let offset = 0;
|
|
96
|
+
for (;;) {
|
|
97
|
+
const [items, hasMore] = await this.fetch(offset, BATCH_SIZE);
|
|
98
|
+
if (items.length === 0) break;
|
|
99
|
+
out.push(...items);
|
|
100
|
+
offset += items.length;
|
|
101
|
+
if (!hasMore) break;
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private sliceAfter(items: T[], after: string | undefined, limit: number): [T[], boolean] {
|
|
107
|
+
if (after === undefined) return [items.slice(0, limit), items.length > limit];
|
|
108
|
+
const idx = items.findIndex((x) => this.idOf(x) === after);
|
|
109
|
+
if (idx === -1) {
|
|
110
|
+
throw new CoreAPIError(`No item found with id ${JSON.stringify(after)} for 'after' cursor.`, {
|
|
111
|
+
status: 400,
|
|
112
|
+
code: "invalid_request_error",
|
|
113
|
+
param: "after",
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const rest = items.slice(idx + 1);
|
|
117
|
+
return [rest.slice(0, limit), rest.length > limit];
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** Local refusals backed by bundled shared/compat/refusals.json. */
|
|
2
|
+
import { REFUSALS, type RefusalSpec } from "./data.js";
|
|
3
|
+
import { Unsupported } from "./errors.js";
|
|
4
|
+
|
|
5
|
+
const byKey = new Map<string, RefusalSpec>();
|
|
6
|
+
for (const r of REFUSALS) {
|
|
7
|
+
byKey.set(`${r.provider}:${r.path}`, r);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function formatRefusalMessage(path: string, reason: string, hint?: string): string {
|
|
11
|
+
const base = `${path}: not supported by Sarvam (${reason}).`;
|
|
12
|
+
return hint ? `${base} ${hint}` : base;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RefuseOverrides {
|
|
16
|
+
reason?: string;
|
|
17
|
+
hint?: string;
|
|
18
|
+
param?: string | null;
|
|
19
|
+
feature?: string;
|
|
20
|
+
needs?: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function refuse(provider: string, path: string, overrides: RefuseOverrides = {}): never {
|
|
24
|
+
const entry = byKey.get(`${provider}:${path}`);
|
|
25
|
+
const reason = overrides.reason ?? entry?.reason ?? "unsupported field";
|
|
26
|
+
const hint = overrides.hint !== undefined ? overrides.hint : (entry?.hint ?? "");
|
|
27
|
+
const param = overrides.param !== undefined ? overrides.param : (entry?.param ?? path.split("=")[0]);
|
|
28
|
+
const feature = overrides.feature ?? entry?.feature ?? `${provider}.unsupported.${param ?? path}`;
|
|
29
|
+
const needs = overrides.needs !== undefined ? overrides.needs : (entry?.needs ?? null);
|
|
30
|
+
throw new Unsupported(formatRefusalMessage(path, reason, hint), { param, feature, needs });
|
|
31
|
+
}
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/** Core Sessions service: neutral SessionRecord <-> Panja API conversations. */
|
|
2
|
+
import { ConversationsApi } from "../../apis/ConversationsApi.js";
|
|
3
|
+
import type { FunctionCallRequest } from "../../compose/events.js";
|
|
4
|
+
import { CoreAPIError } from "./errors.js";
|
|
5
|
+
import { Http } from "./http.js";
|
|
6
|
+
|
|
7
|
+
export type SessionStatus = "idle" | "running" | "requires_action" | "failed";
|
|
8
|
+
|
|
9
|
+
export interface PendingStep {
|
|
10
|
+
requestId: string;
|
|
11
|
+
responseId: string;
|
|
12
|
+
kind: "function" | "clarify";
|
|
13
|
+
calls: FunctionCallRequest[];
|
|
14
|
+
questions: Record<string, unknown>[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SessionRecord {
|
|
18
|
+
id: string;
|
|
19
|
+
agentId: string | null;
|
|
20
|
+
metadata: Record<string, string>;
|
|
21
|
+
title: string | null;
|
|
22
|
+
status: SessionStatus;
|
|
23
|
+
activeResponseId: string | null;
|
|
24
|
+
required: PendingStep[];
|
|
25
|
+
createdAt: string;
|
|
26
|
+
archived: boolean;
|
|
27
|
+
rawMetadata: Record<string, unknown>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isObj(v: unknown): v is Record<string, unknown> {
|
|
31
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function clone<T>(v: T): T {
|
|
35
|
+
return JSON.parse(JSON.stringify(v)) as T;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function iso(v: unknown): string {
|
|
39
|
+
if (v instanceof Date) return v.toISOString();
|
|
40
|
+
if (typeof v === "string" && v) return v;
|
|
41
|
+
return new Date().toISOString();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function extractCompat(rawMeta: unknown): { metadata: Record<string, string>; title: string | null; archived: boolean } {
|
|
45
|
+
if (!isObj(rawMeta)) return { metadata: {}, title: null, archived: false };
|
|
46
|
+
const compat = rawMeta["sdk_compat"];
|
|
47
|
+
if (isObj(compat)) {
|
|
48
|
+
const um = isObj(compat["metadata"]) ? compat["metadata"] : {};
|
|
49
|
+
const out: Record<string, string> = {};
|
|
50
|
+
for (const [k, v] of Object.entries(um)) out[k] = String(v);
|
|
51
|
+
const title = typeof compat["title"] === "string" ? compat["title"] : null;
|
|
52
|
+
const archived = Boolean(compat["archived"]);
|
|
53
|
+
return { metadata: out, title, archived };
|
|
54
|
+
}
|
|
55
|
+
const out: Record<string, string> = {};
|
|
56
|
+
for (const [k, v] of Object.entries(rawMeta)) {
|
|
57
|
+
if (k !== "sdk_compat" && typeof v === "string") out[k] = v;
|
|
58
|
+
}
|
|
59
|
+
return { metadata: out, title: null, archived: false };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseRequiredActions(actions: unknown, responseId: string): PendingStep[] {
|
|
63
|
+
if (!Array.isArray(actions) || actions.length === 0) return [];
|
|
64
|
+
const fnGroups = new Map<string, FunctionCallRequest[]>();
|
|
65
|
+
const clarifySteps: PendingStep[] = [];
|
|
66
|
+
for (const a of actions) {
|
|
67
|
+
if (!isObj(a)) continue;
|
|
68
|
+
const aType = String(a["type"] ?? "function_call");
|
|
69
|
+
const reqId = String(a["requestId"] ?? a["request_id"] ?? "");
|
|
70
|
+
if (aType === "clarify") {
|
|
71
|
+
const questions = Array.isArray(a["questions"]) ? (a["questions"] as Record<string, unknown>[]) : [];
|
|
72
|
+
clarifySteps.push({ requestId: reqId, responseId, kind: "clarify", calls: [], questions });
|
|
73
|
+
} else {
|
|
74
|
+
const callId = String(a["toolCallId"] ?? a["tool_call_id"] ?? "");
|
|
75
|
+
const name = String(a["name"] ?? "");
|
|
76
|
+
const args = isObj(a["arguments"]) ? a["arguments"] : {};
|
|
77
|
+
const list = fnGroups.get(reqId) ?? [];
|
|
78
|
+
list.push({ callId, name, arguments: args });
|
|
79
|
+
fnGroups.set(reqId, list);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const steps: PendingStep[] = [];
|
|
83
|
+
for (const [requestId, calls] of fnGroups.entries()) {
|
|
84
|
+
steps.push({ requestId, responseId, kind: "function", calls, questions: [] });
|
|
85
|
+
}
|
|
86
|
+
steps.push(...clarifySteps);
|
|
87
|
+
return steps;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function detectPendingClarifyFromMessages(msgs: unknown, responseId: string): PendingStep[] {
|
|
91
|
+
if (!Array.isArray(msgs) || msgs.length === 0) return [];
|
|
92
|
+
const last = msgs[msgs.length - 1];
|
|
93
|
+
if (!isObj(last) || last["role"] !== "assistant") return [];
|
|
94
|
+
const parts = last["parts"];
|
|
95
|
+
if (!Array.isArray(parts) || parts.length === 0) return [];
|
|
96
|
+
let clarifyIdx = -1;
|
|
97
|
+
let clarifyPart: Record<string, unknown> | null = null;
|
|
98
|
+
for (let i = 0; i < parts.length; i++) {
|
|
99
|
+
const p = parts[i];
|
|
100
|
+
if (isObj(p) && p["type"] === "data-clarify-request") {
|
|
101
|
+
clarifyIdx = i;
|
|
102
|
+
clarifyPart = p;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!clarifyPart) return [];
|
|
106
|
+
for (const p of parts.slice(clarifyIdx + 1)) {
|
|
107
|
+
if (!isObj(p)) continue;
|
|
108
|
+
const pt = p["type"];
|
|
109
|
+
if (pt === "reasoning" || pt === "step-start") continue;
|
|
110
|
+
if (pt === "data-output" && isObj(p["data"]) && p["data"]["skipped"] === "paused") continue;
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
const data = isObj(clarifyPart["data"]) ? clarifyPart["data"] : {};
|
|
114
|
+
const reqId = String(data["requestId"] ?? clarifyPart["id"] ?? "");
|
|
115
|
+
const questions = Array.isArray(data["questions"]) ? (data["questions"] as Record<string, unknown>[]) : [];
|
|
116
|
+
return [{ requestId: reqId, responseId, kind: "clarify", calls: [], questions }];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function toRecord(conv: unknown): SessionRecord {
|
|
120
|
+
const c = (conv ?? {}) as Record<string, unknown>;
|
|
121
|
+
const rawMetadata = isObj(c["metadata"]) ? clone(c["metadata"]) : {};
|
|
122
|
+
const { metadata, title: compatTitle, archived } = extractCompat(rawMetadata);
|
|
123
|
+
const title = (typeof c["title"] === "string" && c["title"]) ? c["title"] : compatTitle;
|
|
124
|
+
const activeId = typeof c["activeResponseId"] === "string" && c["activeResponseId"] ? c["activeResponseId"] : null;
|
|
125
|
+
const agentIdRaw = c["targetAgentId"] ?? c["targetId"];
|
|
126
|
+
const agentId = typeof agentIdRaw === "string" && agentIdRaw ? agentIdRaw : null;
|
|
127
|
+
let lastMsgId = activeId ?? "";
|
|
128
|
+
const msgs = c["messages"];
|
|
129
|
+
if (!lastMsgId && Array.isArray(msgs)) {
|
|
130
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
131
|
+
const m = msgs[i];
|
|
132
|
+
if (isObj(m) && m["role"] === "assistant" && typeof m["id"] === "string") {
|
|
133
|
+
lastMsgId = m["id"];
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
let required = parseRequiredActions(c["requiredActions"], lastMsgId);
|
|
139
|
+
if (required.length === 0) {
|
|
140
|
+
required = detectPendingClarifyFromMessages(msgs, lastMsgId);
|
|
141
|
+
}
|
|
142
|
+
const status: SessionStatus = required.length > 0 ? "requires_action" : activeId ? "running" : "idle";
|
|
143
|
+
return {
|
|
144
|
+
id: String(c["id"] ?? ""),
|
|
145
|
+
agentId,
|
|
146
|
+
metadata,
|
|
147
|
+
title: title ?? null,
|
|
148
|
+
status,
|
|
149
|
+
activeResponseId: activeId,
|
|
150
|
+
required,
|
|
151
|
+
createdAt: iso(c["createdAt"]),
|
|
152
|
+
archived,
|
|
153
|
+
rawMetadata,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export class SessionUpdateQueue {
|
|
158
|
+
private readonly tails = new Map<string, Promise<void>>();
|
|
159
|
+
|
|
160
|
+
async run<T>(sessionId: string, fn: () => Promise<T>): Promise<T> {
|
|
161
|
+
const prev = this.tails.get(sessionId) ?? Promise.resolve();
|
|
162
|
+
let release!: () => void;
|
|
163
|
+
const gate = new Promise<void>((resolve) => {
|
|
164
|
+
release = resolve;
|
|
165
|
+
});
|
|
166
|
+
const tail = prev.then(() => gate, () => gate);
|
|
167
|
+
this.tails.set(sessionId, tail);
|
|
168
|
+
await prev.catch(() => {});
|
|
169
|
+
try {
|
|
170
|
+
return await fn();
|
|
171
|
+
} finally {
|
|
172
|
+
release();
|
|
173
|
+
if (this.tails.get(sessionId) === tail) {
|
|
174
|
+
this.tails.delete(sessionId);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export class Sessions {
|
|
181
|
+
private readonly api: ConversationsApi;
|
|
182
|
+
private readonly provider: string;
|
|
183
|
+
private readonly updateQueue: SessionUpdateQueue;
|
|
184
|
+
|
|
185
|
+
constructor(private readonly http: Http, opts: { provider?: string; updateQueue?: SessionUpdateQueue } = {}) {
|
|
186
|
+
this.api = new ConversationsApi(http.sdkConfig);
|
|
187
|
+
this.provider = opts.provider ?? "openai";
|
|
188
|
+
this.updateQueue = opts.updateQueue ?? new SessionUpdateQueue();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async create(opts: {
|
|
192
|
+
agentId: string;
|
|
193
|
+
metadata?: Record<string, string>;
|
|
194
|
+
title?: string;
|
|
195
|
+
provider?: string;
|
|
196
|
+
}): Promise<SessionRecord> {
|
|
197
|
+
const sdkCompat: Record<string, unknown> = {
|
|
198
|
+
provider: opts.provider ?? this.provider,
|
|
199
|
+
metadata: Object.fromEntries(Object.entries(opts.metadata ?? {}).map(([k, v]) => [k, String(v)])),
|
|
200
|
+
archived: false,
|
|
201
|
+
};
|
|
202
|
+
if (opts.title !== undefined) sdkCompat["title"] = opts.title;
|
|
203
|
+
// POST /v1/conversations is not deduplicated server-side by Idempotency-Key; never auto-retry.
|
|
204
|
+
const conv = await this.http.call(
|
|
205
|
+
() => this.api.createConversation({
|
|
206
|
+
createConversationBody: {
|
|
207
|
+
agentId: opts.agentId,
|
|
208
|
+
title: opts.title,
|
|
209
|
+
metadata: { sdk_compat: sdkCompat },
|
|
210
|
+
},
|
|
211
|
+
}),
|
|
212
|
+
{ idempotent: false },
|
|
213
|
+
);
|
|
214
|
+
return toRecord(conv);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async retrieve(sessionId: string): Promise<SessionRecord> {
|
|
218
|
+
const conv = await this.http.call(
|
|
219
|
+
() => this.api.getConversation({ conversationId: sessionId }),
|
|
220
|
+
{ idempotent: true },
|
|
221
|
+
);
|
|
222
|
+
return toRecord(conv);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async update(
|
|
226
|
+
sessionId: string,
|
|
227
|
+
opts: { metadata?: Record<string, string | null>; title?: string },
|
|
228
|
+
): Promise<SessionRecord> {
|
|
229
|
+
return this.updateQueue.run(sessionId, async () => {
|
|
230
|
+
const current = await this.retrieve(sessionId);
|
|
231
|
+
const merged: Record<string, string> = { ...current.metadata };
|
|
232
|
+
if (opts.metadata) {
|
|
233
|
+
for (const [k, v] of Object.entries(opts.metadata)) {
|
|
234
|
+
if (v === null) delete merged[k];
|
|
235
|
+
else merged[k] = String(v);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
const newTitle = opts.title !== undefined ? opts.title : current.title;
|
|
239
|
+
const existingCompat = isObj(current.rawMetadata["sdk_compat"]) ? current.rawMetadata["sdk_compat"] : {};
|
|
240
|
+
const sdkCompat: Record<string, unknown> = {
|
|
241
|
+
provider: typeof existingCompat["provider"] === "string" ? existingCompat["provider"] : this.provider,
|
|
242
|
+
metadata: merged,
|
|
243
|
+
archived: current.archived,
|
|
244
|
+
};
|
|
245
|
+
if (newTitle !== null) sdkCompat["title"] = newTitle;
|
|
246
|
+
const fullMeta = clone(current.rawMetadata);
|
|
247
|
+
fullMeta["sdk_compat"] = sdkCompat;
|
|
248
|
+
const conv = await this.http.call(
|
|
249
|
+
() => this.api.updateConversation({
|
|
250
|
+
conversationId: sessionId,
|
|
251
|
+
updateConversationBody: {
|
|
252
|
+
title: newTitle ?? undefined,
|
|
253
|
+
metadata: fullMeta,
|
|
254
|
+
},
|
|
255
|
+
}),
|
|
256
|
+
{ idempotent: true },
|
|
257
|
+
);
|
|
258
|
+
return toRecord(conv);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
async listCursor(opts: {
|
|
263
|
+
cursor?: string;
|
|
264
|
+
limit?: number;
|
|
265
|
+
agentId?: string;
|
|
266
|
+
metadata?: Record<string, string>;
|
|
267
|
+
buffered?: SessionRecord[];
|
|
268
|
+
} = {}): Promise<{ items: SessionRecord[]; nextCursor: string | null; hasMore: boolean; leftover: SessionRecord[] }> {
|
|
269
|
+
const limit = opts.limit ?? 20;
|
|
270
|
+
const matched: SessionRecord[] = opts.buffered ? [...opts.buffered] : [];
|
|
271
|
+
const filtered = opts.agentId !== undefined || opts.metadata !== undefined;
|
|
272
|
+
const target = filtered ? limit + 1 : limit;
|
|
273
|
+
let cur = opts.cursor;
|
|
274
|
+
let nextCursor: string | null = opts.cursor ?? null;
|
|
275
|
+
let moreOnServer = opts.cursor !== undefined;
|
|
276
|
+
let exhausted = opts.buffered !== undefined && opts.cursor === undefined;
|
|
277
|
+
while (matched.length < target && !exhausted) {
|
|
278
|
+
const c = cur;
|
|
279
|
+
const reqLimit = filtered ? 100 : Math.min(100, target - matched.length);
|
|
280
|
+
const page = await this.http.call(
|
|
281
|
+
() => this.api.listConversations({ limit: reqLimit, cursor: c, sessionType: "api" }),
|
|
282
|
+
{ idempotent: true },
|
|
283
|
+
);
|
|
284
|
+
const items = page.data ?? [];
|
|
285
|
+
nextCursor = page.nextCursor ?? null;
|
|
286
|
+
moreOnServer = Boolean(page.hasMore || nextCursor);
|
|
287
|
+
for (const item of items) {
|
|
288
|
+
const rec = toRecord(item);
|
|
289
|
+
if (opts.agentId !== undefined && rec.agentId !== opts.agentId) continue;
|
|
290
|
+
if (opts.metadata !== undefined) {
|
|
291
|
+
const ok = Object.entries(opts.metadata).every(([k, v]) => rec.metadata[k] === v);
|
|
292
|
+
if (!ok) continue;
|
|
293
|
+
}
|
|
294
|
+
matched.push(rec);
|
|
295
|
+
}
|
|
296
|
+
if (items.length === 0 || !nextCursor) {
|
|
297
|
+
nextCursor = null;
|
|
298
|
+
moreOnServer = false;
|
|
299
|
+
exhausted = true;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
cur = nextCursor;
|
|
303
|
+
}
|
|
304
|
+
const pageItems = matched.slice(0, limit);
|
|
305
|
+
const leftover = matched.slice(limit);
|
|
306
|
+
const hasMore = leftover.length > 0 || (!filtered && moreOnServer && nextCursor !== null);
|
|
307
|
+
return { items: pageItems, nextCursor, hasMore, leftover };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async list(
|
|
311
|
+
offset = 0,
|
|
312
|
+
limit = 20,
|
|
313
|
+
filters: { agentId?: string; metadata?: Record<string, string> } = {},
|
|
314
|
+
): Promise<[SessionRecord[], boolean]> {
|
|
315
|
+
const matched: SessionRecord[] = [];
|
|
316
|
+
let cursor: string | undefined;
|
|
317
|
+
const target = offset + limit + 1;
|
|
318
|
+
while (matched.length < target) {
|
|
319
|
+
const c = cursor;
|
|
320
|
+
const page = await this.http.call(
|
|
321
|
+
() => this.api.listConversations({ limit: 100, cursor: c, sessionType: "api" }),
|
|
322
|
+
{ idempotent: true },
|
|
323
|
+
);
|
|
324
|
+
const items = page.data ?? [];
|
|
325
|
+
for (const item of items) {
|
|
326
|
+
const rec = toRecord(item);
|
|
327
|
+
if (filters.agentId !== undefined && rec.agentId !== filters.agentId) continue;
|
|
328
|
+
if (filters.metadata !== undefined) {
|
|
329
|
+
const ok = Object.entries(filters.metadata).every(([k, v]) => rec.metadata[k] === v);
|
|
330
|
+
if (!ok) continue;
|
|
331
|
+
}
|
|
332
|
+
matched.push(rec);
|
|
333
|
+
}
|
|
334
|
+
const nextCursor = page.nextCursor ?? undefined;
|
|
335
|
+
if (items.length === 0 || !nextCursor) break;
|
|
336
|
+
cursor = nextCursor;
|
|
337
|
+
}
|
|
338
|
+
return [matched.slice(offset, offset + limit), matched.length > offset + limit];
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async delete(sessionId: string): Promise<void> {
|
|
342
|
+
await this.http.call(
|
|
343
|
+
() => this.api.deleteConversation({ conversationId: sessionId }),
|
|
344
|
+
{ idempotent: true },
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async ensureNotArchived(sessionId: string): Promise<SessionRecord> {
|
|
349
|
+
const rec = await this.retrieve(sessionId);
|
|
350
|
+
if (rec.archived) {
|
|
351
|
+
throw new CoreAPIError(`Session ${sessionId} is archived and cannot accept new events.`, {
|
|
352
|
+
status: 400,
|
|
353
|
+
code: "invalid_request_error",
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
return rec;
|
|
357
|
+
}
|
|
358
|
+
}
|