@realtimex/sdk 1.3.5-rc.1 → 1.3.5-rc.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/index.d.mts +512 -1
- package/dist/index.d.ts +512 -1
- package/dist/index.js +1536 -2
- package/dist/index.mjs +1511 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1713,6 +1713,1485 @@ var HttpClient = class {
|
|
|
1713
1713
|
}
|
|
1714
1714
|
};
|
|
1715
1715
|
|
|
1716
|
+
// src/core/errors/ContractErrors.ts
|
|
1717
|
+
var ContractError = class extends Error {
|
|
1718
|
+
constructor(code, message, details) {
|
|
1719
|
+
super(message);
|
|
1720
|
+
this.name = this.constructor.name;
|
|
1721
|
+
this.code = code;
|
|
1722
|
+
this.details = details;
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
var ContractValidationError = class extends ContractError {
|
|
1726
|
+
constructor(message, details) {
|
|
1727
|
+
super("contract_validation_error", message, details);
|
|
1728
|
+
}
|
|
1729
|
+
};
|
|
1730
|
+
var ToolValidationError = class extends ContractError {
|
|
1731
|
+
constructor(message, details) {
|
|
1732
|
+
super("tool_validation_error", message, details);
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
var ToolNotFoundError = class extends ContractError {
|
|
1736
|
+
constructor(toolName, details) {
|
|
1737
|
+
super("tool_not_found", `Tool not found: ${toolName}`, details);
|
|
1738
|
+
}
|
|
1739
|
+
};
|
|
1740
|
+
var ScopeDeniedError = class extends ContractError {
|
|
1741
|
+
constructor(permission, details) {
|
|
1742
|
+
super("scope_denied", `Missing required permission: ${permission}`, details);
|
|
1743
|
+
}
|
|
1744
|
+
};
|
|
1745
|
+
var RuntimeTransportError = class extends ContractError {
|
|
1746
|
+
constructor(message, statusCode, details) {
|
|
1747
|
+
super("runtime_transport_error", message, details);
|
|
1748
|
+
this.statusCode = statusCode;
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
|
|
1752
|
+
// src/core/auth/ScopeGuard.ts
|
|
1753
|
+
var ScopeGuard = class {
|
|
1754
|
+
constructor(scopes = []) {
|
|
1755
|
+
this.scopes = new Set(scopes.filter((scope) => scope.trim().length > 0));
|
|
1756
|
+
}
|
|
1757
|
+
can(permission) {
|
|
1758
|
+
if (!permission) return true;
|
|
1759
|
+
if (this.scopes.size === 0) return true;
|
|
1760
|
+
return this.scopes.has(permission);
|
|
1761
|
+
}
|
|
1762
|
+
assert(permission) {
|
|
1763
|
+
if (!permission) return;
|
|
1764
|
+
if (!this.can(permission)) {
|
|
1765
|
+
throw new ScopeDeniedError(permission);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
};
|
|
1769
|
+
|
|
1770
|
+
// src/core/contract/ContractCache.ts
|
|
1771
|
+
var ContractCache = class {
|
|
1772
|
+
constructor(ttlMs = 3e4) {
|
|
1773
|
+
this.entries = /* @__PURE__ */ new Map();
|
|
1774
|
+
this.ttlMs = ttlMs > 0 ? ttlMs : null;
|
|
1775
|
+
}
|
|
1776
|
+
get(key) {
|
|
1777
|
+
const entry = this.entries.get(key);
|
|
1778
|
+
if (!entry) return null;
|
|
1779
|
+
if (entry.expiresAt !== null && entry.expiresAt <= Date.now()) {
|
|
1780
|
+
this.entries.delete(key);
|
|
1781
|
+
return null;
|
|
1782
|
+
}
|
|
1783
|
+
return entry.value;
|
|
1784
|
+
}
|
|
1785
|
+
set(key, value) {
|
|
1786
|
+
const expiresAt = this.ttlMs === null ? null : Date.now() + this.ttlMs;
|
|
1787
|
+
this.entries.set(key, { value, expiresAt });
|
|
1788
|
+
}
|
|
1789
|
+
clear(key) {
|
|
1790
|
+
if (key) {
|
|
1791
|
+
this.entries.delete(key);
|
|
1792
|
+
return;
|
|
1793
|
+
}
|
|
1794
|
+
this.entries.clear();
|
|
1795
|
+
}
|
|
1796
|
+
};
|
|
1797
|
+
|
|
1798
|
+
// src/core/contract/ContractValidator.ts
|
|
1799
|
+
var LOCAL_APP_CONTRACT_VERSION2 = "local-app-contract/v1";
|
|
1800
|
+
var DEFAULT_SUPPORTED_EVENTS = [
|
|
1801
|
+
"task.trigger",
|
|
1802
|
+
"system.ping",
|
|
1803
|
+
"task.claimed",
|
|
1804
|
+
"task.started",
|
|
1805
|
+
"task.progress",
|
|
1806
|
+
"task.completed",
|
|
1807
|
+
"task.failed",
|
|
1808
|
+
"task.canceled"
|
|
1809
|
+
];
|
|
1810
|
+
function isRecord(value) {
|
|
1811
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1812
|
+
}
|
|
1813
|
+
function asStringArray(value) {
|
|
1814
|
+
if (!Array.isArray(value)) return [];
|
|
1815
|
+
return value.filter((item) => typeof item === "string" && item.trim().length > 0);
|
|
1816
|
+
}
|
|
1817
|
+
function asStringRecord(value) {
|
|
1818
|
+
if (!isRecord(value)) return void 0;
|
|
1819
|
+
const entries = Object.entries(value).filter(
|
|
1820
|
+
([key, item]) => key.trim().length > 0 && typeof item === "string"
|
|
1821
|
+
);
|
|
1822
|
+
if (entries.length === 0) return void 0;
|
|
1823
|
+
return entries.reduce((accumulator, [key, item]) => {
|
|
1824
|
+
accumulator[key] = item;
|
|
1825
|
+
return accumulator;
|
|
1826
|
+
}, {});
|
|
1827
|
+
}
|
|
1828
|
+
function normalizeStrictness(value) {
|
|
1829
|
+
return value === "strict" ? "strict" : "compatible";
|
|
1830
|
+
}
|
|
1831
|
+
function normalizeCallbackRules(value) {
|
|
1832
|
+
if (!isRecord(value)) return void 0;
|
|
1833
|
+
const callback = {};
|
|
1834
|
+
if (typeof value.event_id_header === "string") callback.event_id_header = value.event_id_header;
|
|
1835
|
+
if (typeof value.signature_header === "string") callback.signature_header = value.signature_header;
|
|
1836
|
+
if (typeof value.signature_algorithm === "string") callback.signature_algorithm = value.signature_algorithm;
|
|
1837
|
+
if (typeof value.signature_message === "string") callback.signature_message = value.signature_message;
|
|
1838
|
+
if (typeof value.attempt_id_format === "string") callback.attempt_id_format = value.attempt_id_format;
|
|
1839
|
+
if (typeof value.idempotency === "string") callback.idempotency = value.idempotency;
|
|
1840
|
+
return Object.keys(callback).length > 0 ? callback : void 0;
|
|
1841
|
+
}
|
|
1842
|
+
function normalizeTrigger(value) {
|
|
1843
|
+
if (!isRecord(value)) {
|
|
1844
|
+
return { event: "task.trigger" };
|
|
1845
|
+
}
|
|
1846
|
+
const event = value.event === "task.trigger" ? "task.trigger" : "task.trigger";
|
|
1847
|
+
const route = typeof value.route === "string" && value.route.trim().length > 0 ? value.route : void 0;
|
|
1848
|
+
const payloadTemplate = isRecord(value.payload_template) ? value.payload_template : void 0;
|
|
1849
|
+
return {
|
|
1850
|
+
event,
|
|
1851
|
+
route,
|
|
1852
|
+
payload_template: payloadTemplate
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
function normalizeCapability(value) {
|
|
1856
|
+
if (!isRecord(value)) {
|
|
1857
|
+
throw new ContractValidationError("Invalid capability: expected object");
|
|
1858
|
+
}
|
|
1859
|
+
const capabilityId = typeof value.capability_id === "string" ? value.capability_id.trim() : "";
|
|
1860
|
+
const name = typeof value.name === "string" ? value.name.trim() : "";
|
|
1861
|
+
const description = typeof value.description === "string" ? value.description.trim() : "";
|
|
1862
|
+
const permission = typeof value.permission === "string" ? value.permission.trim() : "";
|
|
1863
|
+
if (!capabilityId || !name || !description || !permission) {
|
|
1864
|
+
throw new ContractValidationError("Invalid capability: missing required fields", { capability: value });
|
|
1865
|
+
}
|
|
1866
|
+
if (!isRecord(value.input_schema)) {
|
|
1867
|
+
throw new ContractValidationError("Invalid capability input_schema: expected JSON schema object", {
|
|
1868
|
+
capability_id: capabilityId
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
return {
|
|
1872
|
+
capability_id: capabilityId,
|
|
1873
|
+
name,
|
|
1874
|
+
description,
|
|
1875
|
+
input_schema: value.input_schema,
|
|
1876
|
+
output_schema: isRecord(value.output_schema) ? value.output_schema : void 0,
|
|
1877
|
+
permission,
|
|
1878
|
+
trigger: normalizeTrigger(value.trigger)
|
|
1879
|
+
};
|
|
1880
|
+
}
|
|
1881
|
+
function normalizeCapabilities(value) {
|
|
1882
|
+
if (value === void 0 || value === null) return void 0;
|
|
1883
|
+
if (!Array.isArray(value)) {
|
|
1884
|
+
throw new ContractValidationError("Invalid capabilities: expected array");
|
|
1885
|
+
}
|
|
1886
|
+
return value.map(normalizeCapability);
|
|
1887
|
+
}
|
|
1888
|
+
function extractContractRecord(payload) {
|
|
1889
|
+
if (!isRecord(payload)) {
|
|
1890
|
+
throw new ContractValidationError("Invalid contract response: expected object payload");
|
|
1891
|
+
}
|
|
1892
|
+
if (isRecord(payload.contract)) {
|
|
1893
|
+
return payload.contract;
|
|
1894
|
+
}
|
|
1895
|
+
return payload;
|
|
1896
|
+
}
|
|
1897
|
+
function resolveContractVersion(contract) {
|
|
1898
|
+
if (typeof contract.contract_version === "string") return contract.contract_version;
|
|
1899
|
+
if (typeof contract.version === "string") return contract.version;
|
|
1900
|
+
if (typeof contract.id === "string") return contract.id;
|
|
1901
|
+
return "";
|
|
1902
|
+
}
|
|
1903
|
+
function normalizeLocalAppContractV1(payload) {
|
|
1904
|
+
const contract = extractContractRecord(payload);
|
|
1905
|
+
const version = resolveContractVersion(contract);
|
|
1906
|
+
if (!version) {
|
|
1907
|
+
throw new ContractValidationError("Missing contract version in discovery response");
|
|
1908
|
+
}
|
|
1909
|
+
if (version !== LOCAL_APP_CONTRACT_VERSION2) {
|
|
1910
|
+
throw new ContractValidationError("Unsupported contract version", {
|
|
1911
|
+
expected: LOCAL_APP_CONTRACT_VERSION2,
|
|
1912
|
+
received: version
|
|
1913
|
+
});
|
|
1914
|
+
}
|
|
1915
|
+
const supportedContractEvents = asStringArray(contract.supported_contract_events).length > 0 ? asStringArray(contract.supported_contract_events) : asStringArray(contract.supported_events).length > 0 ? asStringArray(contract.supported_events) : DEFAULT_SUPPORTED_EVENTS;
|
|
1916
|
+
return {
|
|
1917
|
+
contract_version: LOCAL_APP_CONTRACT_VERSION2,
|
|
1918
|
+
strictness: normalizeStrictness(contract.strictness),
|
|
1919
|
+
supported_contract_events: supportedContractEvents,
|
|
1920
|
+
supported_legacy_events: asStringArray(contract.supported_legacy_events),
|
|
1921
|
+
aliases: asStringRecord(contract.aliases),
|
|
1922
|
+
status_map: asStringRecord(contract.status_map),
|
|
1923
|
+
legacy_action_map: asStringRecord(contract.legacy_action_map),
|
|
1924
|
+
callback: normalizeCallbackRules(contract.callback),
|
|
1925
|
+
capabilities: normalizeCapabilities(contract.capabilities)
|
|
1926
|
+
};
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
// src/core/contract/ContractClient.ts
|
|
1930
|
+
var ContractClient = class {
|
|
1931
|
+
constructor(httpClient, options = {}) {
|
|
1932
|
+
this.httpClient = httpClient;
|
|
1933
|
+
this.cache = options.cache || new ContractCache();
|
|
1934
|
+
this.cacheKey = options.cacheKey || "local-app-contract/v1";
|
|
1935
|
+
}
|
|
1936
|
+
async getLocalAppV1(forceRefresh = false) {
|
|
1937
|
+
if (!forceRefresh) {
|
|
1938
|
+
const cached = this.cache.get(this.cacheKey);
|
|
1939
|
+
if (cached) return cached;
|
|
1940
|
+
}
|
|
1941
|
+
const response = await this.httpClient.get("/contracts/local-app/v1");
|
|
1942
|
+
const normalized = normalizeLocalAppContractV1(response);
|
|
1943
|
+
this.cache.set(this.cacheKey, normalized);
|
|
1944
|
+
return normalized;
|
|
1945
|
+
}
|
|
1946
|
+
clearCache() {
|
|
1947
|
+
this.cache.clear(this.cacheKey);
|
|
1948
|
+
}
|
|
1949
|
+
};
|
|
1950
|
+
|
|
1951
|
+
// src/core/transport/HttpClient.ts
|
|
1952
|
+
function toRecordHeaders(input = {}) {
|
|
1953
|
+
if (input instanceof Headers) {
|
|
1954
|
+
const normalized = {};
|
|
1955
|
+
input.forEach((value, key) => {
|
|
1956
|
+
normalized[key] = value;
|
|
1957
|
+
});
|
|
1958
|
+
return normalized;
|
|
1959
|
+
}
|
|
1960
|
+
if (Array.isArray(input)) {
|
|
1961
|
+
return Object.fromEntries(input);
|
|
1962
|
+
}
|
|
1963
|
+
return { ...input };
|
|
1964
|
+
}
|
|
1965
|
+
var ContractHttpClient = class {
|
|
1966
|
+
constructor(config) {
|
|
1967
|
+
this.baseUrl = config.baseUrl.replace(/\/$/, "");
|
|
1968
|
+
this.appId = config.appId;
|
|
1969
|
+
this.appName = config.appName;
|
|
1970
|
+
this.apiKey = config.apiKey;
|
|
1971
|
+
this.fetchImpl = config.fetchImpl || fetch;
|
|
1972
|
+
}
|
|
1973
|
+
async get(path, headers = {}) {
|
|
1974
|
+
return this.request(path, {
|
|
1975
|
+
method: "GET",
|
|
1976
|
+
headers
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
async post(path, body, headers = {}) {
|
|
1980
|
+
return this.request(path, {
|
|
1981
|
+
method: "POST",
|
|
1982
|
+
headers,
|
|
1983
|
+
body: JSON.stringify(body)
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
async request(path, options = {}) {
|
|
1987
|
+
const url = `${this.baseUrl}${path}`;
|
|
1988
|
+
const headers = this.buildHeaders(options.headers);
|
|
1989
|
+
let response;
|
|
1990
|
+
try {
|
|
1991
|
+
response = await this.fetchImpl(url, {
|
|
1992
|
+
...options,
|
|
1993
|
+
headers
|
|
1994
|
+
});
|
|
1995
|
+
} catch (error) {
|
|
1996
|
+
throw new RuntimeTransportError("Failed to reach RealtimeX server", void 0, {
|
|
1997
|
+
cause: error,
|
|
1998
|
+
url
|
|
1999
|
+
});
|
|
2000
|
+
}
|
|
2001
|
+
const payload = await this.parseResponse(response);
|
|
2002
|
+
if (!response.ok) {
|
|
2003
|
+
const errorMessage = payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string" ? payload.error : `Request failed with status ${response.status}`;
|
|
2004
|
+
throw new RuntimeTransportError(errorMessage, response.status, payload);
|
|
2005
|
+
}
|
|
2006
|
+
return payload;
|
|
2007
|
+
}
|
|
2008
|
+
buildHeaders(extraHeaders = {}) {
|
|
2009
|
+
const headers = {
|
|
2010
|
+
"Content-Type": "application/json",
|
|
2011
|
+
...toRecordHeaders(extraHeaders)
|
|
2012
|
+
};
|
|
2013
|
+
if (this.apiKey) {
|
|
2014
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
2015
|
+
}
|
|
2016
|
+
if (this.appId) {
|
|
2017
|
+
headers["x-app-id"] = this.appId;
|
|
2018
|
+
}
|
|
2019
|
+
if (this.appName) {
|
|
2020
|
+
headers["x-app-name"] = this.appName;
|
|
2021
|
+
}
|
|
2022
|
+
return headers;
|
|
2023
|
+
}
|
|
2024
|
+
async parseResponse(response) {
|
|
2025
|
+
const contentType = response.headers.get("content-type") || "";
|
|
2026
|
+
if (contentType.includes("application/json")) {
|
|
2027
|
+
try {
|
|
2028
|
+
return await response.json();
|
|
2029
|
+
} catch {
|
|
2030
|
+
return {};
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
const text = await response.text();
|
|
2034
|
+
if (!text) return {};
|
|
2035
|
+
try {
|
|
2036
|
+
return JSON.parse(text);
|
|
2037
|
+
} catch {
|
|
2038
|
+
return { text };
|
|
2039
|
+
}
|
|
2040
|
+
}
|
|
2041
|
+
};
|
|
2042
|
+
|
|
2043
|
+
// src/core/tooling/SchemaNormalizer.ts
|
|
2044
|
+
function isRecord2(value) {
|
|
2045
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2046
|
+
}
|
|
2047
|
+
function deepClone(value) {
|
|
2048
|
+
return JSON.parse(JSON.stringify(value));
|
|
2049
|
+
}
|
|
2050
|
+
function normalizeSchema(schema) {
|
|
2051
|
+
if (!schema || !isRecord2(schema)) {
|
|
2052
|
+
return {
|
|
2053
|
+
type: "object",
|
|
2054
|
+
properties: {},
|
|
2055
|
+
additionalProperties: true
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
const normalized = deepClone(schema);
|
|
2059
|
+
if (typeof normalized.type !== "string" && !Array.isArray(normalized.type)) {
|
|
2060
|
+
normalized.type = "object";
|
|
2061
|
+
}
|
|
2062
|
+
if (normalized.type === "object" && !isRecord2(normalized.properties)) {
|
|
2063
|
+
normalized.properties = {};
|
|
2064
|
+
}
|
|
2065
|
+
if (Array.isArray(normalized.required)) {
|
|
2066
|
+
normalized.required = normalized.required.filter(
|
|
2067
|
+
(field) => typeof field === "string" && field.trim().length > 0
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
return normalized;
|
|
2071
|
+
}
|
|
2072
|
+
|
|
2073
|
+
// src/core/tooling/ToolNamePolicy.ts
|
|
2074
|
+
function normalizeToken(value) {
|
|
2075
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
2076
|
+
}
|
|
2077
|
+
function toStableToolName(capabilityId, namespace) {
|
|
2078
|
+
const normalizedCapability = normalizeToken(capabilityId.replace(/\./g, "_"));
|
|
2079
|
+
const normalizedNamespace = namespace ? normalizeToken(namespace) : "";
|
|
2080
|
+
if (!normalizedCapability) {
|
|
2081
|
+
return normalizedNamespace ? `${normalizedNamespace}_tool` : "tool";
|
|
2082
|
+
}
|
|
2083
|
+
const combined = normalizedNamespace && !normalizedCapability.startsWith(`${normalizedNamespace}_`) ? `${normalizedNamespace}_${normalizedCapability}` : normalizedCapability;
|
|
2084
|
+
return /^[a-z]/.test(combined) ? combined : `tool_${combined}`;
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
// src/core/tooling/ToolProjector.ts
|
|
2088
|
+
var ToolProjector = class {
|
|
2089
|
+
project(input) {
|
|
2090
|
+
const capabilities = input.contract.capabilities || [];
|
|
2091
|
+
const names = /* @__PURE__ */ new Set();
|
|
2092
|
+
return capabilities.map((capability) => {
|
|
2093
|
+
const baseName = toStableToolName(capability.capability_id, input.namespace || input.appId);
|
|
2094
|
+
const uniqueName = this.ensureUniqueToolName(baseName, names);
|
|
2095
|
+
return {
|
|
2096
|
+
tool_name: uniqueName,
|
|
2097
|
+
title: capability.name,
|
|
2098
|
+
description: capability.description,
|
|
2099
|
+
input_schema: normalizeSchema(capability.input_schema),
|
|
2100
|
+
output_schema: capability.output_schema,
|
|
2101
|
+
permission: capability.permission,
|
|
2102
|
+
capability_id: capability.capability_id,
|
|
2103
|
+
trigger: capability.trigger
|
|
2104
|
+
};
|
|
2105
|
+
});
|
|
2106
|
+
}
|
|
2107
|
+
ensureUniqueToolName(baseName, names) {
|
|
2108
|
+
if (!names.has(baseName)) {
|
|
2109
|
+
names.add(baseName);
|
|
2110
|
+
return baseName;
|
|
2111
|
+
}
|
|
2112
|
+
let index = 2;
|
|
2113
|
+
while (names.has(`${baseName}_${index}`)) {
|
|
2114
|
+
index += 1;
|
|
2115
|
+
}
|
|
2116
|
+
const uniqueName = `${baseName}_${index}`;
|
|
2117
|
+
names.add(uniqueName);
|
|
2118
|
+
return uniqueName;
|
|
2119
|
+
}
|
|
2120
|
+
};
|
|
2121
|
+
|
|
2122
|
+
// src/core/runtime/ExecutionStore.ts
|
|
2123
|
+
var ExecutionStore = class {
|
|
2124
|
+
constructor() {
|
|
2125
|
+
this.registries = /* @__PURE__ */ new Map();
|
|
2126
|
+
}
|
|
2127
|
+
registerTools(registryKey, tools) {
|
|
2128
|
+
const registry = /* @__PURE__ */ new Map();
|
|
2129
|
+
for (const tool of tools) {
|
|
2130
|
+
registry.set(tool.tool_name, tool);
|
|
2131
|
+
}
|
|
2132
|
+
this.registries.set(registryKey, registry);
|
|
2133
|
+
}
|
|
2134
|
+
hasRegistry(registryKey) {
|
|
2135
|
+
return this.registries.has(registryKey);
|
|
2136
|
+
}
|
|
2137
|
+
getTool(registryKey, toolName) {
|
|
2138
|
+
return this.registries.get(registryKey)?.get(toolName);
|
|
2139
|
+
}
|
|
2140
|
+
clear(registryKey) {
|
|
2141
|
+
if (registryKey) {
|
|
2142
|
+
this.registries.delete(registryKey);
|
|
2143
|
+
return;
|
|
2144
|
+
}
|
|
2145
|
+
this.registries.clear();
|
|
2146
|
+
}
|
|
2147
|
+
};
|
|
2148
|
+
|
|
2149
|
+
// src/core/runtime/LifecycleReporter.ts
|
|
2150
|
+
var LifecycleReporter = class {
|
|
2151
|
+
constructor() {
|
|
2152
|
+
this.handlers = /* @__PURE__ */ new Set();
|
|
2153
|
+
}
|
|
2154
|
+
onEvent(handler) {
|
|
2155
|
+
this.handlers.add(handler);
|
|
2156
|
+
return () => {
|
|
2157
|
+
this.handlers.delete(handler);
|
|
2158
|
+
};
|
|
2159
|
+
}
|
|
2160
|
+
emit(event) {
|
|
2161
|
+
for (const handler of this.handlers) {
|
|
2162
|
+
try {
|
|
2163
|
+
handler(event);
|
|
2164
|
+
} catch {
|
|
2165
|
+
}
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
|
|
2170
|
+
// src/core/runtime/RetryPolicy.ts
|
|
2171
|
+
function defaultShouldRetry(error) {
|
|
2172
|
+
if (error && typeof error === "object") {
|
|
2173
|
+
const status = error.statusCode;
|
|
2174
|
+
if (typeof status === "number") {
|
|
2175
|
+
return status >= 500 || status === 429;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
return true;
|
|
2179
|
+
}
|
|
2180
|
+
var RetryPolicy = class {
|
|
2181
|
+
constructor(options = {}) {
|
|
2182
|
+
this.maxAttempts = Math.max(1, options.maxAttempts ?? 3);
|
|
2183
|
+
this.baseDelayMs = Math.max(0, options.baseDelayMs ?? 150);
|
|
2184
|
+
this.maxDelayMs = Math.max(this.baseDelayMs, options.maxDelayMs ?? 2e3);
|
|
2185
|
+
this.shouldRetry = options.shouldRetry || ((error) => defaultShouldRetry(error));
|
|
2186
|
+
}
|
|
2187
|
+
async execute(operation) {
|
|
2188
|
+
let lastError = null;
|
|
2189
|
+
for (let attempt = 1; attempt <= this.maxAttempts; attempt += 1) {
|
|
2190
|
+
try {
|
|
2191
|
+
return await operation(attempt);
|
|
2192
|
+
} catch (error) {
|
|
2193
|
+
lastError = error;
|
|
2194
|
+
const canRetry = attempt < this.maxAttempts && this.shouldRetry(error, attempt);
|
|
2195
|
+
if (!canRetry) throw error;
|
|
2196
|
+
const delayMs = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** (attempt - 1));
|
|
2197
|
+
if (delayMs > 0) {
|
|
2198
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
throw lastError instanceof Error ? lastError : new Error("Retry operation failed");
|
|
2203
|
+
}
|
|
2204
|
+
};
|
|
2205
|
+
|
|
2206
|
+
// src/core/runtime/ContractRuntime.ts
|
|
2207
|
+
var LIFECYCLE_EVENTS = /* @__PURE__ */ new Set([
|
|
2208
|
+
"task.claimed",
|
|
2209
|
+
"task.started",
|
|
2210
|
+
"task.progress",
|
|
2211
|
+
"task.completed",
|
|
2212
|
+
"task.failed",
|
|
2213
|
+
"task.canceled"
|
|
2214
|
+
]);
|
|
2215
|
+
var DEFAULT_PROVIDER = "gemini";
|
|
2216
|
+
function isRecord3(value) {
|
|
2217
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2218
|
+
}
|
|
2219
|
+
function toRecord(value) {
|
|
2220
|
+
return isRecord3(value) ? value : {};
|
|
2221
|
+
}
|
|
2222
|
+
function resolveToolCallId(input) {
|
|
2223
|
+
if (typeof input.tool_call_id === "string" && input.tool_call_id.trim().length > 0) {
|
|
2224
|
+
return input.tool_call_id;
|
|
2225
|
+
}
|
|
2226
|
+
const payload = isRecord3(input.payload) ? input.payload : void 0;
|
|
2227
|
+
if (payload && typeof payload.tool_call_id === "string" && payload.tool_call_id.trim().length > 0) {
|
|
2228
|
+
return payload.tool_call_id;
|
|
2229
|
+
}
|
|
2230
|
+
const data = isRecord3(input.data) ? input.data : void 0;
|
|
2231
|
+
if (data && typeof data.tool_call_id === "string" && data.tool_call_id.trim().length > 0) {
|
|
2232
|
+
return data.tool_call_id;
|
|
2233
|
+
}
|
|
2234
|
+
return void 0;
|
|
2235
|
+
}
|
|
2236
|
+
var ContractRuntime = class {
|
|
2237
|
+
constructor(options) {
|
|
2238
|
+
if (!options.baseUrl) {
|
|
2239
|
+
throw new ContractValidationError("ContractRuntime requires baseUrl");
|
|
2240
|
+
}
|
|
2241
|
+
this.appId = options.appId;
|
|
2242
|
+
this.appName = options.appName;
|
|
2243
|
+
this.defaultNamespace = options.namespace;
|
|
2244
|
+
this.httpClient = new ContractHttpClient({
|
|
2245
|
+
baseUrl: options.baseUrl,
|
|
2246
|
+
appId: options.appId,
|
|
2247
|
+
appName: options.appName,
|
|
2248
|
+
apiKey: options.apiKey,
|
|
2249
|
+
fetchImpl: options.fetchImpl
|
|
2250
|
+
});
|
|
2251
|
+
this.contractClient = new ContractClient(this.httpClient, {
|
|
2252
|
+
cache: new ContractCache(options.cacheTtlMs ?? 3e4)
|
|
2253
|
+
});
|
|
2254
|
+
this.toolProjector = new ToolProjector();
|
|
2255
|
+
this.executionStore = new ExecutionStore();
|
|
2256
|
+
this.lifecycleReporter = new LifecycleReporter();
|
|
2257
|
+
this.scopeGuard = new ScopeGuard(options.permissions || []);
|
|
2258
|
+
this.retryPolicy = new RetryPolicy(options.retry);
|
|
2259
|
+
}
|
|
2260
|
+
async getContract(appId) {
|
|
2261
|
+
this.assertAppContext(appId);
|
|
2262
|
+
return this.contractClient.getLocalAppV1(false);
|
|
2263
|
+
}
|
|
2264
|
+
async getTools(input) {
|
|
2265
|
+
this.assertAppContext(input.appId);
|
|
2266
|
+
const contract = await this.contractClient.getLocalAppV1(false);
|
|
2267
|
+
const tools = this.toolProjector.project({
|
|
2268
|
+
contract,
|
|
2269
|
+
provider: input.provider,
|
|
2270
|
+
appId: input.appId,
|
|
2271
|
+
namespace: input.namespace || this.defaultNamespace || input.appId
|
|
2272
|
+
});
|
|
2273
|
+
this.executionStore.registerTools(
|
|
2274
|
+
this.buildRegistryKey(input.appId, input.provider, input.namespace),
|
|
2275
|
+
tools
|
|
2276
|
+
);
|
|
2277
|
+
return tools;
|
|
2278
|
+
}
|
|
2279
|
+
async executeToolCall(call, context) {
|
|
2280
|
+
try {
|
|
2281
|
+
this.assertAppContext(context.appId);
|
|
2282
|
+
const provider = context.provider || DEFAULT_PROVIDER;
|
|
2283
|
+
const namespace = context.namespace || this.defaultNamespace || context.appId;
|
|
2284
|
+
const registryKey = this.buildRegistryKey(context.appId, provider, namespace);
|
|
2285
|
+
if (!this.executionStore.hasRegistry(registryKey)) {
|
|
2286
|
+
await this.getTools({
|
|
2287
|
+
appId: context.appId,
|
|
2288
|
+
provider,
|
|
2289
|
+
namespace
|
|
2290
|
+
});
|
|
2291
|
+
}
|
|
2292
|
+
const tool = this.executionStore.getTool(registryKey, call.tool_name);
|
|
2293
|
+
if (!tool) {
|
|
2294
|
+
throw new ToolNotFoundError(call.tool_name, {
|
|
2295
|
+
registryKey
|
|
2296
|
+
});
|
|
2297
|
+
}
|
|
2298
|
+
this.scopeGuard.assert(tool.permission);
|
|
2299
|
+
const validationErrors = this.validateToolArgs(tool, call.args);
|
|
2300
|
+
if (validationErrors.length > 0) {
|
|
2301
|
+
throw new ToolValidationError("Tool input validation failed", {
|
|
2302
|
+
tool_name: call.tool_name,
|
|
2303
|
+
errors: validationErrors
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
const eventId = context.idempotencyKey || call.tool_call_id;
|
|
2307
|
+
const requestBody = this.buildTriggerRequestBody(call, context, tool, eventId);
|
|
2308
|
+
const response = await this.retryPolicy.execute(
|
|
2309
|
+
() => this.httpClient.post(tool.trigger.route || "/webhooks/realtimex", requestBody)
|
|
2310
|
+
);
|
|
2311
|
+
if (response.success === false) {
|
|
2312
|
+
throw new RuntimeTransportError(response.error || "Failed to trigger task", void 0, response);
|
|
2313
|
+
}
|
|
2314
|
+
const taskId = this.resolveTaskId(response);
|
|
2315
|
+
const attemptId = normalizeAttemptId(response.attempt_id);
|
|
2316
|
+
this.tryEmitLifecycleEvent({
|
|
2317
|
+
tool_call_id: call.tool_call_id,
|
|
2318
|
+
task_id: taskId,
|
|
2319
|
+
attempt_id: attemptId,
|
|
2320
|
+
event_type: response.event_type,
|
|
2321
|
+
event_id: response.event_id,
|
|
2322
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2323
|
+
payload: toRecord(response)
|
|
2324
|
+
});
|
|
2325
|
+
if (taskId) {
|
|
2326
|
+
return {
|
|
2327
|
+
status: "queued",
|
|
2328
|
+
tool_call_id: call.tool_call_id,
|
|
2329
|
+
task_id: taskId,
|
|
2330
|
+
attempt_id: attemptId,
|
|
2331
|
+
output: {
|
|
2332
|
+
message: response.message || "Task accepted"
|
|
2333
|
+
}
|
|
2334
|
+
};
|
|
2335
|
+
}
|
|
2336
|
+
return {
|
|
2337
|
+
status: "completed",
|
|
2338
|
+
tool_call_id: call.tool_call_id,
|
|
2339
|
+
output: toRecord(response)
|
|
2340
|
+
};
|
|
2341
|
+
} catch (error) {
|
|
2342
|
+
return this.toFailedResult(call.tool_call_id, error);
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
onExecutionEvent(handler) {
|
|
2346
|
+
return this.lifecycleReporter.onEvent(handler);
|
|
2347
|
+
}
|
|
2348
|
+
ingestExecutionEvent(input) {
|
|
2349
|
+
const eventTypeRaw = typeof input.event_type === "string" && input.event_type || typeof input.event === "string" && input.event || "";
|
|
2350
|
+
const normalized = normalizeContractEvent(eventTypeRaw);
|
|
2351
|
+
if (!normalized || !LIFECYCLE_EVENTS.has(normalized)) {
|
|
2352
|
+
return null;
|
|
2353
|
+
}
|
|
2354
|
+
const taskId = typeof input.task_id === "string" && input.task_id || typeof input.task_uuid === "string" && input.task_uuid || "";
|
|
2355
|
+
if (!taskId) return null;
|
|
2356
|
+
const event = {
|
|
2357
|
+
tool_call_id: resolveToolCallId(input) || taskId,
|
|
2358
|
+
task_id: taskId,
|
|
2359
|
+
attempt_id: normalizeAttemptId(input.attempt_id),
|
|
2360
|
+
event_type: normalized,
|
|
2361
|
+
event_id: typeof input.event_id === "string" && input.event_id || `${taskId}:${normalized}:${Date.now()}`,
|
|
2362
|
+
timestamp: typeof input.timestamp === "string" && input.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
|
|
2363
|
+
payload: toRecord(input.payload || input.data)
|
|
2364
|
+
};
|
|
2365
|
+
this.lifecycleReporter.emit(event);
|
|
2366
|
+
return event;
|
|
2367
|
+
}
|
|
2368
|
+
clearCache() {
|
|
2369
|
+
this.contractClient.clearCache();
|
|
2370
|
+
this.executionStore.clear();
|
|
2371
|
+
}
|
|
2372
|
+
assertAppContext(appId) {
|
|
2373
|
+
if (!appId || appId.trim().length === 0) {
|
|
2374
|
+
throw new ContractValidationError("appId is required");
|
|
2375
|
+
}
|
|
2376
|
+
if (this.appId && this.appId !== appId) {
|
|
2377
|
+
throw new ContractValidationError("Runtime appId mismatch", {
|
|
2378
|
+
runtime_app_id: this.appId,
|
|
2379
|
+
requested_app_id: appId
|
|
2380
|
+
});
|
|
2381
|
+
}
|
|
2382
|
+
}
|
|
2383
|
+
buildRegistryKey(appId, provider, namespace) {
|
|
2384
|
+
const resolvedNamespace = namespace || this.defaultNamespace || appId;
|
|
2385
|
+
return `${appId}:${provider}:${resolvedNamespace}`;
|
|
2386
|
+
}
|
|
2387
|
+
resolveTaskId(response) {
|
|
2388
|
+
if (typeof response.task_uuid === "string" && response.task_uuid.trim().length > 0) {
|
|
2389
|
+
return response.task_uuid;
|
|
2390
|
+
}
|
|
2391
|
+
if (typeof response.task_id === "string" && response.task_id.trim().length > 0) {
|
|
2392
|
+
return response.task_id;
|
|
2393
|
+
}
|
|
2394
|
+
return void 0;
|
|
2395
|
+
}
|
|
2396
|
+
buildTriggerRequestBody(call, context, tool, eventId) {
|
|
2397
|
+
const payloadTemplate = isRecord3(tool.trigger.payload_template) ? tool.trigger.payload_template : {};
|
|
2398
|
+
const templateRawData = isRecord3(payloadTemplate.raw_data) ? payloadTemplate.raw_data : {};
|
|
2399
|
+
const payload = {
|
|
2400
|
+
...payloadTemplate,
|
|
2401
|
+
raw_data: {
|
|
2402
|
+
...templateRawData,
|
|
2403
|
+
capability_id: tool.capability_id,
|
|
2404
|
+
tool_name: call.tool_name,
|
|
2405
|
+
tool_call_id: call.tool_call_id,
|
|
2406
|
+
args: call.args,
|
|
2407
|
+
context: {
|
|
2408
|
+
user_id: context.userId,
|
|
2409
|
+
workspace_id: context.workspaceId || null,
|
|
2410
|
+
request_id: context.requestId || null,
|
|
2411
|
+
metadata: context.metadata || null
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
};
|
|
2415
|
+
if (typeof payload.auto_run !== "boolean") {
|
|
2416
|
+
payload.auto_run = false;
|
|
2417
|
+
}
|
|
2418
|
+
return {
|
|
2419
|
+
app_name: this.appName,
|
|
2420
|
+
app_id: this.appId || context.appId,
|
|
2421
|
+
event: tool.trigger.event,
|
|
2422
|
+
event_id: eventId,
|
|
2423
|
+
payload
|
|
2424
|
+
};
|
|
2425
|
+
}
|
|
2426
|
+
validateToolArgs(tool, args) {
|
|
2427
|
+
const errors = [];
|
|
2428
|
+
if (!isRecord3(args)) {
|
|
2429
|
+
errors.push("args must be an object");
|
|
2430
|
+
return errors;
|
|
2431
|
+
}
|
|
2432
|
+
const requiredFields = Array.isArray(tool.input_schema.required) ? tool.input_schema.required.filter((field) => typeof field === "string") : [];
|
|
2433
|
+
for (const field of requiredFields) {
|
|
2434
|
+
const value = args[field];
|
|
2435
|
+
if (value === void 0 || value === null || typeof value === "string" && value.trim().length === 0) {
|
|
2436
|
+
errors.push(`Missing required field: ${field}`);
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
const properties = isRecord3(tool.input_schema.properties) ? tool.input_schema.properties : {};
|
|
2440
|
+
for (const [field, schemaValue] of Object.entries(properties)) {
|
|
2441
|
+
if (!(field in args)) continue;
|
|
2442
|
+
if (!isRecord3(schemaValue)) continue;
|
|
2443
|
+
const typeValue = schemaValue.type;
|
|
2444
|
+
if (typeof typeValue === "string") {
|
|
2445
|
+
if (!this.matchesType(args[field], typeValue)) {
|
|
2446
|
+
errors.push(`Invalid type for ${field}: expected ${typeValue}`);
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
if (Array.isArray(typeValue)) {
|
|
2450
|
+
const valid = typeValue.some(
|
|
2451
|
+
(item) => typeof item === "string" && this.matchesType(args[field], item)
|
|
2452
|
+
);
|
|
2453
|
+
if (!valid) {
|
|
2454
|
+
errors.push(
|
|
2455
|
+
`Invalid type for ${field}: expected one of ${typeValue.filter((item) => typeof item === "string").join(", ")}`
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
return errors;
|
|
2461
|
+
}
|
|
2462
|
+
matchesType(value, expectedType) {
|
|
2463
|
+
switch (expectedType) {
|
|
2464
|
+
case "string":
|
|
2465
|
+
return typeof value === "string";
|
|
2466
|
+
case "number":
|
|
2467
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
2468
|
+
case "integer":
|
|
2469
|
+
return typeof value === "number" && Number.isInteger(value);
|
|
2470
|
+
case "boolean":
|
|
2471
|
+
return typeof value === "boolean";
|
|
2472
|
+
case "object":
|
|
2473
|
+
return isRecord3(value);
|
|
2474
|
+
case "array":
|
|
2475
|
+
return Array.isArray(value);
|
|
2476
|
+
case "null":
|
|
2477
|
+
return value === null;
|
|
2478
|
+
default:
|
|
2479
|
+
return true;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
tryEmitLifecycleEvent(input) {
|
|
2483
|
+
if (!input.task_id || !input.event_type) return;
|
|
2484
|
+
const normalized = normalizeContractEvent(input.event_type);
|
|
2485
|
+
if (!normalized || !LIFECYCLE_EVENTS.has(normalized)) {
|
|
2486
|
+
return;
|
|
2487
|
+
}
|
|
2488
|
+
this.lifecycleReporter.emit({
|
|
2489
|
+
tool_call_id: input.tool_call_id,
|
|
2490
|
+
task_id: input.task_id,
|
|
2491
|
+
attempt_id: normalizeAttemptId(input.attempt_id),
|
|
2492
|
+
event_type: normalized,
|
|
2493
|
+
event_id: input.event_id || `${input.task_id}:${normalized}:${Date.now()}`,
|
|
2494
|
+
timestamp: input.timestamp,
|
|
2495
|
+
payload: input.payload
|
|
2496
|
+
});
|
|
2497
|
+
}
|
|
2498
|
+
toFailedResult(toolCallId, error) {
|
|
2499
|
+
if (error instanceof ContractError) {
|
|
2500
|
+
const retryable = error instanceof RuntimeTransportError ? error.statusCode === void 0 || error.statusCode >= 500 || error.statusCode === 429 : false;
|
|
2501
|
+
return {
|
|
2502
|
+
status: "failed",
|
|
2503
|
+
tool_call_id: toolCallId,
|
|
2504
|
+
error: {
|
|
2505
|
+
code: error.code,
|
|
2506
|
+
message: error.message,
|
|
2507
|
+
retryable
|
|
2508
|
+
}
|
|
2509
|
+
};
|
|
2510
|
+
}
|
|
2511
|
+
if (error instanceof Error) {
|
|
2512
|
+
return {
|
|
2513
|
+
status: "failed",
|
|
2514
|
+
tool_call_id: toolCallId,
|
|
2515
|
+
error: {
|
|
2516
|
+
code: "runtime_error",
|
|
2517
|
+
message: error.message,
|
|
2518
|
+
retryable: true
|
|
2519
|
+
}
|
|
2520
|
+
};
|
|
2521
|
+
}
|
|
2522
|
+
return {
|
|
2523
|
+
status: "failed",
|
|
2524
|
+
tool_call_id: toolCallId,
|
|
2525
|
+
error: {
|
|
2526
|
+
code: "runtime_error",
|
|
2527
|
+
message: "Unknown runtime error",
|
|
2528
|
+
retryable: true
|
|
2529
|
+
}
|
|
2530
|
+
};
|
|
2531
|
+
}
|
|
2532
|
+
};
|
|
2533
|
+
|
|
2534
|
+
// src/core/auth/AuthProvider.ts
|
|
2535
|
+
var StaticAuthProvider = class {
|
|
2536
|
+
constructor(options = {}) {
|
|
2537
|
+
this.appId = options.appId;
|
|
2538
|
+
this.appName = options.appName;
|
|
2539
|
+
this.apiKey = options.apiKey;
|
|
2540
|
+
}
|
|
2541
|
+
buildHeaders(baseHeaders = {}) {
|
|
2542
|
+
const headers = { ...baseHeaders };
|
|
2543
|
+
if (this.apiKey) {
|
|
2544
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
2545
|
+
}
|
|
2546
|
+
if (this.appId) {
|
|
2547
|
+
headers["x-app-id"] = this.appId;
|
|
2548
|
+
}
|
|
2549
|
+
if (this.appName) {
|
|
2550
|
+
headers["x-app-name"] = this.appName;
|
|
2551
|
+
}
|
|
2552
|
+
return headers;
|
|
2553
|
+
}
|
|
2554
|
+
};
|
|
2555
|
+
|
|
2556
|
+
// src/adapters/gemini/GeminiToolAdapter.ts
|
|
2557
|
+
function isRecord4(value) {
|
|
2558
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2559
|
+
}
|
|
2560
|
+
function parseArgs(value) {
|
|
2561
|
+
if (isRecord4(value)) return value;
|
|
2562
|
+
if (typeof value === "string") {
|
|
2563
|
+
try {
|
|
2564
|
+
const parsed = JSON.parse(value);
|
|
2565
|
+
return isRecord4(parsed) ? parsed : {};
|
|
2566
|
+
} catch {
|
|
2567
|
+
return {};
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
return {};
|
|
2571
|
+
}
|
|
2572
|
+
var GeminiToolAdapter = class {
|
|
2573
|
+
toProviderTools(tools) {
|
|
2574
|
+
return tools.map((tool) => ({
|
|
2575
|
+
name: tool.tool_name,
|
|
2576
|
+
description: tool.description,
|
|
2577
|
+
parameters: tool.input_schema
|
|
2578
|
+
}));
|
|
2579
|
+
}
|
|
2580
|
+
fromProviderToolCall(call) {
|
|
2581
|
+
return {
|
|
2582
|
+
tool_call_id: call.id,
|
|
2583
|
+
tool_name: call.name,
|
|
2584
|
+
args: parseArgs(call.args)
|
|
2585
|
+
};
|
|
2586
|
+
}
|
|
2587
|
+
toProviderResult(result) {
|
|
2588
|
+
return {
|
|
2589
|
+
tool_call_id: result.tool_call_id || result.task_id || "unknown",
|
|
2590
|
+
status: result.status,
|
|
2591
|
+
payload: result.status === "failed" ? { error: result.error } : {
|
|
2592
|
+
...result.output || {},
|
|
2593
|
+
task_id: result.task_id,
|
|
2594
|
+
attempt_id: result.attempt_id
|
|
2595
|
+
}
|
|
2596
|
+
};
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
|
|
2600
|
+
// src/adapters/claude/ClaudeToolAdapter.ts
|
|
2601
|
+
var ClaudeToolAdapter = class {
|
|
2602
|
+
toProviderTools(tools) {
|
|
2603
|
+
return tools.map((tool) => ({
|
|
2604
|
+
name: tool.tool_name,
|
|
2605
|
+
description: tool.description,
|
|
2606
|
+
input_schema: tool.input_schema
|
|
2607
|
+
}));
|
|
2608
|
+
}
|
|
2609
|
+
fromProviderToolCall(call) {
|
|
2610
|
+
return {
|
|
2611
|
+
tool_call_id: call.id,
|
|
2612
|
+
tool_name: call.name,
|
|
2613
|
+
args: call.input || {}
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
toProviderResult(result) {
|
|
2617
|
+
const contentPayload = result.status === "failed" ? { error: result.error } : {
|
|
2618
|
+
...result.output || {},
|
|
2619
|
+
task_id: result.task_id,
|
|
2620
|
+
attempt_id: result.attempt_id
|
|
2621
|
+
};
|
|
2622
|
+
return {
|
|
2623
|
+
type: "tool_result",
|
|
2624
|
+
tool_use_id: result.tool_call_id || result.task_id || "unknown",
|
|
2625
|
+
content: JSON.stringify(contentPayload),
|
|
2626
|
+
is_error: result.status === "failed" ? true : void 0
|
|
2627
|
+
};
|
|
2628
|
+
}
|
|
2629
|
+
};
|
|
2630
|
+
|
|
2631
|
+
// src/adapters/codex/CodexToolAdapter.ts
|
|
2632
|
+
function isRecord5(value) {
|
|
2633
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2634
|
+
}
|
|
2635
|
+
function parseArguments(value) {
|
|
2636
|
+
if (isRecord5(value)) return value;
|
|
2637
|
+
if (typeof value === "string") {
|
|
2638
|
+
try {
|
|
2639
|
+
const parsed = JSON.parse(value);
|
|
2640
|
+
return isRecord5(parsed) ? parsed : {};
|
|
2641
|
+
} catch {
|
|
2642
|
+
return {};
|
|
2643
|
+
}
|
|
2644
|
+
}
|
|
2645
|
+
return {};
|
|
2646
|
+
}
|
|
2647
|
+
var CodexToolAdapter = class {
|
|
2648
|
+
toProviderTools(tools) {
|
|
2649
|
+
return tools.map((tool) => ({
|
|
2650
|
+
type: "function",
|
|
2651
|
+
function: {
|
|
2652
|
+
name: tool.tool_name,
|
|
2653
|
+
description: tool.description,
|
|
2654
|
+
parameters: tool.input_schema
|
|
2655
|
+
}
|
|
2656
|
+
}));
|
|
2657
|
+
}
|
|
2658
|
+
fromProviderToolCall(call) {
|
|
2659
|
+
return {
|
|
2660
|
+
tool_call_id: call.id,
|
|
2661
|
+
tool_name: call.function.name,
|
|
2662
|
+
args: parseArguments(call.function.arguments)
|
|
2663
|
+
};
|
|
2664
|
+
}
|
|
2665
|
+
toProviderResult(result) {
|
|
2666
|
+
const outputPayload = result.status === "failed" ? { error: result.error } : {
|
|
2667
|
+
...result.output || {},
|
|
2668
|
+
task_id: result.task_id,
|
|
2669
|
+
attempt_id: result.attempt_id
|
|
2670
|
+
};
|
|
2671
|
+
return {
|
|
2672
|
+
tool_call_id: result.tool_call_id || result.task_id || "unknown",
|
|
2673
|
+
output: JSON.stringify(outputPayload),
|
|
2674
|
+
is_error: result.status === "failed" ? true : void 0
|
|
2675
|
+
};
|
|
2676
|
+
}
|
|
2677
|
+
};
|
|
2678
|
+
|
|
2679
|
+
// src/acp/ACPEventMapper.ts
|
|
2680
|
+
function getErrorMessage(error) {
|
|
2681
|
+
if (error instanceof Error) return error.message;
|
|
2682
|
+
if (typeof error === "string") return error;
|
|
2683
|
+
return "Unknown error";
|
|
2684
|
+
}
|
|
2685
|
+
function buildRealtimeXMeta(input) {
|
|
2686
|
+
return {
|
|
2687
|
+
realtimex: {
|
|
2688
|
+
tool_call_id: input.reference.toolCallId,
|
|
2689
|
+
task_id: input.taskId,
|
|
2690
|
+
attempt_id: input.attemptId,
|
|
2691
|
+
event_id: input.eventId,
|
|
2692
|
+
contract_version: "local-app-contract/v1",
|
|
2693
|
+
contract_event: input.contractEvent,
|
|
2694
|
+
cancelled: input.cancelled === true ? true : void 0,
|
|
2695
|
+
app_id: input.reference.appId,
|
|
2696
|
+
user_id: input.reference.userId,
|
|
2697
|
+
workspace_id: input.reference.workspaceId,
|
|
2698
|
+
provider: input.reference.provider,
|
|
2699
|
+
namespace: input.reference.namespace
|
|
2700
|
+
}
|
|
2701
|
+
};
|
|
2702
|
+
}
|
|
2703
|
+
var ACPEventMapper = class {
|
|
2704
|
+
createReference(invocation, context) {
|
|
2705
|
+
return {
|
|
2706
|
+
sessionId: context.sessionId,
|
|
2707
|
+
toolCallId: invocation.toolCallId,
|
|
2708
|
+
appId: context.appId,
|
|
2709
|
+
userId: context.userId,
|
|
2710
|
+
workspaceId: context.workspaceId,
|
|
2711
|
+
provider: context.provider,
|
|
2712
|
+
namespace: context.namespace,
|
|
2713
|
+
title: invocation.title || invocation.toolName,
|
|
2714
|
+
kind: invocation.kind || "execute"
|
|
2715
|
+
};
|
|
2716
|
+
}
|
|
2717
|
+
buildPendingUpdate(invocation, reference) {
|
|
2718
|
+
return {
|
|
2719
|
+
sessionId: reference.sessionId,
|
|
2720
|
+
update: {
|
|
2721
|
+
type: "tool_call",
|
|
2722
|
+
toolCallId: invocation.toolCallId,
|
|
2723
|
+
title: reference.title,
|
|
2724
|
+
kind: reference.kind,
|
|
2725
|
+
status: "pending",
|
|
2726
|
+
rawInput: invocation.args,
|
|
2727
|
+
_meta: buildRealtimeXMeta({
|
|
2728
|
+
reference,
|
|
2729
|
+
contractEvent: "task.trigger"
|
|
2730
|
+
})
|
|
2731
|
+
}
|
|
2732
|
+
};
|
|
2733
|
+
}
|
|
2734
|
+
buildResultUpdate(result, reference) {
|
|
2735
|
+
const status = this.mapExecutionResultStatus(result);
|
|
2736
|
+
const taskId = result.task_id;
|
|
2737
|
+
const attemptId = result.attempt_id;
|
|
2738
|
+
const contractEvent = status === "completed" ? "task.completed" : status === "failed" ? "task.failed" : "task.started";
|
|
2739
|
+
const rawOutput = status === "failed" ? {
|
|
2740
|
+
error: result.error || {
|
|
2741
|
+
code: "runtime_error",
|
|
2742
|
+
message: "Unknown runtime error",
|
|
2743
|
+
retryable: true
|
|
2744
|
+
}
|
|
2745
|
+
} : {
|
|
2746
|
+
...result.output || {},
|
|
2747
|
+
task_id: taskId,
|
|
2748
|
+
attempt_id: attemptId
|
|
2749
|
+
};
|
|
2750
|
+
return {
|
|
2751
|
+
sessionId: reference.sessionId,
|
|
2752
|
+
update: {
|
|
2753
|
+
type: "tool_call_update",
|
|
2754
|
+
toolCallId: reference.toolCallId,
|
|
2755
|
+
status,
|
|
2756
|
+
content: [
|
|
2757
|
+
{
|
|
2758
|
+
type: "text",
|
|
2759
|
+
text: status === "in_progress" ? "Task queued" : status === "completed" ? "Task completed" : "Task failed"
|
|
2760
|
+
}
|
|
2761
|
+
],
|
|
2762
|
+
rawOutput,
|
|
2763
|
+
_meta: buildRealtimeXMeta({
|
|
2764
|
+
reference,
|
|
2765
|
+
taskId,
|
|
2766
|
+
attemptId,
|
|
2767
|
+
contractEvent
|
|
2768
|
+
})
|
|
2769
|
+
}
|
|
2770
|
+
};
|
|
2771
|
+
}
|
|
2772
|
+
buildLifecycleUpdate(event, reference) {
|
|
2773
|
+
const status = this.mapContractEventStatus(event.event_type);
|
|
2774
|
+
if (!status) return null;
|
|
2775
|
+
const payload = event.payload || {};
|
|
2776
|
+
const progressText = this.resolveEventText(event.event_type, payload);
|
|
2777
|
+
const cancelled = event.event_type === "task.canceled";
|
|
2778
|
+
return {
|
|
2779
|
+
sessionId: reference.sessionId,
|
|
2780
|
+
update: {
|
|
2781
|
+
type: "tool_call_update",
|
|
2782
|
+
toolCallId: reference.toolCallId,
|
|
2783
|
+
status,
|
|
2784
|
+
content: progressText ? [
|
|
2785
|
+
{
|
|
2786
|
+
type: "text",
|
|
2787
|
+
text: progressText
|
|
2788
|
+
}
|
|
2789
|
+
] : void 0,
|
|
2790
|
+
rawOutput: payload,
|
|
2791
|
+
_meta: buildRealtimeXMeta({
|
|
2792
|
+
reference,
|
|
2793
|
+
taskId: event.task_id,
|
|
2794
|
+
attemptId: event.attempt_id,
|
|
2795
|
+
eventId: event.event_id,
|
|
2796
|
+
contractEvent: event.event_type,
|
|
2797
|
+
cancelled
|
|
2798
|
+
})
|
|
2799
|
+
}
|
|
2800
|
+
};
|
|
2801
|
+
}
|
|
2802
|
+
buildNotifyFailureUpdate(reference, error) {
|
|
2803
|
+
return {
|
|
2804
|
+
sessionId: reference.sessionId,
|
|
2805
|
+
update: {
|
|
2806
|
+
type: "tool_call_update",
|
|
2807
|
+
toolCallId: reference.toolCallId,
|
|
2808
|
+
status: "failed",
|
|
2809
|
+
content: [
|
|
2810
|
+
{
|
|
2811
|
+
type: "text",
|
|
2812
|
+
text: `Adapter notify failed: ${getErrorMessage(error)}`
|
|
2813
|
+
}
|
|
2814
|
+
],
|
|
2815
|
+
rawOutput: {
|
|
2816
|
+
error: {
|
|
2817
|
+
code: "acp_notify_failed",
|
|
2818
|
+
message: getErrorMessage(error)
|
|
2819
|
+
}
|
|
2820
|
+
},
|
|
2821
|
+
_meta: buildRealtimeXMeta({
|
|
2822
|
+
reference,
|
|
2823
|
+
contractEvent: "adapter.notify_failed"
|
|
2824
|
+
})
|
|
2825
|
+
}
|
|
2826
|
+
};
|
|
2827
|
+
}
|
|
2828
|
+
mapContractEventStatus(eventType) {
|
|
2829
|
+
switch (eventType) {
|
|
2830
|
+
case "task.claimed":
|
|
2831
|
+
case "task.started":
|
|
2832
|
+
case "task.progress":
|
|
2833
|
+
return "in_progress";
|
|
2834
|
+
case "task.completed":
|
|
2835
|
+
return "completed";
|
|
2836
|
+
case "task.failed":
|
|
2837
|
+
case "task.canceled":
|
|
2838
|
+
return "failed";
|
|
2839
|
+
default:
|
|
2840
|
+
return null;
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2843
|
+
mapExecutionResultStatus(result) {
|
|
2844
|
+
switch (result.status) {
|
|
2845
|
+
case "completed":
|
|
2846
|
+
return "completed";
|
|
2847
|
+
case "failed":
|
|
2848
|
+
return "failed";
|
|
2849
|
+
case "queued":
|
|
2850
|
+
return "in_progress";
|
|
2851
|
+
default:
|
|
2852
|
+
return "failed";
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
resolveEventText(eventType, payload) {
|
|
2856
|
+
const payloadMessage = typeof payload.message === "string" ? payload.message : typeof payload.error === "string" ? payload.error : void 0;
|
|
2857
|
+
if (payloadMessage) return payloadMessage;
|
|
2858
|
+
switch (eventType) {
|
|
2859
|
+
case "task.claimed":
|
|
2860
|
+
return "Task claimed";
|
|
2861
|
+
case "task.started":
|
|
2862
|
+
return "Task started";
|
|
2863
|
+
case "task.progress":
|
|
2864
|
+
return "Task in progress";
|
|
2865
|
+
case "task.completed":
|
|
2866
|
+
return "Task completed";
|
|
2867
|
+
case "task.failed":
|
|
2868
|
+
return "Task failed";
|
|
2869
|
+
case "task.canceled":
|
|
2870
|
+
return "Task canceled";
|
|
2871
|
+
default:
|
|
2872
|
+
return void 0;
|
|
2873
|
+
}
|
|
2874
|
+
}
|
|
2875
|
+
};
|
|
2876
|
+
|
|
2877
|
+
// src/acp/ACPPermissionBridge.ts
|
|
2878
|
+
function isRecord6(value) {
|
|
2879
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2880
|
+
}
|
|
2881
|
+
function normalizePermissionOptions(invocation, buildPermissionOptions) {
|
|
2882
|
+
const built = buildPermissionOptions ? buildPermissionOptions(invocation) : void 0;
|
|
2883
|
+
if (built && built.length > 0) return built;
|
|
2884
|
+
return [
|
|
2885
|
+
{
|
|
2886
|
+
id: "allow_once",
|
|
2887
|
+
label: "Allow once",
|
|
2888
|
+
kind: "allow_once"
|
|
2889
|
+
},
|
|
2890
|
+
{
|
|
2891
|
+
id: "deny_once",
|
|
2892
|
+
label: "Deny",
|
|
2893
|
+
kind: "deny_once"
|
|
2894
|
+
}
|
|
2895
|
+
];
|
|
2896
|
+
}
|
|
2897
|
+
function parseDecision(response) {
|
|
2898
|
+
if (typeof response === "boolean") return response;
|
|
2899
|
+
if (!isRecord6(response)) return false;
|
|
2900
|
+
if (typeof response.allow === "boolean") return response.allow;
|
|
2901
|
+
const decision = typeof response.decision === "string" && response.decision || typeof response.outcome === "string" && response.outcome || typeof response.selected === "string" && response.selected || "";
|
|
2902
|
+
const normalized = decision.trim().toLowerCase();
|
|
2903
|
+
if (!normalized) return false;
|
|
2904
|
+
return normalized === "allow" || normalized === "allow_once" || normalized === "allow_always" || normalized === "approved" || normalized === "granted";
|
|
2905
|
+
}
|
|
2906
|
+
var ACPPermissionBridge = class {
|
|
2907
|
+
constructor(options) {
|
|
2908
|
+
this.notifier = options.notifier;
|
|
2909
|
+
this.enabled = options.enabled;
|
|
2910
|
+
this.buildPermissionOptions = options.buildPermissionOptions;
|
|
2911
|
+
}
|
|
2912
|
+
async requestToolPermission(invocation, context) {
|
|
2913
|
+
if (!this.enabled) return true;
|
|
2914
|
+
if (!this.notifier.request) {
|
|
2915
|
+
return false;
|
|
2916
|
+
}
|
|
2917
|
+
const options = normalizePermissionOptions(invocation, this.buildPermissionOptions);
|
|
2918
|
+
try {
|
|
2919
|
+
const response = await this.notifier.request("session/request_permission", {
|
|
2920
|
+
sessionId: context.sessionId,
|
|
2921
|
+
title: invocation.title || invocation.toolName,
|
|
2922
|
+
description: `Allow tool ${invocation.toolName} to run?`,
|
|
2923
|
+
options,
|
|
2924
|
+
metadata: {
|
|
2925
|
+
tool_call_id: invocation.toolCallId,
|
|
2926
|
+
tool_name: invocation.toolName,
|
|
2927
|
+
app_id: context.appId
|
|
2928
|
+
}
|
|
2929
|
+
});
|
|
2930
|
+
return parseDecision(response);
|
|
2931
|
+
} catch {
|
|
2932
|
+
return false;
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
};
|
|
2936
|
+
|
|
2937
|
+
// src/acp/ACPTelemetry.ts
|
|
2938
|
+
var ACPTelemetry = class {
|
|
2939
|
+
constructor(sink) {
|
|
2940
|
+
this.sink = sink;
|
|
2941
|
+
}
|
|
2942
|
+
emit(event) {
|
|
2943
|
+
if (!this.sink) return;
|
|
2944
|
+
try {
|
|
2945
|
+
const output = this.sink.emit(event);
|
|
2946
|
+
if (output && typeof output.then === "function") {
|
|
2947
|
+
void output.catch(() => {
|
|
2948
|
+
});
|
|
2949
|
+
}
|
|
2950
|
+
} catch {
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
};
|
|
2954
|
+
|
|
2955
|
+
// src/acp/ACPContractAdapter.ts
|
|
2956
|
+
function isRecord7(value) {
|
|
2957
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2958
|
+
}
|
|
2959
|
+
function getString(value) {
|
|
2960
|
+
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
2961
|
+
}
|
|
2962
|
+
function resolveTaskId(payload) {
|
|
2963
|
+
return getString(payload.task_id) || getString(payload.task_uuid);
|
|
2964
|
+
}
|
|
2965
|
+
function resolveToolCallId2(payload) {
|
|
2966
|
+
const direct = getString(payload.tool_call_id);
|
|
2967
|
+
if (direct) return direct;
|
|
2968
|
+
if (isRecord7(payload.payload)) {
|
|
2969
|
+
const nestedPayload = getString(payload.payload.tool_call_id);
|
|
2970
|
+
if (nestedPayload) return nestedPayload;
|
|
2971
|
+
}
|
|
2972
|
+
if (isRecord7(payload.data)) {
|
|
2973
|
+
const nestedData = getString(payload.data.tool_call_id);
|
|
2974
|
+
if (nestedData) return nestedData;
|
|
2975
|
+
}
|
|
2976
|
+
return void 0;
|
|
2977
|
+
}
|
|
2978
|
+
function isTerminalStatus(status) {
|
|
2979
|
+
return status === "completed" || status === "failed";
|
|
2980
|
+
}
|
|
2981
|
+
var ACPContractAdapter = class {
|
|
2982
|
+
constructor(options) {
|
|
2983
|
+
this.taskReferences = /* @__PURE__ */ new Map();
|
|
2984
|
+
this.toolCallReferences = /* @__PURE__ */ new Map();
|
|
2985
|
+
this.runtime = options.runtime;
|
|
2986
|
+
this.notifier = options.notifier;
|
|
2987
|
+
this.mapper = new ACPEventMapper();
|
|
2988
|
+
this.permissionBridge = new ACPPermissionBridge({
|
|
2989
|
+
notifier: options.notifier,
|
|
2990
|
+
enabled: options.requestPermission === true,
|
|
2991
|
+
buildPermissionOptions: options.buildPermissionOptions
|
|
2992
|
+
});
|
|
2993
|
+
this.telemetry = new ACPTelemetry(options.telemetry);
|
|
2994
|
+
this.runtimeUnsubscribe = this.runtime.onExecutionEvent((event) => {
|
|
2995
|
+
void this.handleRuntimeEvent(event);
|
|
2996
|
+
});
|
|
2997
|
+
}
|
|
2998
|
+
dispose() {
|
|
2999
|
+
this.runtimeUnsubscribe();
|
|
3000
|
+
this.taskReferences.clear();
|
|
3001
|
+
this.toolCallReferences.clear();
|
|
3002
|
+
}
|
|
3003
|
+
async executeTool(invocation, context) {
|
|
3004
|
+
const reference = this.mapper.createReference(invocation, context);
|
|
3005
|
+
this.rememberReference(reference);
|
|
3006
|
+
await this.notify(this.mapper.buildPendingUpdate(invocation, reference));
|
|
3007
|
+
const permissionGranted = await this.permissionBridge.requestToolPermission(
|
|
3008
|
+
invocation,
|
|
3009
|
+
context
|
|
3010
|
+
);
|
|
3011
|
+
this.telemetry.emit({
|
|
3012
|
+
phase: "permission",
|
|
3013
|
+
result: permissionGranted ? "ok" : "failed",
|
|
3014
|
+
sessionId: context.sessionId,
|
|
3015
|
+
toolCallId: invocation.toolCallId,
|
|
3016
|
+
toolName: invocation.toolName
|
|
3017
|
+
});
|
|
3018
|
+
if (!permissionGranted) {
|
|
3019
|
+
const result2 = {
|
|
3020
|
+
status: "failed",
|
|
3021
|
+
tool_call_id: invocation.toolCallId,
|
|
3022
|
+
error: {
|
|
3023
|
+
code: "permission_denied",
|
|
3024
|
+
message: `Permission denied for ${invocation.toolName}`,
|
|
3025
|
+
retryable: false
|
|
3026
|
+
}
|
|
3027
|
+
};
|
|
3028
|
+
await this.notify(this.mapper.buildResultUpdate(result2, reference));
|
|
3029
|
+
this.cleanupReference(reference, result2);
|
|
3030
|
+
return result2;
|
|
3031
|
+
}
|
|
3032
|
+
const result = await this.runtime.executeToolCall(
|
|
3033
|
+
{
|
|
3034
|
+
tool_call_id: invocation.toolCallId,
|
|
3035
|
+
tool_name: invocation.toolName,
|
|
3036
|
+
args: invocation.args
|
|
3037
|
+
},
|
|
3038
|
+
{
|
|
3039
|
+
appId: context.appId,
|
|
3040
|
+
userId: context.userId,
|
|
3041
|
+
workspaceId: context.workspaceId,
|
|
3042
|
+
provider: context.provider,
|
|
3043
|
+
namespace: context.namespace
|
|
3044
|
+
}
|
|
3045
|
+
);
|
|
3046
|
+
const normalizedResult = {
|
|
3047
|
+
...result,
|
|
3048
|
+
tool_call_id: result.tool_call_id || invocation.toolCallId
|
|
3049
|
+
};
|
|
3050
|
+
if (normalizedResult.task_id) {
|
|
3051
|
+
this.taskReferences.set(normalizedResult.task_id, reference);
|
|
3052
|
+
}
|
|
3053
|
+
await this.notify(this.mapper.buildResultUpdate(normalizedResult, reference));
|
|
3054
|
+
this.telemetry.emit({
|
|
3055
|
+
phase: "execute",
|
|
3056
|
+
result: normalizedResult.status === "failed" ? "failed" : "ok",
|
|
3057
|
+
sessionId: reference.sessionId,
|
|
3058
|
+
toolCallId: reference.toolCallId,
|
|
3059
|
+
toolName: invocation.toolName,
|
|
3060
|
+
taskId: normalizedResult.task_id,
|
|
3061
|
+
attemptId: normalizedResult.attempt_id,
|
|
3062
|
+
status: normalizedResult.status === "queued" ? "in_progress" : normalizedResult.status === "completed" ? "completed" : normalizedResult.status === "failed" ? "failed" : void 0,
|
|
3063
|
+
error: normalizedResult.error?.message
|
|
3064
|
+
});
|
|
3065
|
+
this.cleanupReference(reference, normalizedResult);
|
|
3066
|
+
return normalizedResult;
|
|
3067
|
+
}
|
|
3068
|
+
ingestContractCallback(payload, context) {
|
|
3069
|
+
const initialTaskId = resolveTaskId(payload);
|
|
3070
|
+
const initialToolCallId = resolveToolCallId2(payload);
|
|
3071
|
+
if (initialTaskId) {
|
|
3072
|
+
const existingByTask = this.taskReferences.get(initialTaskId);
|
|
3073
|
+
const existingByCall = initialToolCallId ? this.toolCallReferences.get(initialToolCallId) : void 0;
|
|
3074
|
+
const reference = existingByTask || existingByCall || {
|
|
3075
|
+
sessionId: context.sessionId,
|
|
3076
|
+
toolCallId: initialToolCallId || initialTaskId,
|
|
3077
|
+
appId: "unknown",
|
|
3078
|
+
userId: "unknown",
|
|
3079
|
+
title: initialToolCallId || initialTaskId,
|
|
3080
|
+
kind: "other"
|
|
3081
|
+
};
|
|
3082
|
+
this.taskReferences.set(initialTaskId, reference);
|
|
3083
|
+
this.toolCallReferences.set(reference.toolCallId, reference);
|
|
3084
|
+
}
|
|
3085
|
+
const event = this.runtime.ingestExecutionEvent(payload);
|
|
3086
|
+
this.telemetry.emit({
|
|
3087
|
+
phase: "ingest",
|
|
3088
|
+
result: event ? "ok" : "skipped",
|
|
3089
|
+
sessionId: context.sessionId,
|
|
3090
|
+
toolCallId: event?.tool_call_id,
|
|
3091
|
+
taskId: event?.task_id,
|
|
3092
|
+
attemptId: event?.attempt_id,
|
|
3093
|
+
eventId: event?.event_id,
|
|
3094
|
+
eventType: event?.event_type
|
|
3095
|
+
});
|
|
3096
|
+
return event;
|
|
3097
|
+
}
|
|
3098
|
+
async handleRuntimeEvent(event) {
|
|
3099
|
+
const reference = this.resolveReferenceForEvent(event);
|
|
3100
|
+
if (!reference) {
|
|
3101
|
+
this.telemetry.emit({
|
|
3102
|
+
phase: "runtime_event",
|
|
3103
|
+
result: "skipped",
|
|
3104
|
+
toolCallId: event.tool_call_id,
|
|
3105
|
+
taskId: event.task_id,
|
|
3106
|
+
attemptId: event.attempt_id,
|
|
3107
|
+
eventId: event.event_id,
|
|
3108
|
+
eventType: event.event_type
|
|
3109
|
+
});
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
this.taskReferences.set(event.task_id, reference);
|
|
3113
|
+
const update = this.mapper.buildLifecycleUpdate(event, reference);
|
|
3114
|
+
if (!update) {
|
|
3115
|
+
this.telemetry.emit({
|
|
3116
|
+
phase: "runtime_event",
|
|
3117
|
+
result: "skipped",
|
|
3118
|
+
sessionId: reference.sessionId,
|
|
3119
|
+
toolCallId: reference.toolCallId,
|
|
3120
|
+
taskId: event.task_id,
|
|
3121
|
+
attemptId: event.attempt_id,
|
|
3122
|
+
eventId: event.event_id,
|
|
3123
|
+
eventType: event.event_type
|
|
3124
|
+
});
|
|
3125
|
+
return;
|
|
3126
|
+
}
|
|
3127
|
+
await this.notify(update);
|
|
3128
|
+
this.telemetry.emit({
|
|
3129
|
+
phase: "runtime_event",
|
|
3130
|
+
result: "ok",
|
|
3131
|
+
sessionId: reference.sessionId,
|
|
3132
|
+
toolCallId: reference.toolCallId,
|
|
3133
|
+
taskId: event.task_id,
|
|
3134
|
+
attemptId: event.attempt_id,
|
|
3135
|
+
eventId: event.event_id,
|
|
3136
|
+
eventType: event.event_type,
|
|
3137
|
+
status: update.update.status
|
|
3138
|
+
});
|
|
3139
|
+
if (isTerminalStatus(update.update.status)) {
|
|
3140
|
+
this.taskReferences.delete(event.task_id);
|
|
3141
|
+
this.toolCallReferences.delete(reference.toolCallId);
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
resolveReferenceForEvent(event) {
|
|
3145
|
+
const byTask = this.taskReferences.get(event.task_id);
|
|
3146
|
+
if (byTask) return byTask;
|
|
3147
|
+
const byToolCall = this.toolCallReferences.get(event.tool_call_id);
|
|
3148
|
+
if (byToolCall) return byToolCall;
|
|
3149
|
+
return void 0;
|
|
3150
|
+
}
|
|
3151
|
+
rememberReference(reference) {
|
|
3152
|
+
this.toolCallReferences.set(reference.toolCallId, reference);
|
|
3153
|
+
}
|
|
3154
|
+
cleanupReference(reference, result) {
|
|
3155
|
+
const status = result.status === "queued" ? "in_progress" : result.status === "completed" ? "completed" : result.status === "failed" ? "failed" : "failed";
|
|
3156
|
+
if (!isTerminalStatus(status)) return;
|
|
3157
|
+
this.toolCallReferences.delete(reference.toolCallId);
|
|
3158
|
+
if (result.task_id) {
|
|
3159
|
+
this.taskReferences.delete(result.task_id);
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
async notify(update) {
|
|
3163
|
+
try {
|
|
3164
|
+
await this.notifier.notify("session/update", update);
|
|
3165
|
+
this.telemetry.emit({
|
|
3166
|
+
phase: "notify",
|
|
3167
|
+
result: "ok",
|
|
3168
|
+
sessionId: update.sessionId,
|
|
3169
|
+
toolCallId: update.update.toolCallId,
|
|
3170
|
+
status: update.update.status,
|
|
3171
|
+
metadata: {
|
|
3172
|
+
type: update.update.type
|
|
3173
|
+
}
|
|
3174
|
+
});
|
|
3175
|
+
} catch (error) {
|
|
3176
|
+
const reference = this.toolCallReferences.get(update.update.toolCallId);
|
|
3177
|
+
this.telemetry.emit({
|
|
3178
|
+
phase: "notify",
|
|
3179
|
+
result: "failed",
|
|
3180
|
+
sessionId: update.sessionId,
|
|
3181
|
+
toolCallId: update.update.toolCallId,
|
|
3182
|
+
status: update.update.status,
|
|
3183
|
+
error: error instanceof Error ? error.message : "Unknown notify error"
|
|
3184
|
+
});
|
|
3185
|
+
if (!reference) return;
|
|
3186
|
+
const failureUpdate = this.mapper.buildNotifyFailureUpdate(reference, error);
|
|
3187
|
+
try {
|
|
3188
|
+
await this.notifier.notify("session/update", failureUpdate);
|
|
3189
|
+
} catch {
|
|
3190
|
+
}
|
|
3191
|
+
}
|
|
3192
|
+
}
|
|
3193
|
+
};
|
|
3194
|
+
|
|
1716
3195
|
// src/index.ts
|
|
1717
3196
|
var _RealtimeXSDK = class _RealtimeXSDK {
|
|
1718
3197
|
constructor(config = {}) {
|
|
@@ -1739,6 +3218,13 @@ var _RealtimeXSDK = class _RealtimeXSDK {
|
|
|
1739
3218
|
this.agent = new AgentModule(this.httpClient);
|
|
1740
3219
|
this.mcp = new MCPModule(this.realtimexUrl, this.appId, this.appName, this.apiKey);
|
|
1741
3220
|
this.contract = new ContractModule(this.realtimexUrl, this.appName, this.appId, this.apiKey);
|
|
3221
|
+
this.contractRuntime = new ContractRuntime({
|
|
3222
|
+
baseUrl: this.realtimexUrl,
|
|
3223
|
+
appId: this.appId || void 0,
|
|
3224
|
+
appName: this.appName,
|
|
3225
|
+
apiKey: this.apiKey,
|
|
3226
|
+
permissions: this.permissions
|
|
3227
|
+
});
|
|
1742
3228
|
if (this.permissions.length > 0 && this.appId && !this.apiKey) {
|
|
1743
3229
|
this.register().catch((err) => {
|
|
1744
3230
|
console.error("[RealtimeX SDK] Auto-registration failed:", err.message);
|
|
@@ -1839,6 +3325,10 @@ var _RealtimeXSDK = class _RealtimeXSDK {
|
|
|
1839
3325
|
_RealtimeXSDK.DEFAULT_REALTIMEX_URL = "http://localhost:3001";
|
|
1840
3326
|
var RealtimeXSDK = _RealtimeXSDK;
|
|
1841
3327
|
export {
|
|
3328
|
+
ACPContractAdapter,
|
|
3329
|
+
ACPEventMapper,
|
|
3330
|
+
ACPPermissionBridge,
|
|
3331
|
+
ACPTelemetry,
|
|
1842
3332
|
ActivitiesModule,
|
|
1843
3333
|
AgentModule,
|
|
1844
3334
|
ApiModule,
|
|
@@ -1846,7 +3336,16 @@ export {
|
|
|
1846
3336
|
CONTRACT_EVENT_ID_HEADER,
|
|
1847
3337
|
CONTRACT_SIGNATURE_ALGORITHM,
|
|
1848
3338
|
CONTRACT_SIGNATURE_HEADER,
|
|
3339
|
+
ClaudeToolAdapter,
|
|
3340
|
+
CodexToolAdapter,
|
|
3341
|
+
ContractCache,
|
|
3342
|
+
ContractClient,
|
|
3343
|
+
ContractError,
|
|
3344
|
+
ContractHttpClient,
|
|
1849
3345
|
ContractModule,
|
|
3346
|
+
ContractRuntime,
|
|
3347
|
+
ContractValidationError,
|
|
3348
|
+
GeminiToolAdapter,
|
|
1850
3349
|
LLMModule,
|
|
1851
3350
|
LLMPermissionError,
|
|
1852
3351
|
LLMProviderError,
|
|
@@ -1856,9 +3355,17 @@ export {
|
|
|
1856
3355
|
PermissionRequiredError,
|
|
1857
3356
|
PortModule,
|
|
1858
3357
|
RealtimeXSDK,
|
|
3358
|
+
RetryPolicy,
|
|
3359
|
+
RuntimeTransportError,
|
|
1859
3360
|
STTModule,
|
|
3361
|
+
ScopeDeniedError,
|
|
3362
|
+
ScopeGuard,
|
|
3363
|
+
StaticAuthProvider,
|
|
1860
3364
|
TTSModule,
|
|
1861
3365
|
TaskModule,
|
|
3366
|
+
ToolNotFoundError,
|
|
3367
|
+
ToolProjector,
|
|
3368
|
+
ToolValidationError,
|
|
1862
3369
|
VectorStore,
|
|
1863
3370
|
WebhookModule,
|
|
1864
3371
|
buildContractIdempotencyKey,
|
|
@@ -1868,6 +3375,9 @@ export {
|
|
|
1868
3375
|
hashContractPayload,
|
|
1869
3376
|
normalizeAttemptId,
|
|
1870
3377
|
normalizeContractEvent,
|
|
3378
|
+
normalizeLocalAppContractV1,
|
|
3379
|
+
normalizeSchema,
|
|
1871
3380
|
parseAttemptRunId,
|
|
1872
|
-
signContractEvent
|
|
3381
|
+
signContractEvent,
|
|
3382
|
+
toStableToolName
|
|
1873
3383
|
};
|