@ceki/sdk 1.13.0 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1990,6 +1990,380 @@ var Client = class _Client {
1990
1990
  async function connect(apiKey, opts) {
1991
1991
  return Client.create(apiKey, opts);
1992
1992
  }
1993
+
1994
+ // src/contract.ts
1995
+ var ROLE_REVIEWER = 5;
1996
+ var ROLE_QA = 6;
1997
+ var ContractError = class extends Error {
1998
+ constructor(message) {
1999
+ super(message);
2000
+ this.name = "ContractError";
2001
+ }
2002
+ };
2003
+ function parseBenefitable(value) {
2004
+ if (value === null || value === void 0 || value === "") return null;
2005
+ const parts = String(value).split(":");
2006
+ if (parts.length !== 2) {
2007
+ throw new Error(`benefitable must be 'type:id', got: ${JSON.stringify(value)}`);
2008
+ }
2009
+ const [btype, bid] = parts;
2010
+ const num = Number.parseInt(bid, 10);
2011
+ if (!Number.isFinite(num) || Number.isNaN(num)) {
2012
+ throw new Error(`benefitable id must be int, got: ${JSON.stringify(bid)}`);
2013
+ }
2014
+ return { type: btype, value: num };
2015
+ }
2016
+ function parseParticipant(value, roleId) {
2017
+ const base = parseBenefitable(value);
2018
+ if (base === null) return null;
2019
+ return {
2020
+ participable_id: base.value,
2021
+ type: base.type,
2022
+ role_id: roleId
2023
+ };
2024
+ }
2025
+ function cleanArgs(o) {
2026
+ const out = {};
2027
+ for (const [k, v] of Object.entries(o)) {
2028
+ if (v !== void 0 && v !== null) {
2029
+ out[k] = v;
2030
+ }
2031
+ }
2032
+ return out;
2033
+ }
2034
+ function deriveLabel(desc) {
2035
+ if (!desc) return "progress";
2036
+ const lines = String(desc).split(/\r?\n/);
2037
+ for (const ln of lines) {
2038
+ const t = ln.trim();
2039
+ if (t) return t.slice(0, 60);
2040
+ }
2041
+ return "progress";
2042
+ }
2043
+ function contractIdsFromEnv() {
2044
+ const raw = (process.env.CEKI_CONTRACT_IDS ?? "").trim();
2045
+ if (!raw) return [];
2046
+ try {
2047
+ const parsed = JSON.parse(raw);
2048
+ if (Array.isArray(parsed)) return parsed.map((x) => String(x));
2049
+ } catch {
2050
+ }
2051
+ return raw.replace(/\[/g, "").replace(/\]/g, "").split(",").map((s) => s.trim()).filter((s) => s.length > 0);
2052
+ }
2053
+ function resolveEndpoint() {
2054
+ const override = process.env.CEKI_AGENT_MCP_ENDPOINT;
2055
+ if (override) return override.replace(/\/+$/, "");
2056
+ const base = (process.env.CEKI_API_URL ?? defaults.apiUrl).replace(/\/+$/, "");
2057
+ return `${base}/mcp/agent`;
2058
+ }
2059
+ function resolveApiBase() {
2060
+ const override = process.env.CEKI_API_BASE;
2061
+ if (override) return override.replace(/\/+$/, "");
2062
+ const base = (process.env.CEKI_API_URL ?? defaults.apiUrl).replace(/\/+$/, "");
2063
+ return `${base}/api`;
2064
+ }
2065
+ function resolveToken() {
2066
+ return process.env.CEKI_AGENT_TOKEN ?? process.env.CEKI_API_KEY ?? "";
2067
+ }
2068
+ var TOOL_MAP = {
2069
+ list: "get-my-contracts",
2070
+ members: "get-contract-members",
2071
+ tasks: "get-contract-events",
2072
+ "my-jobs": "get-my-jobs",
2073
+ task: "get-event",
2074
+ children: "get-event-children",
2075
+ history: "get-event-history",
2076
+ create: "create-contract-event",
2077
+ comment: "comment",
2078
+ propose: "propose-correction",
2079
+ vote: "vote-correction"
2080
+ };
2081
+ var FetchHttpClient = class {
2082
+ constructor(timeoutMs) {
2083
+ this.timeoutMs = timeoutMs;
2084
+ }
2085
+ timeoutMs;
2086
+ withTimeout() {
2087
+ const ctl = new AbortController();
2088
+ const t = setTimeout(() => ctl.abort(), this.timeoutMs);
2089
+ return { signal: ctl.signal, cancel: () => clearTimeout(t) };
2090
+ }
2091
+ async post(url, init) {
2092
+ const { signal, cancel } = this.withTimeout();
2093
+ try {
2094
+ const r = await fetch(url, { method: "POST", headers: init.headers, body: init.body, signal });
2095
+ const text = await r.text();
2096
+ return {
2097
+ status: r.status,
2098
+ text: async () => text,
2099
+ json: async () => {
2100
+ try {
2101
+ return JSON.parse(text);
2102
+ } catch {
2103
+ return { raw: text };
2104
+ }
2105
+ }
2106
+ };
2107
+ } finally {
2108
+ cancel();
2109
+ }
2110
+ }
2111
+ async get(url, init) {
2112
+ const { signal, cancel } = this.withTimeout();
2113
+ try {
2114
+ const r = await fetch(url, { method: "GET", headers: init.headers, signal });
2115
+ const text = await r.text();
2116
+ return {
2117
+ status: r.status,
2118
+ text: async () => text,
2119
+ json: async () => {
2120
+ try {
2121
+ return JSON.parse(text);
2122
+ } catch {
2123
+ return { raw: text };
2124
+ }
2125
+ }
2126
+ };
2127
+ } finally {
2128
+ cancel();
2129
+ }
2130
+ }
2131
+ };
2132
+ var ContractClient = class {
2133
+ endpoint;
2134
+ apiBase;
2135
+ token;
2136
+ http;
2137
+ constructor(opts = {}) {
2138
+ this.endpoint = (opts.endpoint ?? resolveEndpoint()).replace(/\/+$/, "");
2139
+ this.apiBase = (opts.apiBase ?? resolveApiBase()).replace(/\/+$/, "");
2140
+ this.token = opts.token !== void 0 ? opts.token : resolveToken();
2141
+ this.http = opts.http ?? new FetchHttpClient(opts.timeoutMs ?? 3e4);
2142
+ }
2143
+ headers() {
2144
+ if (!this.token) {
2145
+ throw new ContractError("agent token not set (CEKI_AGENT_TOKEN or CEKI_API_KEY)");
2146
+ }
2147
+ return {
2148
+ "Content-Type": "application/json",
2149
+ Accept: "application/json",
2150
+ Authorization: `Bearer ${this.token}`
2151
+ };
2152
+ }
2153
+ async rpc(method, params) {
2154
+ const body = JSON.stringify({
2155
+ jsonrpc: "2.0",
2156
+ id: Date.now(),
2157
+ method,
2158
+ params
2159
+ });
2160
+ const resp = await this.http.post(this.endpoint, { headers: this.headers(), body });
2161
+ let parsed;
2162
+ try {
2163
+ parsed = await resp.json();
2164
+ } catch {
2165
+ parsed = { raw: await resp.text() };
2166
+ }
2167
+ if (resp.status !== 200) {
2168
+ const snippet = JSON.stringify(parsed).slice(0, 400);
2169
+ throw new ContractError(`HTTP ${resp.status}: ${snippet}`);
2170
+ }
2171
+ return parsed ?? {};
2172
+ }
2173
+ /** Call MCP tool; unwrap content[].text (JSON-parsed) or structuredContent. */
2174
+ async call(tool, args = {}) {
2175
+ const body = await this.rpc("tools/call", { name: tool, arguments: args });
2176
+ if (body["error"]) {
2177
+ throw new ContractError(`${tool} \u2192 ${JSON.stringify(body["error"]).slice(0, 400)}`);
2178
+ }
2179
+ const result = body["result"] ?? {};
2180
+ const content = result["content"];
2181
+ if (Array.isArray(content)) {
2182
+ const texts = content.filter((c) => c["type"] === "text").map((c) => String(c["text"] ?? ""));
2183
+ const joined = texts.join("\n");
2184
+ try {
2185
+ return JSON.parse(joined);
2186
+ } catch {
2187
+ return joined;
2188
+ }
2189
+ }
2190
+ if (result["structuredContent"] !== void 0) return result["structuredContent"];
2191
+ return result;
2192
+ }
2193
+ async tools() {
2194
+ const body = await this.rpc("tools/list", {});
2195
+ const result = body["result"] ?? {};
2196
+ const tools = result["tools"];
2197
+ if (Array.isArray(tools)) return tools.map((t) => t["name"]);
2198
+ return body;
2199
+ }
2200
+ async raw(tool, args = {}) {
2201
+ return this.call(tool, args);
2202
+ }
2203
+ // ── domain helpers ──────────────────────────────────────────────
2204
+ async listContracts() {
2205
+ return this.call(TOOL_MAP.list, {});
2206
+ }
2207
+ async members(contractId) {
2208
+ return this.call(TOOL_MAP.members, { contract_id: Number(contractId) });
2209
+ }
2210
+ async tasks(contractId) {
2211
+ return this.call(TOOL_MAP.tasks, { contract_id: Number(contractId) });
2212
+ }
2213
+ async myJobs() {
2214
+ return this.call(TOOL_MAP["my-jobs"], {});
2215
+ }
2216
+ async task(eventId) {
2217
+ return this.call(TOOL_MAP.task, { event_id: Number(eventId) });
2218
+ }
2219
+ async children(eventId) {
2220
+ return this.call(TOOL_MAP.children, { event_id: Number(eventId) });
2221
+ }
2222
+ async history(eventId, opts = {}) {
2223
+ const args = cleanArgs({ event_id: Number(eventId), limit: opts.limit });
2224
+ return this.call(TOOL_MAP.history, args);
2225
+ }
2226
+ async create(contractId, opts) {
2227
+ const users = [];
2228
+ const rev = parseParticipant(opts.reviewer, ROLE_REVIEWER);
2229
+ if (rev !== null) users.push(rev);
2230
+ const qa = parseParticipant(opts.qa, ROLE_QA);
2231
+ if (qa !== null) users.push(qa);
2232
+ if (opts.participants && opts.participants.length) {
2233
+ users.push(...opts.participants);
2234
+ }
2235
+ const args = cleanArgs({
2236
+ contract_id: Number(contractId),
2237
+ label: opts.label,
2238
+ type_id: opts.type,
2239
+ status_id: opts.status,
2240
+ kal_schedule_id: opts.kalScheduleId,
2241
+ start: opts.start,
2242
+ end: opts.end,
2243
+ timezone: opts.timezone,
2244
+ date: opts.date,
2245
+ duration: opts.duration,
2246
+ amount: opts.amount,
2247
+ currency: opts.currency,
2248
+ description: opts.description,
2249
+ data: opts.data,
2250
+ benefitable: opts.benefitable !== void 0 ? parseBenefitable(opts.benefitable) : void 0,
2251
+ users: users.length > 0 ? users : void 0
2252
+ });
2253
+ return this.call(TOOL_MAP.create, args);
2254
+ }
2255
+ async comment(eventId, opts = {}) {
2256
+ const args = cleanArgs({
2257
+ event_id: Number(eventId),
2258
+ label: opts.label,
2259
+ type_id: opts.type,
2260
+ status_id: opts.status,
2261
+ start: opts.start,
2262
+ end: opts.end,
2263
+ date: opts.date,
2264
+ duration: opts.duration,
2265
+ amount: opts.amount,
2266
+ currency: opts.currency,
2267
+ description: opts.description,
2268
+ benefitable: opts.benefitable !== void 0 ? parseBenefitable(opts.benefitable) : void 0
2269
+ });
2270
+ return this.call(TOOL_MAP.comment, args);
2271
+ }
2272
+ async propose(eventId, opts = {}) {
2273
+ const args = cleanArgs({
2274
+ event_id: Number(eventId),
2275
+ status_id: opts.status,
2276
+ label: opts.label,
2277
+ description: opts.description,
2278
+ start: opts.start,
2279
+ end: opts.end,
2280
+ date: opts.date,
2281
+ duration: opts.duration,
2282
+ amount: opts.amount,
2283
+ currency: opts.currency,
2284
+ benefitable: opts.benefitable !== void 0 ? parseBenefitable(opts.benefitable) : void 0
2285
+ });
2286
+ return this.call(TOOL_MAP.propose, args);
2287
+ }
2288
+ /** Status correction (optional) + progress comment in one shot.
2289
+ *
2290
+ * The event's own description is NOT touched. `desc` becomes the
2291
+ * body of a child comment-event, not a label/description overwrite
2292
+ * on the parent event. Use this for Hand/QA/Reviewer progress
2293
+ * reports — `propose --desc` would clobber the parent spec.
2294
+ */
2295
+ async progress(eventId, opts) {
2296
+ let statusResult = null;
2297
+ if (opts.status !== void 0 && opts.status !== null) {
2298
+ statusResult = await this.propose(eventId, { status: Number(opts.status) });
2299
+ }
2300
+ const label = deriveLabel(opts.desc);
2301
+ const commentResult = await this.comment(eventId, { label, description: opts.desc });
2302
+ return { status_correction: statusResult, comment: commentResult };
2303
+ }
2304
+ async vote(eventId, ids, vote) {
2305
+ return this.call(TOOL_MAP.vote, {
2306
+ event_id: Number(eventId),
2307
+ ids: ids.map((i) => Number(i)),
2308
+ vote: Boolean(vote)
2309
+ });
2310
+ }
2311
+ // ── polling (REST, not MCP) ────────────────────────────────────
2312
+ /** GET /agent/polling. Returns [] on 429 (rate-limit, 10/min/token). */
2313
+ async poll() {
2314
+ const resp = await this.http.get(`${this.apiBase}/agent/polling`, {
2315
+ headers: { Accept: "application/json", Authorization: `Bearer ${this.token}` }
2316
+ });
2317
+ if (resp.status === 429) return [];
2318
+ if (resp.status !== 200) {
2319
+ let body2;
2320
+ try {
2321
+ body2 = await resp.json();
2322
+ } catch {
2323
+ body2 = await resp.text();
2324
+ }
2325
+ throw new ContractError(`polling HTTP ${resp.status}: ${JSON.stringify(body2).slice(0, 300)}`);
2326
+ }
2327
+ const body = await resp.json();
2328
+ if (Array.isArray(body)) return body;
2329
+ if (body && typeof body === "object") {
2330
+ const obj = body;
2331
+ for (const k of ["notifications", "data", "items"]) {
2332
+ const v = obj[k];
2333
+ if (Array.isArray(v)) return v;
2334
+ }
2335
+ }
2336
+ return [];
2337
+ }
2338
+ };
2339
+
2340
+ // src/timelog.ts
2341
+ var TOOL_MAP2 = {
2342
+ start: "timelog-start",
2343
+ stop: "timelog-stop",
2344
+ check: "timelog-check"
2345
+ };
2346
+ var TimelogClient = class {
2347
+ c;
2348
+ constructor(opts = {}) {
2349
+ if (opts.contract) {
2350
+ this.c = opts.contract;
2351
+ } else {
2352
+ this.c = new ContractClient(opts);
2353
+ }
2354
+ }
2355
+ async start(eventId) {
2356
+ return this.c.call(TOOL_MAP2.start, { event_id: Number(eventId) });
2357
+ }
2358
+ async stop(eventId, label) {
2359
+ const args = { event_id: Number(eventId) };
2360
+ if (label !== void 0 && label !== null) args["label"] = label;
2361
+ return this.c.call(TOOL_MAP2.stop, args);
2362
+ }
2363
+ async check(eventId) {
2364
+ return this.c.call(TOOL_MAP2.check, { event_id: Number(eventId) });
2365
+ }
2366
+ };
1993
2367
  export {
1994
2368
  AuthError,
1995
2369
  Browser,
@@ -2002,18 +2376,28 @@ export {
2002
2376
  ChatSendFailed,
2003
2377
  Client,
2004
2378
  ConnectionLost,
2379
+ ContractClient,
2380
+ ContractError,
2005
2381
  HumanProfile,
2006
2382
  Humanizer,
2007
2383
  InsufficientFunds,
2008
2384
  NotOwner,
2009
2385
  ProviderDisconnected,
2010
2386
  ProviderOffline,
2387
+ ROLE_QA,
2388
+ ROLE_REVIEWER,
2011
2389
  RateLimitExceeded,
2012
2390
  SessionEnded,
2013
2391
  SessionExpired,
2014
2392
  SessionNotFound,
2393
+ TimelogClient,
2015
2394
  TimeoutError,
2016
2395
  TransportError,
2017
- connect
2396
+ cleanArgs,
2397
+ connect,
2398
+ contractIdsFromEnv,
2399
+ deriveLabel,
2400
+ parseBenefitable,
2401
+ parseParticipant
2018
2402
  };
2019
2403
  //# sourceMappingURL=index.js.map