@ceki/sdk 1.12.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
@@ -655,27 +655,39 @@ var Browser = class _Browser {
655
655
  this._sendRaw(msg);
656
656
  });
657
657
  }
658
- async navigate(url, timeout = 3e4) {
659
- if (this._humanizer) await this._humanizer.before("navigate");
658
+ // task 427 — per-call kill-switch. human=false bypasses humanizer timings
659
+ // AND tells the extension to skip mouse-jitter via the `_ceki_raw` marker
660
+ // (see cdp.ts). human=true forces humanizer; human undefined = session
661
+ // default. Global env CEKI_HUMAN_DISABLE=1 nulls this._humanizer in the
662
+ // constructor so all paths become raw.
663
+ _humanizeForCall(human) {
664
+ if (human === false) return null;
665
+ return this._humanizer;
666
+ }
667
+ async navigate(url, timeout = 3e4, opts) {
668
+ const h = this._humanizeForCall(opts?.human);
669
+ if (h) await h.before("navigate");
660
670
  const result = await this.send({ method: "Page.navigate", params: { url } }, timeout);
661
- if (this._humanizer) await this._humanizer.after("navigate");
671
+ if (h) await h.after("navigate");
662
672
  return {
663
673
  url: String(result?.url ?? url),
664
674
  frameId: result?.frameId ? String(result.frameId) : void 0
665
675
  };
666
676
  }
667
- async click(x, y) {
668
- if (this._humanizer) await this._humanizer.before("click");
677
+ async click(x, y, opts) {
678
+ const h = this._humanizeForCall(opts?.human);
679
+ if (h) await h.before("click");
680
+ const rawFlag = h === null ? { _ceki_raw: true } : {};
669
681
  await this.send({
670
682
  method: "Input.dispatchMouseEvent",
671
- params: { type: "mousePressed", x, y, button: "left", clickCount: 1 }
683
+ params: { type: "mousePressed", x, y, button: "left", clickCount: 1, ...rawFlag }
672
684
  });
673
685
  await this.send({
674
686
  method: "Input.dispatchMouseEvent",
675
687
  params: { type: "mouseReleased", x, y, button: "left", clickCount: 1 }
676
688
  });
677
689
  this._lastPointer = [x, y];
678
- if (this._humanizer) await this._humanizer.after("click");
690
+ if (h) await h.after("click");
679
691
  }
680
692
  async _sendKeystroke(char) {
681
693
  const mapping = keymapForChar(char);
@@ -721,9 +733,10 @@ var Browser = class _Browser {
721
733
  });
722
734
  }
723
735
  }
724
- async type(text) {
725
- if (this._humanizer) {
726
- await this._humanizer.before("type");
736
+ async type(text, opts) {
737
+ const h = this._humanizeForCall(opts?.human);
738
+ if (h) {
739
+ await h.before("type");
727
740
  if (this._lastPointer) {
728
741
  const [px, py] = this._lastPointer;
729
742
  await this.send({
@@ -736,10 +749,10 @@ var Browser = class _Browser {
736
749
  });
737
750
  }
738
751
  }
739
- const human = this._humanizer ? ["natural", "careful"].includes(this._humanizer.profile.name) ? this._humanizer.profile.name : "natural" : null;
752
+ const human = h ? ["natural", "careful"].includes(h.profile.name) ? h.profile.name : "natural" : null;
740
753
  await this.send({ method: "Ceki.typeText", params: { text, human } });
741
- if (this._humanizer) {
742
- await this._humanizer.after("type");
754
+ if (h) {
755
+ await h.after("type");
743
756
  }
744
757
  }
745
758
  async scroll(opts) {
@@ -747,13 +760,14 @@ var Browser = class _Browser {
747
760
  const y = opts?.y ?? 0;
748
761
  const deltaX = opts?.deltaX ?? 0;
749
762
  const deltaY = opts?.deltaY ?? -300;
750
- if (this._humanizer) await this._humanizer.before("scroll");
763
+ const h = this._humanizeForCall(opts?.human);
764
+ if (h) await h.before("scroll");
751
765
  await this.send({
752
766
  method: "Input.dispatchMouseEvent",
753
767
  params: { type: "mouseWheel", x, y, deltaX, deltaY }
754
768
  });
755
769
  this._lastPointer = [x, y];
756
- if (this._humanizer) await this._humanizer.after("scroll");
770
+ if (h) await h.after("scroll");
757
771
  }
758
772
  async screenshot(opts) {
759
773
  const format = opts?.format ?? "base64";
@@ -1976,6 +1990,380 @@ var Client = class _Client {
1976
1990
  async function connect(apiKey, opts) {
1977
1991
  return Client.create(apiKey, opts);
1978
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
+ };
1979
2367
  export {
1980
2368
  AuthError,
1981
2369
  Browser,
@@ -1988,18 +2376,28 @@ export {
1988
2376
  ChatSendFailed,
1989
2377
  Client,
1990
2378
  ConnectionLost,
2379
+ ContractClient,
2380
+ ContractError,
1991
2381
  HumanProfile,
1992
2382
  Humanizer,
1993
2383
  InsufficientFunds,
1994
2384
  NotOwner,
1995
2385
  ProviderDisconnected,
1996
2386
  ProviderOffline,
2387
+ ROLE_QA,
2388
+ ROLE_REVIEWER,
1997
2389
  RateLimitExceeded,
1998
2390
  SessionEnded,
1999
2391
  SessionExpired,
2000
2392
  SessionNotFound,
2393
+ TimelogClient,
2001
2394
  TimeoutError,
2002
2395
  TransportError,
2003
- connect
2396
+ cleanArgs,
2397
+ connect,
2398
+ contractIdsFromEnv,
2399
+ deriveLabel,
2400
+ parseBenefitable,
2401
+ parseParticipant
2004
2402
  };
2005
2403
  //# sourceMappingURL=index.js.map