@cursor/sdk 1.0.22 → 1.0.23
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/cjs/18.js +1 -1
- package/dist/cjs/642.js +1 -1
- package/dist/cjs/973.js +1 -0
- package/dist/cjs/agent/run-event-notifier-api.d.ts.map +1 -1
- package/dist/cjs/agent.d.ts +11 -0
- package/dist/cjs/agent.d.ts.map +1 -1
- package/dist/cjs/cloud-agent.d.ts.map +1 -1
- package/dist/cjs/cloud-api-client.d.ts +4 -1
- package/dist/cjs/cloud-api-client.d.ts.map +1 -1
- package/dist/cjs/errors.d.ts +2 -0
- package/dist/cjs/errors.d.ts.map +1 -1
- package/dist/cjs/executor-common.d.ts.map +1 -1
- package/dist/cjs/executor-types.d.ts +2 -0
- package/dist/cjs/executor-types.d.ts.map +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/local-executor.d.ts.map +1 -1
- package/dist/cjs/platform.d.ts.map +1 -1
- package/dist/cjs/public-api.d.ts +2 -2
- package/dist/cjs/public-api.d.ts.map +1 -1
- package/dist/cjs/run-event-notifier-api.d.ts.map +1 -1
- package/dist/cjs/run.d.ts +8 -0
- package/dist/cjs/run.d.ts.map +1 -1
- package/dist/cjs/sqlite.js +1 -1
- package/dist/cjs/store/atomic-write.d.ts +10 -0
- package/dist/cjs/store/atomic-write.d.ts.map +1 -0
- package/dist/cjs/store/jsonl-local-agent-store.d.ts.map +1 -1
- package/dist/esm/18.js +1 -1
- package/dist/esm/357.js +1 -1
- package/dist/esm/642.js +1 -1
- package/dist/esm/agent/run-event-notifier-api.d.ts.map +1 -1
- package/dist/esm/agent.d.ts +11 -0
- package/dist/esm/agent.d.ts.map +1 -1
- package/dist/esm/cloud-agent.d.ts.map +1 -1
- package/dist/esm/cloud-api-client.d.ts +4 -1
- package/dist/esm/cloud-api-client.d.ts.map +1 -1
- package/dist/esm/errors.d.ts +2 -0
- package/dist/esm/errors.d.ts.map +1 -1
- package/dist/esm/executor-common.d.ts.map +1 -1
- package/dist/esm/executor-types.d.ts +2 -0
- package/dist/esm/executor-types.d.ts.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/local-executor.d.ts.map +1 -1
- package/dist/esm/platform.d.ts.map +1 -1
- package/dist/esm/public-api.d.ts +2 -2
- package/dist/esm/public-api.d.ts.map +1 -1
- package/dist/esm/run-event-notifier-api.d.ts.map +1 -1
- package/dist/esm/run.d.ts +8 -0
- package/dist/esm/run.d.ts.map +1 -1
- package/dist/esm/sqlite.js +1 -1
- package/dist/esm/store/atomic-write.d.ts +10 -0
- package/dist/esm/store/atomic-write.d.ts.map +1 -0
- package/dist/esm/store/jsonl-local-agent-store.d.ts.map +1 -1
- package/package.json +6 -6
- package/dist/cjs/174.js +0 -1
package/dist/cjs/18.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=18,exports.ids=[18],exports.modules={"../cursor-sdk-local-runtime/dist/run-store/sqlite-blob-store.js"(e,t,s){s.d(t,{SQLiteBlobStoreWithMetadata:()=>l});var i=s("node:fs"),r=s("node:path"),n=s("../agent-kv/dist/index.js"),o=s("../utils/dist/index.js"),a=s("../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js");const d=new n.aY;class l extends o.jG{dbPath;driverPromise;driver;metadata;listeners={agentId:new Set,latestRootBlobId:new Set,name:new Set,createdAt:new Set,mode:new Set,isRunEverything:new Set,approvalMode:new Set,lastUsedModel:new Set,lastDebugServerPort:new Set,currentPlanUri:new Set};persistScheduled=!1;isDisposing=!1;disposePromise;static async initAndLoad(e){const t=new l(e);return await t.getDriver(),t}constructor(e){super(),this.dbPath=e;const t=(0,r.basename)((0,r.dirname)(this.dbPath));this.metadata=(0,n.sh)(t)}async getDriver(){if(this.driverPromise)return this.driverPromise;const e=(async()=>{const e=(0,r.dirname)(this.dbPath);(0,i.existsSync)(e)||(0,i.mkdirSync)(e,{recursive:!0});const t=await(0,a.d)(this.dbPath);try{this.initializeDriver(t)}catch(e){throw t.close(),e}return this.driver=t,t})().catch((t=>{throw this.driverPromise===e&&(this.driverPromise=void 0),t}));return this.driverPromise=e,e}initializeDriver(e){e.exec("PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 5000;\n PRAGMA user_version = 1;\n CREATE TABLE IF NOT EXISTS blobs (id TEXT PRIMARY KEY, data BLOB);\n CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);");const t=e.get("SELECT value FROM meta WHERE key = ?",["0"]);if(null==t?void 0:t.value){const e=(0,n.aD)(t.value);return void(this.metadata=d.deserialize(e))}const s=d.serialize(this.metadata);e.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",(0,n.nj)(s)])}async getBlob(e,t){if(this.isDisposing)return;const s=(0,n.nj)(t),i=(await this.getDriver()).get("SELECT data FROM blobs WHERE id = ?",[s]);return null==(null==i?void 0:i.data)?void 0:new Uint8Array(i.data)}async listBlobIds(){return this.isDisposing?[]:(await this.getDriver()).all("SELECT id FROM blobs ORDER BY id ASC").map((e=>e.id))}async deleteBlob(e){this.isDisposing||(await this.getDriver()).run("DELETE FROM blobs WHERE id = ?",[e])}async setBlob(e,t,s){if(this.isDisposing)return;const i=(0,n.nj)(t),r=Buffer.from(s);(await this.getDriver()).run("INSERT OR REPLACE INTO blobs (id, data) VALUES (?, ?)",[i,r])}async setBlobLocallyOnly(e,t,s){return Promise.resolve()}async flush(e){return Promise.resolve()}get(e){return this.metadata[e]}valuesEqual(e,t,s){if("latestRootBlobId"===e){const e=t,i=s;if(e===i)return!0;if(!e||!i)return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t++)if(e[t]!==i[t])return!1;return!0}return t===s}schedulePersist(){!this.isDisposing&&this.driver&&(this.persistScheduled||(this.persistScheduled=!0,queueMicrotask((()=>{this.persistScheduled=!1,!this.isDisposing&&this.driver&&this.persistMetadata()}))))}set(e,t){const s=this.metadata[e];if(this.valuesEqual(e,s,t))return;this.metadata=Object.assign(Object.assign({},this.metadata),{[e]:t}),this.driver&&this.schedulePersist();const i=this.listeners[e];i&&i.size>0&&queueMicrotask((()=>{i.forEach((e=>{e()}))}))}persistMetadata(){const e=this.driver;if(!e)return;const t=d.serialize(this.metadata);e.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",(0,n.nj)(t)])}subscribe(e,t){const s=this.listeners[e];return s?(s.add(t),()=>s.delete(t)):()=>{}}async dispose(){return this.disposePromise?this.disposePromise:this.driverPromise?(this.disposePromise=this.cleanup().then((()=>{this.driverPromise=void 0,this.driver=void 0})),this.disposePromise):void 0}async cleanup(){var e;if(!this.driverPromise)return;const t=await this.driverPromise.catch((()=>{}));if(!t)return this.driverPromise=void 0,void(this.driver=void 0);this.persistScheduled=!1,this.persistMetadata(),this.isDisposing=!0;const s=t.get("SELECT value FROM meta WHERE key = ?",["0"]);let o=0;if(null==s?void 0:s.value){const e=(0,n.aD)(s.value);o=d.deserialize(e).latestRootBlobId.length}const a=t.get("SELECT COUNT(*) AS count FROM blobs"),l=Number(null!==(e=null==a?void 0:a.count)&&void 0!==e?e:0);if(t.close(),0===o&&0===l){this.driverPromise=void 0,this.driver=void 0;const e=(0,r.dirname)(this.dbPath);try{(0,i.rmSync)(e,{recursive:!0,force:!0})}catch(e){}}}}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"(e,t,s){s.d(t,{d:()=>r});class i extends Error{constructor(e,t){super(e,t),this.name="NoSqliteDriverError"}}async function r(e){if(void 0!==globalThis.Bun)return(await s.e(914).then(s.bind(s,"../cursor-sdk-local-runtime/dist/run-store/sqlite/bun-sqlite-driver.js"))).openBunSqliteDriver(e);let t;try{t=await s.e(343).then(s.bind(s,"../cursor-sdk-local-runtime/dist/run-store/sqlite/node-sqlite-driver.js"))}catch(e){if(function(e){return"ERR_UNKNOWN_BUILTIN_MODULE"===("object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0)||(e instanceof Error?e.message.toLowerCase():String(e).toLowerCase()).includes("node:sqlite")}(e))throw new i("node:sqlite is not available in this runtime. The default local agent store requires Node >= 22.13 (or another runtime that implements node:sqlite). Configure a JsonlLocalAgentStore instead.",{cause:e});throw e}return t.openNodeSqliteDriver(e)}}};
|
|
1
|
+
"use strict";exports.id=18,exports.ids=[18],exports.modules={"../cursor-sdk-local-runtime/dist/run-store/sqlite-blob-store.js"(e,t,s){s.d(t,{SQLiteBlobStoreWithMetadata:()=>l});var i=s("node:fs"),r=s("node:path"),n=s("../agent-kv/dist/index.js"),o=s("../utils/dist/index.js"),a=s("../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js");const d=new n.aY;class l extends o.jG{dbPath;driverPromise;driver;metadata;listeners={agentId:new Set,latestRootBlobId:new Set,name:new Set,createdAt:new Set,mode:new Set,isRunEverything:new Set,approvalMode:new Set,lastUsedModel:new Set,lastDebugServerPort:new Set,currentPlanUri:new Set,subagentInfo:new Set};persistScheduled=!1;isDisposing=!1;disposePromise;static async initAndLoad(e){const t=new l(e);return await t.getDriver(),t}constructor(e){super(),this.dbPath=e;const t=(0,r.basename)((0,r.dirname)(this.dbPath));this.metadata=(0,n.sh)(t)}async getDriver(){if(this.driverPromise)return this.driverPromise;const e=(async()=>{const e=(0,r.dirname)(this.dbPath);(0,i.existsSync)(e)||(0,i.mkdirSync)(e,{recursive:!0});const t=await(0,a.d)(this.dbPath);try{this.initializeDriver(t)}catch(e){throw t.close(),e}return this.driver=t,t})().catch((t=>{throw this.driverPromise===e&&(this.driverPromise=void 0),t}));return this.driverPromise=e,e}initializeDriver(e){e.exec("PRAGMA journal_mode = WAL;\n PRAGMA synchronous = NORMAL;\n PRAGMA busy_timeout = 5000;\n PRAGMA user_version = 1;\n CREATE TABLE IF NOT EXISTS blobs (id TEXT PRIMARY KEY, data BLOB);\n CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);");const t=e.get("SELECT value FROM meta WHERE key = ?",["0"]);if(null==t?void 0:t.value){const e=(0,n.aD)(t.value);return void(this.metadata=d.deserialize(e))}const s=d.serialize(this.metadata);e.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",(0,n.nj)(s)])}async getBlob(e,t){if(this.isDisposing)return;const s=(0,n.nj)(t),i=(await this.getDriver()).get("SELECT data FROM blobs WHERE id = ?",[s]);return null==(null==i?void 0:i.data)?void 0:new Uint8Array(i.data)}async listBlobIds(){return this.isDisposing?[]:(await this.getDriver()).all("SELECT id FROM blobs ORDER BY id ASC").map((e=>e.id))}async deleteBlob(e){this.isDisposing||(await this.getDriver()).run("DELETE FROM blobs WHERE id = ?",[e])}async setBlob(e,t,s){if(this.isDisposing)return;const i=(0,n.nj)(t),r=Buffer.from(s);(await this.getDriver()).run("INSERT OR REPLACE INTO blobs (id, data) VALUES (?, ?)",[i,r])}async setBlobLocallyOnly(e,t,s){return Promise.resolve()}async flush(e){return Promise.resolve()}get(e){return this.metadata[e]}valuesEqual(e,t,s){if("latestRootBlobId"===e){const e=t,i=s;if(e===i)return!0;if(!e||!i)return!1;if(e.length!==i.length)return!1;for(let t=0;t<e.length;t++)if(e[t]!==i[t])return!1;return!0}return t===s}schedulePersist(){!this.isDisposing&&this.driver&&(this.persistScheduled||(this.persistScheduled=!0,queueMicrotask((()=>{this.persistScheduled=!1,!this.isDisposing&&this.driver&&this.persistMetadata()}))))}set(e,t){const s=this.metadata[e];if(this.valuesEqual(e,s,t))return;this.metadata=Object.assign(Object.assign({},this.metadata),{[e]:t}),this.driver&&this.schedulePersist();const i=this.listeners[e];i&&i.size>0&&queueMicrotask((()=>{i.forEach((e=>{e()}))}))}persistMetadata(){const e=this.driver;if(!e)return;const t=d.serialize(this.metadata);e.run("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",["0",(0,n.nj)(t)])}subscribe(e,t){const s=this.listeners[e];return s?(s.add(t),()=>s.delete(t)):()=>{}}async dispose(){return this.disposePromise?this.disposePromise:this.driverPromise?(this.disposePromise=this.cleanup().then((()=>{this.driverPromise=void 0,this.driver=void 0})),this.disposePromise):void 0}async cleanup(){var e;if(!this.driverPromise)return;const t=await this.driverPromise.catch((()=>{}));if(!t)return this.driverPromise=void 0,void(this.driver=void 0);this.persistScheduled=!1,this.persistMetadata(),this.isDisposing=!0;const s=t.get("SELECT value FROM meta WHERE key = ?",["0"]);let o=0;if(null==s?void 0:s.value){const e=(0,n.aD)(s.value);o=d.deserialize(e).latestRootBlobId.length}const a=t.get("SELECT COUNT(*) AS count FROM blobs"),l=Number(null!==(e=null==a?void 0:a.count)&&void 0!==e?e:0);if(t.close(),0===o&&0===l){this.driverPromise=void 0,this.driver=void 0;const e=(0,r.dirname)(this.dbPath);try{(0,i.rmSync)(e,{recursive:!0,force:!0})}catch(e){}}}}},"../cursor-sdk-local-runtime/dist/run-store/sqlite/open-sqlite-driver.js"(e,t,s){s.d(t,{d:()=>r});class i extends Error{constructor(e,t){super(e,t),this.name="NoSqliteDriverError"}}async function r(e){if(void 0!==globalThis.Bun)return(await s.e(914).then(s.bind(s,"../cursor-sdk-local-runtime/dist/run-store/sqlite/bun-sqlite-driver.js"))).openBunSqliteDriver(e);let t;try{t=await s.e(343).then(s.bind(s,"../cursor-sdk-local-runtime/dist/run-store/sqlite/node-sqlite-driver.js"))}catch(e){if(function(e){return"ERR_UNKNOWN_BUILTIN_MODULE"===("object"==typeof e&&null!==e&&"code"in e&&"string"==typeof e.code?e.code:void 0)||(e instanceof Error?e.message.toLowerCase():String(e).toLowerCase()).includes("node:sqlite")}(e))throw new i("node:sqlite is not available in this runtime. The default local agent store requires Node >= 22.13 (or another runtime that implements node:sqlite). Configure a JsonlLocalAgentStore instead.",{cause:e});throw e}return t.openNodeSqliteDriver(e)}}};
|
package/dist/cjs/642.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.id=642,exports.ids=[642],exports.modules={"./src/agent/cloud-agent.ts"(t,e,i){i.r(e),i.d(e,{archiveCloudAgent:()=>P,cancelCloudRun:()=>D,createCloudAgent:()=>j,deleteCloudAgent:()=>q,getCloudAgent:()=>K,getCloudMe:()=>T,getCloudRun:()=>x,listCloudAgents:()=>N,listCloudModels:()=>$,listCloudRepositories:()=>L,listCloudRuns:()=>k,resumeCloudAgent:()=>M,unarchiveCloudAgent:()=>U,validateCloudModelAvailability:()=>A});var n=i("../cursor-sdk-local-runtime/dist/run-store/index.js"),s=i("./src/agent/analytics.ts"),o=i("./src/agent/cloud-api-client.ts"),r=i("./src/agent/errors.ts");function a(t){if(void 0===t)return;const e=[];for(const[i,n]of Object.entries(t))if("command"in n){if(void 0!==n.cwd)throw new r.j1(`Cloud MCP server "${i}" cannot include cwd.`);e.push(Object.assign({name:i},n))}else e.push(Object.assign({name:i},n));return e.length>0?e:void 0}var d=i("./src/agent/run-interaction-accumulator.ts"),u=i("./src/agent/subagent-conversion.ts"),l=i("./src/agent/tool-call-utils.ts"),c=i("./src/agent/types/delta-types.ts"),h=i("./src/agent/usage-types.ts"),v=function(t,e,i,n){return new(i||(i=Promise))((function(s,o){function r(t){try{d(n.next(t))}catch(t){o(t)}}function a(t){try{d(n.throw(t))}catch(t){o(t)}}function d(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,a)}d((n=n.apply(t,e||[])).next())}))},f=function(t){return this instanceof f?(this.v=t,this):new f(t)};function g(t){if(""===t)throw new r.j1("API key is required for cloud operations. Caller passed an empty apiKey explicitly; refusing to fall back to CURSOR_API_KEY.",{isRetryable:!1,code:"unauthenticated"});const e=null!=t?t:process.env.CURSOR_API_KEY;if(!e)throw new r.j1("API key is required for cloud operations. Set CURSOR_API_KEY or pass apiKey.",{isRetryable:!1,code:"unauthenticated"});return e}const m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function p(t){if(!t.startsWith("bc-")||!m.test(t.slice(3)))throw new r.j1("Agent ID must be in the format 'bc-<uuid>'",{isRetryable:!1})}function y(t){if(!t.startsWith("run-")||!m.test(t.slice(4)))throw new r.j1("Run ID must be in the format 'run-<uuid>'",{isRetryable:!1})}function w(t){switch(t){case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"CANCELLED":return"cancelled";default:return"error"}}function b(t){return"running"===t||"completed"===t||"error"===t}const _=new Set(["assistant","thinking","tool_call"]);class I{constructor(){this.queue=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const e=this.waiters.shift();if(!e)return this.queue.length>=8192?(this.overflow=new r.LF("Cloud agent message buffer overflow; consumer is too slow",{code:"stream_buffer_overflow",errorName:"CursorSdkError"}),void(this.closed=!0)):void this.queue.push(t);e({value:t,done:!1})}close(){var t;if(!this.closed)for(this.closed=!0;this.waiters.length>0;)null===(t=this.waiters.shift())||void 0===t||t({value:void 0,done:!0})}stream(){return function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=i.apply(t,e||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",(function(t){return function(e){return Promise.resolve(e).then(t,u)}})),n[Symbol.asyncIterator]=function(){return this},n;function r(t,e){s[t]&&(n[t]=function(e){return new Promise((function(i,n){o.push([t,e,i,n])>1||a(t,e)}))},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=s[t](e)).value instanceof f?Promise.resolve(i.value.v).then(d,u):l(o[0][2],i)}catch(t){l(o[0][3],t)}var i}function d(t){a("next",t)}function u(t){a("throw",t)}function l(t,e){t(e),o.shift(),o.length&&a(o[0][0],o[0][1])}}(this,arguments,(function*(){for(;;){const t=this.queue.shift();if(t){yield yield f(t);continue}if(this.overflow)throw this.overflow;if(this.closed)return yield f(void 0);const e=yield f(new Promise((t=>{this.waiters.push(t)})));if(e.done)return yield f(void 0);yield yield f(e.value)}}))}}const S=new Set(["unauthorized","forbidden","not_found"]);function R(t,e){return v(this,void 0,void 0,(function*(){t<=0||(null==e?void 0:e.aborted)||(yield new Promise((i=>{const n=setTimeout((()=>{null==e||e.removeEventListener("abort",s),i()}),t),s=()=>{clearTimeout(n),i()};null==e||e.addEventListener("abort",s,{once:!0})})))}))}class C{constructor(t,e,i,n){this.client=t,this.buffer=new I,this.listeners=new Set,this.streamStarted=!1,this.emittedLegacyFrameIds=new Set,this.appliedInteractionUpdates=new Set,this.id=e.id,this.agentId=e.agentId,this.requestId=e.requestId,this._status=w(e.status),this.createdAt=Date.parse(e.createdAt);const s=(0,o.O)(e);this._result=s.result,this._durationMs=s.durationMs,this._git=s.git,this._model=n,this.sendOptions=i}get status(){return this._status}get result(){return this._result}get usage(){return this._usage}get durationMs(){return this._durationMs}get git(){return this._git}get model(){return this._model}supports(t){return"stream"===t||"wait"===t||"cancel"===t||"conversation"===t}unsupportedReason(t){if(!this.supports(t))return`Unknown run operation "${t}"`}stream(){try{return this.ensureStreamStarted(),this.buffer.stream()}catch(t){throw(0,r.Nt)(t,{operation:"run.stream"})}}conversation(){return v(this,void 0,void 0,(function*(){var t,e;try{this.ensureStreamStarted();try{yield this.streamPromise}catch(t){}return null!==(e=null===(t=this.accumulator)||void 0===t?void 0:t.conversation())&&void 0!==e?e:[]}catch(t){throw(0,r.Nt)(t,{operation:"run.conversation"})}}))}wait(){return v(this,void 0,void 0,(function*(){try{if("running"!==this._status)return this.buildResult();this.ensureStreamStarted();try{yield this.streamPromise}catch(t){"running"===this._status&&this.setStatus("error")}return this.buildResult()}catch(t){throw(0,r.Nt)(t,{operation:"run.wait"})}}))}cancel(){return v(this,void 0,void 0,(function*(){var t;try{if("cancelled"===this._status)return;yield this.client.cancelRun({agentId:this.agentId,runId:this.id}),null===(t=this.abortController)||void 0===t||t.abort(),this.setStatus("cancelled")}catch(t){throw(0,r.Nt)(t,{operation:"run.cancel"})}}))}onDidChangeStatus(t){return this.listeners.add(t),()=>this.listeners.delete(t)}abortClientStream(){var t;null===(t=this.abortController)||void 0===t||t.abort()}disposeClientStream(){return v(this,void 0,void 0,(function*(){this.abortClientStream(),void 0!==this.streamPromise&&(yield function(t){return v(this,void 0,void 0,(function*(){let e;try{yield Promise.race([t.catch((()=>{})),new Promise((t=>{var i;e=setTimeout(t,2e3),null===(i=e.unref)||void 0===i||i.call(e)}))])}finally{void 0!==e&&clearTimeout(e)}}))}(this.streamPromise))}))}ensureStreamStarted(){var t,e;if(this.streamStarted)return;this.streamStarted=!0,this.abortController=new AbortController;const i=new d.e4({onDelta:null===(t=this.sendOptions)||void 0===t?void 0:t.onDelta,onStep:null===(e=this.sendOptions)||void 0===e?void 0:e.onStep});this.accumulator=i,this.streamPromise=this.runStreamLoop(i,this.abortController.signal),this.streamPromise.catch((()=>{}))}runStreamLoop(t,e){return v(this,void 0,void 0,(function*(){let i=0;const n=Date.now()+72e5;try{do{const o=yield this.runOneStreamAttempt(t,e);if(e.aborted)break;if("received-result"===o)break;if(yield this.refetchAndSync(),e.aborted||"running"!==this._status)break;if(Date.now()>=n)break;if(i>=6){yield this.pollRunUntilTerminal(e,n);break}const r=Math.min((s=i,Math.min(3e4,1e3*Math.pow(2,s))),Math.max(0,n-Date.now()));i++,yield R(r,e)}while("running"===this._status&&!e.aborted);"running"===this._status&&Date.now()>=n&&this.setStatus("error"),yield t.flushPendingStep()}finally{this.buffer.close()}var s}))}applyInteractionUpdate(t,e){return v(this,void 0,void 0,(function*(){var i;if(yield t.apply(e),this._usage=null!==(i=t.usage())&&void 0!==i?i:this._usage,"turn-ended"!==e.type)return;const n=(0,h.q)(e.usage);n&&this.buffer.push({type:"usage",agent_id:this.agentId,run_id:this.id,usage:n})}))}runOneStreamAttempt(t,e){return v(this,void 0,void 0,(function*(){const i=this.lastEventId;let n=!1;try{const i=yield this.client.streamRun(Object.assign({agentId:this.agentId,runId:this.id,signal:e},void 0!==this.lastEventId?{lastEventId:this.lastEventId}:{}));yield function(t,e,i,n,s){return v(this,void 0,void 0,(function*(){var a,d,u,h,v,f,g,m,p;const y=t.body.getReader(),I=new TextDecoder;let R="";try{for(;;){if(null==s?void 0:s.aborted)return;const{value:t,done:C}=yield y.read();if(C)break;R+=I.decode(t,{stream:!0});let O=R.indexOf("\n\n");for(;-1!==O;){const t=R.slice(0,O);R=R.slice(O+2),O=R.indexOf("\n\n");const s=t.split("\n");let I,C;const j=[];for(const t of s)t.startsWith("id: ")?C=t.slice(4).trim():t.startsWith("event: ")?I=t.slice(7).trim():t.startsWith("data: ")&&j.push(t.slice(6));if(void 0!==C&&C.length>0&&(void 0===I||!_.has(I))&&(null===(a=n.onEventId)||void 0===a||a.call(n,C)),"done"===I)return void(yield y.cancel());if(0===j.length)continue;const A=j.join("\n");let M;try{M=JSON.parse(A)}catch(t){throw new r.Dr(`Malformed SSE event: ${A}`,{isRetryable:!0})}if(I&&(!_.has(I)||void 0===C||!1!==(null===(d=n.shouldEmitLegacyFrame)||void 0===d?void 0:d.call(n,C))))switch(I){case"assistant":{const t=(0,l.u)(M)?M:{};n.onMessage({type:"assistant",agent_id:e,run_id:i,message:{role:"assistant",content:[{type:"text",text:null!==(u=t.text)&&void 0!==u?u:""}]}});break}case"thinking":{const t=(0,l.u)(M)?M:{};n.onMessage({type:"thinking",agent_id:e,run_id:i,text:null!==(h=t.text)&&void 0!==h?h:""});break}case"tool_call":{const t=(0,l.u)(M)?M:{},s=(0,l.u)(t.data)?t.data:t,o=b(s.status)?s.status:"running",r="string"==typeof s.callId?s.callId:"",a="string"==typeof s.name?s.name:"unknown";n.onMessage(Object.assign(Object.assign(Object.assign({type:"tool_call",agent_id:e,run_id:i,call_id:r,name:a,status:o},"args"in s?{args:s.args}:{}),"result"in s?{result:s.result}:{}),(0,l.D)(s.truncated)?{truncated:s.truncated}:{}));break}case"interaction_update":{if(void 0===n.onInteractionUpdate)break;if(!1===(null===(v=n.shouldApplyInteractionUpdate)||void 0===v?void 0:v.call(n,C,A)))break;const t=c.Zs.safeParse(M);if(!t.success)break;yield n.onInteractionUpdate(t.data);break}case"status":{const t=((0,l.u)(M)?M:{}).status;t&&(null===(f=n.onStatusChange)||void 0===f||f.call(n,w(t)),n.onMessage({type:"status",agent_id:e,run_id:i,status:t}));break}case"result":if((0,l.u)(M)){const t=M,e=Object.assign(Object.assign({},t),"string"==typeof t.text&&void 0===t.result?{result:t.text}:{});null===(g=n.onResult)||void 0===g||g.call(n,(0,o.O)(e))}return void(yield y.cancel());case"heartbeat":break;case"error":{const t=(0,l.u)(M)?M:{},e=null!==(m=t.code)&&void 0!==m?m:"UNKNOWN",i=null!==(p=t.message)&&void 0!==p?p:"Unknown error";if(S.has(e))throw new r.j1(`[${e}] ${i}`,{code:e,isRetryable:!1});throw new r.c$(`[${e}] ${i}`,{code:e,isRetryable:!1})}}}}}catch(t){if((null==s?void 0:s.aborted)||"object"==typeof t&&null!==t&&"name"in t&&"AbortError"===t.name)return;throw t}finally{try{yield y.cancel()}catch(t){}}}))}(i,this.agentId,this.id,{onMessage:t=>this.buffer.push(t),onResult:t=>{var e;this._result=t.result,this._durationMs=t.durationMs,this._git=t.git,this.setStatus(w(null!==(e=t.status)&&void 0!==e?e:"FINISHED")),n=!0},onStatusChange:t=>{"running"===t&&this.setStatus(t)},onInteractionUpdate:e=>this.applyInteractionUpdate(t,e),onEventId:t=>{this.lastEventId=t,this.emittedLegacyFrameIds.clear()},shouldEmitLegacyFrame:t=>!this.emittedLegacyFrameIds.has(t)&&(this.emittedLegacyFrameIds.add(t),!0),shouldApplyInteractionUpdate:(t,e)=>{var i;const n=void 0!==t&&t.length>0?t:`${null!==(i=this.lastEventId)&&void 0!==i?i:""}\0${e}`;return!this.appliedInteractionUpdates.has(n)&&(this.appliedInteractionUpdates.add(n),!0)}},e)}catch(t){if(function(t){return t instanceof Error&&t.message.startsWith("[invalid_last_event_id]")}(t))this.lastEventId===i&&(this.lastEventId=void 0);else if(function(t){if(t instanceof r.v3||t instanceof r.j1)return!0;if(t instanceof Error){const e=/^\[([a-z_]+)\]/.exec(t.message);if(null!==e&&S.has(e[1]))return!0}return!1}(t))throw"running"===this._status&&this.setStatus("error"),t}return n?"received-result":"stream-dropped"}))}pollRunUntilTerminal(t,e){return v(this,void 0,void 0,(function*(){for(;"running"===this._status&&!t.aborted;){const i=e-Date.now();if(i<=0)return void this.setStatus("error");if(yield R(Math.min(15e3,i),t),t.aborted)return;yield this.refetchAndSync()}}))}setStatus(t){if(this._status!==t){this._status=t;for(const e of this.listeners)e(t)}}refetchAndSync(){return v(this,void 0,void 0,(function*(){let t;try{t=yield this.client.getRun({agentId:this.agentId,runId:this.id})}catch(t){if(t instanceof r.v3||t instanceof r.j1)throw"running"===this._status&&this.setStatus("error"),t;return}const e=(0,o.O)(t);void 0!==e.result&&(this._result=e.result),void 0!==e.durationMs&&(this._durationMs=e.durationMs),void 0!==e.git&&(this._git=e.git),"running"===this._status&&this.setStatus(w(t.status))}))}buildResult(){const t="running"===this._status?"error":this._status;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({id:this.id},void 0!==this.requestId?{requestId:this.requestId}:{}),{status:t}),void 0!==this._result?{result:this._result}:{}),void 0!==this._model?{model:this._model}:{}),void 0!==this._durationMs?{durationMs:this._durationMs}:{}),void 0!==this._git?{git:this._git}:{}),void 0!==this._usage?{usage:this._usage}:{})}}class O{constructor(t,e,i,n){this.client=e,this.options=i,this.activeRuns=new Set,this.agentId=t,this.serverCreated=n,this._model=i.model}get model(){return this._model}send(t,e){return v(this,void 0,void 0,(function*(){var i,n,o,d,l,c,h,v,f,g,m,p,y,w,b,_,I,S,R,O;try{if(void 0!==(null===(i=null==e?void 0:e.local)||void 0===i?void 0:i.customTools))throw new r.j1("Custom local tools are only supported for local SDK agents. Create the agent with getLocalPlatformOptions() or omit local.customTools.",{isRetryable:!1});const j=function(t){var e;return"string"==typeof t?{text:t}:{text:t.text,images:null===(e=t.images)||void 0===e?void 0:e.map((t=>"url"in t?{url:t.url,dimension:t.dimension}:{data:t.data,mimeType:t.mimeType,dimension:t.dimension}))}}(t),A=!this.serverCreated,M=null!==(n=null==e?void 0:e.mcpServers)&&void 0!==n?n:this.options.mcpServers,N=null!==(o=null==e?void 0:e.model)&&void 0!==o?o:this._model,k=void 0!==(null==e?void 0:e.mode)?e.mode:A?this.options.mode:void 0,x=void 0!==(null==e?void 0:e.onStep)||void 0!==(null==e?void 0:e.onDelta)?Object.assign(Object.assign({},void 0!==e.onStep?{onStep:e.onStep}:{}),void 0!==e.onDelta?{onDelta:e.onDelta}:{}):void 0;let D;if(A){const t=(0,u.SB)(this.options.agents),i=void 0!==(null===(d=this.options.cloud)||void 0===d?void 0:d.envVars),n=yield this.client.createAgent(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i?{}:{agentId:this.agentId}),{prompt:j}),void 0!==N?{model:N}:{}),void 0!==this.options.name?{name:this.options.name}:{}),{mcpServers:a(M)}),void 0!==t?{customSubagents:t}:{}),{env:null===(l=this.options.cloud)||void 0===l?void 0:l.env,envVars:null===(c=this.options.cloud)||void 0===c?void 0:c.envVars,repos:null===(h=this.options.cloud)||void 0===h?void 0:h.repos,workOnCurrentBranch:null===(v=this.options.cloud)||void 0===v?void 0:v.workOnCurrentBranch,autoCreatePR:null===(f=this.options.cloud)||void 0===f?void 0:f.autoCreatePR,skipReviewerRequest:null===(g=this.options.cloud)||void 0===g?void 0:g.skipReviewerRequest}),void 0!==k?{mode:k}:{}),{idempotencyKey:null!==(m=null==e?void 0:e.idempotencyKey)&&void 0!==m?m:this.options.idempotencyKey});if(i)this.agentId=n.agent.id;else if(n.agent.id!==this.agentId)throw new r.c$(`Server returned mismatched agent id "${n.agent.id}"; expected "${this.agentId}". This indicates a backend bug.`,{isRetryable:!1});this.serverCreated=!0,D=new C(this.client,n.run,x,N)}else{const t=yield this.client.createRun(this.agentId,Object.assign(Object.assign({prompt:j,mcpServers:a(M)},void 0!==(null==e?void 0:e.model)?{model:e.model}:{}),void 0!==k?{mode:k}:{}),{idempotencyKey:null==e?void 0:e.idempotencyKey});D=new C(this.client,t.run,x,N)}void 0!==(null==e?void 0:e.model)&&(this._model=e.model);const E=null!==(w=null===(y=null===(p=this.options.cloud)||void 0===p?void 0:p.env)||void 0===y?void 0:y.type)&&void 0!==w?w:"cloud",K=null==N?void 0:N.params;(0,s.Zn)(this.options.apiKey,Object.assign(Object.assign({agent_id:this.agentId,run_id:D.id,request_id:D.requestId,runtime:E,model:null!==(b=null==N?void 0:N.id)&&void 0!==b?b:"default"},K&&K.length>0?{model_params:JSON.stringify(K)}:{}),{prompt_length:j.text.length,has_images:(null!==(I=null===(_=j.images)||void 0===_?void 0:_.length)&&void 0!==I?I:0)>0,is_resume:!A,mcp_server_count:Object.keys(null!=M?M:{}).length,cloud_repo_count:null===(R=null===(S=this.options.cloud)||void 0===S?void 0:S.repos)||void 0===R?void 0:R.length,cloud_auto_create_pr:null===(O=this.options.cloud)||void 0===O?void 0:O.autoCreatePR})),this.activeRuns.add(D);const P=this.options.apiKey,U=this.agentId,q=D.id;return D.wait().then((t=>{(0,s.G5)(P,{agent_id:U,run_id:q,request_id:D.requestId,runtime:E,end_reason:"finished"===t.status?"success":"cancelled"===t.status?"abort":"error"})})).finally((()=>{this.activeRuns.delete(D)})),D.ensureStreamStarted(),D}catch(t){throw(0,r.Nt)(t,{operation:"agent.send"})}}))}close(){for(const t of this.activeRuns)t.abortClientStream();(0,s.rd)()}reload(){return v(this,void 0,void 0,(function*(){}))}[Symbol.asyncDispose](){return v(this,void 0,void 0,(function*(){yield Promise.allSettled(Array.from(this.activeRuns,(t=>t.disposeClientStream()))),yield(0,s.rd)()}))}listArtifacts(){return v(this,void 0,void 0,(function*(){try{return this.serverCreated?(yield this.client.listArtifacts(this.agentId)).items.map((t=>({path:t.path,sizeBytes:t.sizeBytes,updatedAt:t.updatedAt}))):[]}catch(t){throw(0,r.Nt)(t,{operation:"agent.listArtifacts"})}}))}downloadArtifact(t){return v(this,void 0,void 0,(function*(){try{if(!this.serverCreated)throw new r.j1("Agent has not been created yet; call send() first.",{isRetryable:!1});const{url:e}=yield this.client.getArtifactDownloadUrl({agentId:this.agentId,path:t});let i;try{i=yield fetch(e)}catch(t){throw new r.Dr("Failed to download artifact",{cause:t,isRetryable:!0})}if(!i.ok)throw new r.Dr(`Failed to download artifact: ${i.status}`,{status:i.status,isRetryable:i.status>=500});return Buffer.from(yield i.arrayBuffer())}catch(t){throw(0,r.Nt)(t,{operation:"agent.downloadArtifact"})}}))}}function j(t){var e,i;const s=g(t.apiKey);if(void 0!==t.agentId&&void 0!==(null===(e=t.cloud)||void 0===e?void 0:e.envVars))throw new r.j1("cloud.envVars cannot be combined with agentId; omit agentId so the server can mint an agent id.",{isRetryable:!1});const a=new o.N(s),d=null!==(i=t.agentId)&&void 0!==i?i:(0,n.M2)();return new O(d,a,t,!1)}function A(t){return v(this,arguments,void 0,(function*({apiKey:t,model:e}){const i="string"==typeof e?e.trim():e.id.trim();if(0===i.length)throw new r.j1("Model id is required. Pass a non-empty `model.id` or `model: '<model-id>'`.",{isRetryable:!1,code:"invalid_model"});let n,s;try{n=g(t)}catch(t){if(t instanceof r.j1)return;throw t}try{s=(yield new o.N(n).listModels()).items}catch(t){if(t instanceof r.Dr||t instanceof r.v3||t instanceof r.OE)return;throw t}const a=s.some((t=>{var e;return t.id===i||!0===(null===(e=t.aliases)||void 0===e?void 0:e.includes(i))}));if(!a)throw new r.j1(`Model '${i}' is not available or invalid. Call Cursor.models.list() to see valid model ids.`,{isRetryable:!1,code:"invalid_model"})}))}function M(t,e){const i=g(e.apiKey),n=new o.N(i);return new O(t,n,Object.assign({},e),!0)}function N(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new o.N(e),n=yield i.listAgents({limit:t.limit,cursor:t.cursor,prUrl:t.prUrl,includeArchived:t.includeArchived});return{items:n.items.map(E),nextCursor:n.nextCursor}}))}function k(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new o.N(i),s=yield n.listRuns(t,{limit:e.limit,cursor:e.cursor});return{items:s.items.map((t=>new C(n,t))),nextCursor:s.nextCursor}}))}function x(t,e){return v(this,void 0,void 0,(function*(){y(t),p(e.agentId);const i=g(e.apiKey),n=new o.N(i),s=yield n.getRun({agentId:e.agentId,runId:t});return new C(n,s)}))}function D(t,e){return v(this,void 0,void 0,(function*(){y(t),p(e.agentId);const i=g(e.apiKey),n=new o.N(i);yield n.cancelRun({agentId:e.agentId,runId:t})}))}function E(t){var e,i,n;return{agentId:t.id,name:null!==(e=t.name)&&void 0!==e?e:"",summary:null!==(i=t.name)&&void 0!==i?i:"",lastModified:new Date(t.updatedAt).getTime(),createdAt:new Date(t.createdAt).getTime(),archived:"ARCHIVED"===t.status,runtime:"cloud",env:t.env,repos:null===(n=t.repos)||void 0===n?void 0:n.map((t=>t.url))}}function K(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new o.N(i);return E(yield n.getAgent(t))}))}function P(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new o.N(i);yield n.archiveAgent(t)}))}function U(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new o.N(i);yield n.unarchiveAgent(t)}))}function q(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new o.N(i);yield n.deleteAgent(t)}))}function T(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey);return new o.N(e).getMe()}))}function $(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new o.N(e);return(yield i.listModels()).items}))}function L(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new o.N(e);return(yield i.listRepositories()).items}))}}};
|
|
1
|
+
"use strict";exports.id=642,exports.ids=[642],exports.modules={"./src/agent/cloud-agent.ts"(t,e,i){i.r(e),i.d(e,{archiveCloudAgent:()=>U,cancelCloudRun:()=>x,createCloudAgent:()=>A,deleteCloudAgent:()=>T,getCloudAgent:()=>P,getCloudMe:()=>$,getCloudRun:()=>N,listCloudAgents:()=>E,listCloudModels:()=>L,listCloudRepositories:()=>F,listCloudRuns:()=>M,resumeCloudAgent:()=>k,unarchiveCloudAgent:()=>q,validateCloudModelAvailability:()=>D});var n=i("../cursor-sdk-local-runtime/dist/run-store/index.js"),s=i("./src/agent/analytics.ts"),r=i("./src/agent/cloud-api-client.ts"),o=i("./src/agent/errors.ts");function a(t){if(void 0===t)return;const e=[];for(const[i,n]of Object.entries(t))if("command"in n){if(void 0!==n.cwd)throw new o.j1(`Cloud MCP server "${i}" cannot include cwd.`);e.push(Object.assign({name:i},n))}else e.push(Object.assign({name:i},n));return e.length>0?e:void 0}var d=i("./src/agent/run-interaction-accumulator.ts"),u=i("./src/agent/subagent-conversion.ts"),l=i("./src/agent/tool-call-utils.ts"),c=i("./src/agent/types/delta-types.ts"),h=i("./src/agent/usage-types.ts"),v=function(t,e,i,n){return new(i||(i=Promise))((function(s,r){function o(t){try{d(n.next(t))}catch(t){r(t)}}function a(t){try{d(n.throw(t))}catch(t){r(t)}}function d(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(o,a)}d((n=n.apply(t,e||[])).next())}))},f=function(t){return this instanceof f?(this.v=t,this):new f(t)};function g(t){if(""===t)throw new o.j1("API key is required for cloud operations. Caller passed an empty apiKey explicitly; refusing to fall back to CURSOR_API_KEY.",{isRetryable:!1,code:"unauthenticated"});const e=null!=t?t:process.env.CURSOR_API_KEY;if(!e)throw new o.j1("API key is required for cloud operations. Set CURSOR_API_KEY or pass apiKey.",{isRetryable:!1,code:"unauthenticated"});return e}const m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function p(t){if(!t.startsWith("bc-")||!m.test(t.slice(3)))throw new o.j1("Agent ID must be in the format 'bc-<uuid>'",{isRetryable:!1})}function y(t){if(!t.startsWith("run-")||!m.test(t.slice(4)))throw new o.j1("Run ID must be in the format 'run-<uuid>'",{isRetryable:!1})}function w(t){switch(t){case"CREATING":case"RUNNING":return"running";case"FINISHED":return"finished";case"CANCELLED":return"cancelled";default:return"error"}}function b(t){return"running"===t||"completed"===t||"error"===t}const _=new Set(["assistant","thinking","tool_call"]);class I{constructor(){this.queue=[],this.waiters=[],this.closed=!1}push(t){if(this.closed)return;const e=this.waiters.shift();if(!e)return this.queue.length>=8192?(this.overflow=new o.LF("Cloud agent message buffer overflow; consumer is too slow",{code:"stream_buffer_overflow",errorName:"CursorSdkError"}),void(this.closed=!0)):void this.queue.push(t);e({value:t,done:!1})}close(){var t;if(!this.closed)for(this.closed=!0;this.waiters.length>0;)null===(t=this.waiters.shift())||void 0===t||t({value:void 0,done:!0})}stream(){return function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,s=i.apply(t,e||[]),r=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",(function(t){return function(e){return Promise.resolve(e).then(t,u)}})),n[Symbol.asyncIterator]=function(){return this},n;function o(t,e){s[t]&&(n[t]=function(e){return new Promise((function(i,n){r.push([t,e,i,n])>1||a(t,e)}))},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=s[t](e)).value instanceof f?Promise.resolve(i.value.v).then(d,u):l(r[0][2],i)}catch(t){l(r[0][3],t)}var i}function d(t){a("next",t)}function u(t){a("throw",t)}function l(t,e){t(e),r.shift(),r.length&&a(r[0][0],r[0][1])}}(this,arguments,(function*(){for(;;){const t=this.queue.shift();if(t){yield yield f(t);continue}if(this.overflow)throw this.overflow;if(this.closed)return yield f(void 0);const e=yield f(new Promise((t=>{this.waiters.push(t)})));if(e.done)return yield f(void 0);yield yield f(e.value)}}))}}const S=new Set(["unauthorized","forbidden","not_found"]);function O(t,e){return v(this,void 0,void 0,(function*(){t<=0||(null==e?void 0:e.aborted)||(yield new Promise((i=>{const n=setTimeout((()=>{null==e||e.removeEventListener("abort",s),i()}),t),s=()=>{clearTimeout(n),i()};null==e||e.addEventListener("abort",s,{once:!0})})))}))}class R{constructor(t,e,i,n){this.client=t,this.buffer=new I,this.listeners=new Set,this.streamStarted=!1,this.emittedLegacyFrameIds=new Set,this.appliedInteractionUpdates=new Set,this.id=e.id,this.agentId=e.agentId,this.requestId=e.requestId,this._status=w(e.status),this.createdAt=Date.parse(e.createdAt);const s=(0,r.O)(e);this._result=s.result,this._error="error"===this._status?s.error:void 0,this._durationMs=s.durationMs,this._git=s.git,this._model=n,this.sendOptions=i}get status(){return this._status}get result(){return this._result}get error(){return"error"===this._status?this._error:void 0}get usage(){return this._usage}get durationMs(){return this._durationMs}get git(){return this._git}get model(){return this._model}supports(t){return"stream"===t||"wait"===t||"cancel"===t||"conversation"===t}unsupportedReason(t){if(!this.supports(t))return`Unknown run operation "${t}"`}stream(){try{return this.ensureStreamStarted(),this.buffer.stream()}catch(t){throw(0,o.Nt)(t,{operation:"run.stream"})}}conversation(){return v(this,void 0,void 0,(function*(){var t,e;try{this.ensureStreamStarted();try{yield this.streamPromise}catch(t){}return null!==(e=null===(t=this.accumulator)||void 0===t?void 0:t.conversation())&&void 0!==e?e:[]}catch(t){throw(0,o.Nt)(t,{operation:"run.conversation"})}}))}wait(){return v(this,void 0,void 0,(function*(){try{if("running"!==this._status)return this.buildResult();this.ensureStreamStarted();try{yield this.streamPromise}catch(t){"running"===this._status&&(this._error=(0,o.D7)(t),this.setStatus("error"))}return this.buildResult()}catch(t){throw(0,o.Nt)(t,{operation:"run.wait"})}}))}cancel(){return v(this,void 0,void 0,(function*(){var t;try{if("cancelled"===this._status)return;yield this.client.cancelRun({agentId:this.agentId,runId:this.id}),null===(t=this.abortController)||void 0===t||t.abort(),this.setStatus("cancelled")}catch(t){throw(0,o.Nt)(t,{operation:"run.cancel"})}}))}onDidChangeStatus(t){return this.listeners.add(t),()=>this.listeners.delete(t)}abortClientStream(){var t;null===(t=this.abortController)||void 0===t||t.abort()}disposeClientStream(){return v(this,void 0,void 0,(function*(){this.abortClientStream(),void 0!==this.streamPromise&&(yield function(t){return v(this,void 0,void 0,(function*(){let e;try{yield Promise.race([t.catch((()=>{})),new Promise((t=>{var i;e=setTimeout(t,2e3),null===(i=e.unref)||void 0===i||i.call(e)}))])}finally{void 0!==e&&clearTimeout(e)}}))}(this.streamPromise))}))}ensureStreamStarted(){var t,e;if(this.streamStarted)return;this.streamStarted=!0,this.abortController=new AbortController;const i=new d.e4({onDelta:null===(t=this.sendOptions)||void 0===t?void 0:t.onDelta,onStep:null===(e=this.sendOptions)||void 0===e?void 0:e.onStep});this.accumulator=i,this.streamPromise=this.runStreamLoop(i,this.abortController.signal),this.streamPromise.catch((()=>{}))}runStreamLoop(t,e){return v(this,void 0,void 0,(function*(){let i=0;const n=Date.now()+72e5;try{do{const r=yield this.runOneStreamAttempt(t,e);if(e.aborted)break;if("received-result"===r)break;if(yield this.refetchAndSync(),e.aborted||"running"!==this._status)break;if(Date.now()>=n)break;if(i>=6){yield this.pollRunUntilTerminal(e,n);break}const o=Math.min((s=i,Math.min(3e4,1e3*Math.pow(2,s))),Math.max(0,n-Date.now()));i++,yield O(o,e)}while("running"===this._status&&!e.aborted);"running"===this._status&&Date.now()>=n&&this.setWaitDeadlineError(),yield t.flushPendingStep()}finally{this.buffer.close()}var s}))}applyInteractionUpdate(t,e){return v(this,void 0,void 0,(function*(){var i;if(yield t.apply(e),this._usage=null!==(i=t.usage())&&void 0!==i?i:this._usage,"turn-ended"!==e.type)return;const n=(0,h.q)(e.usage);n&&this.buffer.push({type:"usage",agent_id:this.agentId,run_id:this.id,usage:n})}))}runOneStreamAttempt(t,e){return v(this,void 0,void 0,(function*(){const i=this.lastEventId;let n=!1;try{const i=yield this.client.streamRun(Object.assign({agentId:this.agentId,runId:this.id,signal:e},void 0!==this.lastEventId?{lastEventId:this.lastEventId}:{}));yield function(t,e,i,n,s){return v(this,void 0,void 0,(function*(){var a,d,u,h,v,f,g,m,p;const y=t.body.getReader(),I=new TextDecoder;let O="";try{for(;;){if(null==s?void 0:s.aborted)return;const{value:t,done:R}=yield y.read();if(R)break;O+=I.decode(t,{stream:!0});let j=O.indexOf("\n\n");for(;-1!==j;){const t=O.slice(0,j);O=O.slice(j+2),j=O.indexOf("\n\n");const s=t.split("\n");let I,R;const C=[];for(const t of s)t.startsWith("id: ")?R=t.slice(4).trim():t.startsWith("event: ")?I=t.slice(7).trim():t.startsWith("data: ")&&C.push(t.slice(6));if(void 0!==R&&R.length>0&&(void 0===I||!_.has(I))&&(null===(a=n.onEventId)||void 0===a||a.call(n,R)),"done"===I)return void(yield y.cancel());if(0===C.length)continue;const A=C.join("\n");let D;try{D=JSON.parse(A)}catch(t){throw new o.Dr(`Malformed SSE event: ${A}`,{isRetryable:!0})}if(I&&(!_.has(I)||void 0===R||!1!==(null===(d=n.shouldEmitLegacyFrame)||void 0===d?void 0:d.call(n,R))))switch(I){case"assistant":{const t=(0,l.u)(D)?D:{};n.onMessage({type:"assistant",agent_id:e,run_id:i,message:{role:"assistant",content:[{type:"text",text:null!==(u=t.text)&&void 0!==u?u:""}]}});break}case"thinking":{const t=(0,l.u)(D)?D:{};n.onMessage({type:"thinking",agent_id:e,run_id:i,text:null!==(h=t.text)&&void 0!==h?h:""});break}case"tool_call":{const t=(0,l.u)(D)?D:{},s=(0,l.u)(t.data)?t.data:t,r=b(s.status)?s.status:"running",o="string"==typeof s.callId?s.callId:"",a="string"==typeof s.name?s.name:"unknown";n.onMessage(Object.assign(Object.assign(Object.assign({type:"tool_call",agent_id:e,run_id:i,call_id:o,name:a,status:r},"args"in s?{args:s.args}:{}),"result"in s?{result:s.result}:{}),(0,l.D)(s.truncated)?{truncated:s.truncated}:{}));break}case"interaction_update":{if(void 0===n.onInteractionUpdate)break;if(!1===(null===(v=n.shouldApplyInteractionUpdate)||void 0===v?void 0:v.call(n,R,A)))break;const t=c.Zs.safeParse(D);if(!t.success)break;yield n.onInteractionUpdate(t.data);break}case"status":{const t=((0,l.u)(D)?D:{}).status;t&&(null===(f=n.onStatusChange)||void 0===f||f.call(n,w(t)),n.onMessage({type:"status",agent_id:e,run_id:i,status:t}));break}case"result":if((0,l.u)(D)){const t=D,e=Object.assign(Object.assign({},t),"string"==typeof t.text&&void 0===t.result?{result:t.text}:{});null===(g=n.onResult)||void 0===g||g.call(n,(0,r.O)(e))}return void(yield y.cancel());case"heartbeat":break;case"error":{const t=(0,l.u)(D)?D:{},e=null!==(m=t.code)&&void 0!==m?m:"UNKNOWN",i=null!==(p=t.message)&&void 0!==p?p:"Unknown error";if(S.has(e))throw new o.j1(`[${e}] ${i}`,{code:e,isRetryable:!1});throw new o.c$(`[${e}] ${i}`,{code:e,isRetryable:!1})}}}}}catch(t){if((null==s?void 0:s.aborted)||"object"==typeof t&&null!==t&&"name"in t&&"AbortError"===t.name)return;throw t}finally{try{yield y.cancel()}catch(t){}}}))}(i,this.agentId,this.id,{onMessage:t=>this.buffer.push(t),onResult:t=>{var e,i;this._result=t.result;const s=w(null!==(e=t.status)&&void 0!==e?e:"FINISHED");this._error="error"===s?null!==(i=t.error)&&void 0!==i?i:this._error:void 0,this._durationMs=t.durationMs,this._git=t.git,this.setStatus(s),n=!0},onStatusChange:t=>{"running"===t&&this.setStatus(t)},onInteractionUpdate:e=>this.applyInteractionUpdate(t,e),onEventId:t=>{this.lastEventId=t,this.emittedLegacyFrameIds.clear()},shouldEmitLegacyFrame:t=>!this.emittedLegacyFrameIds.has(t)&&(this.emittedLegacyFrameIds.add(t),!0),shouldApplyInteractionUpdate:(t,e)=>{var i;const n=void 0!==t&&t.length>0?t:`${null!==(i=this.lastEventId)&&void 0!==i?i:""}\0${e}`;return!this.appliedInteractionUpdates.has(n)&&(this.appliedInteractionUpdates.add(n),!0)}},e)}catch(t){if(function(t){return t instanceof Error&&t.message.startsWith("[invalid_last_event_id]")}(t))this.lastEventId===i&&(this.lastEventId=void 0);else if(function(t){if(t instanceof o.v3||t instanceof o.j1)return!0;if(t instanceof Error){const e=/^\[([a-z_]+)\]/.exec(t.message);if(null!==e&&S.has(e[1]))return!0}return!1}(t))throw"running"===this._status&&(this._error=(0,o.D7)(t),this.setStatus("error")),t}return n?"received-result":"stream-dropped"}))}pollRunUntilTerminal(t,e){return v(this,void 0,void 0,(function*(){for(;"running"===this._status&&!t.aborted;){const i=e-Date.now();if(i<=0)return void this.setWaitDeadlineError();if(yield O(Math.min(15e3,i),t),t.aborted)return;yield this.refetchAndSync()}}))}setWaitDeadlineError(){this._error={message:"Timed out waiting for the cloud run to finish."},this.setStatus("error")}setStatus(t){if(this._status!==t){this._status=t;for(const e of this.listeners)e(t)}}refetchAndSync(){return v(this,void 0,void 0,(function*(){let t;try{t=yield this.client.getRun({agentId:this.agentId,runId:this.id})}catch(t){if(t instanceof o.v3||t instanceof o.j1)throw"running"===this._status&&(this._error=(0,o.D7)(t),this.setStatus("error")),t;return}const e=(0,r.O)(t);void 0!==e.result&&(this._result=e.result);const i=w(t.status);"error"===i&&void 0!==e.error?this._error=e.error:"error"!==i&&(this._error=void 0),void 0!==e.durationMs&&(this._durationMs=e.durationMs),void 0!==e.git&&(this._git=e.git),"running"===this._status&&this.setStatus(i)}))}buildResult(){const t="running"===this._status?"error":this._status;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({id:this.id},void 0!==this.requestId?{requestId:this.requestId}:{}),{status:t}),void 0!==this._result?{result:this._result}:{}),"error"===t&&void 0!==this._error?{error:this._error}:{}),void 0!==this._model?{model:this._model}:{}),void 0!==this._durationMs?{durationMs:this._durationMs}:{}),void 0!==this._git?{git:this._git}:{}),void 0!==this._usage?{usage:this._usage}:{})}}class j{constructor(t,e,i,n){this.client=e,this.options=i,this.activeRuns=new Set,this.agentId=t,this.serverCreated=n,this._model=i.model}get model(){return this._model}send(t,e){return v(this,void 0,void 0,(function*(){var i,n,r,d,l,c,h,v,f,g,m,p,y,w,b,_,I,S,O,j;try{if(void 0!==(null===(i=null==e?void 0:e.local)||void 0===i?void 0:i.customTools))throw new o.j1("Custom local tools are only supported for local SDK agents. Create the agent with getLocalPlatformOptions() or omit local.customTools.",{isRetryable:!1});const A=function(t){var e;return"string"==typeof t?{text:t}:{text:t.text,images:null===(e=t.images)||void 0===e?void 0:e.map((t=>"url"in t?{url:t.url,dimension:t.dimension}:{data:t.data,mimeType:t.mimeType,dimension:t.dimension}))}}(t),D=!this.serverCreated,k=null!==(n=null==e?void 0:e.mcpServers)&&void 0!==n?n:this.options.mcpServers,E=null!==(r=null==e?void 0:e.model)&&void 0!==r?r:this._model,M=void 0!==(null==e?void 0:e.mode)?e.mode:D?this.options.mode:void 0,N=null===(d=this.options.cloud)||void 0===d?void 0:d.envVars,x=null===(l=null==e?void 0:e.cloud)||void 0===l?void 0:l.envVars,K=void 0!==(null==e?void 0:e.onStep)||void 0!==(null==e?void 0:e.onDelta)?Object.assign(Object.assign({},void 0!==e.onStep?{onStep:e.onStep}:{}),void 0!==e.onDelta?{onDelta:e.onDelta}:{}):void 0;let P;if(D){const t=(0,u.SB)(this.options.agents),i=C(N),n=yield this.client.createAgent(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},i?{}:{agentId:this.agentId}),{prompt:A}),void 0!==E?{model:E}:{}),void 0!==this.options.name?{name:this.options.name}:{}),{mcpServers:a(k)}),void 0!==t?{customSubagents:t}:{}),{env:null===(c=this.options.cloud)||void 0===c?void 0:c.env}),C(N)?{envVars:N}:{}),C(x)?{runEnvVars:x}:{}),{repos:null===(h=this.options.cloud)||void 0===h?void 0:h.repos,workOnCurrentBranch:null===(v=this.options.cloud)||void 0===v?void 0:v.workOnCurrentBranch,autoCreatePR:null===(f=this.options.cloud)||void 0===f?void 0:f.autoCreatePR,skipReviewerRequest:null===(g=this.options.cloud)||void 0===g?void 0:g.skipReviewerRequest}),void 0!==M?{mode:M}:{}),{idempotencyKey:null!==(m=null==e?void 0:e.idempotencyKey)&&void 0!==m?m:this.options.idempotencyKey});if(i)this.agentId=n.agent.id;else if(n.agent.id!==this.agentId)throw new o.c$(`Server returned mismatched agent id "${n.agent.id}"; expected "${this.agentId}". This indicates a backend bug.`,{isRetryable:!1});this.serverCreated=!0,P=new R(this.client,n.run,K,E)}else{const t=yield this.client.createRun(this.agentId,Object.assign(Object.assign(Object.assign({prompt:A,mcpServers:a(k)},void 0!==(null==e?void 0:e.model)?{model:e.model}:{}),C(x)?{envVars:x}:{}),void 0!==M?{mode:M}:{}),{idempotencyKey:null==e?void 0:e.idempotencyKey});P=new R(this.client,t.run,K,E)}void 0!==(null==e?void 0:e.model)&&(this._model=e.model);const U=null!==(w=null===(y=null===(p=this.options.cloud)||void 0===p?void 0:p.env)||void 0===y?void 0:y.type)&&void 0!==w?w:"cloud",q=null==E?void 0:E.params;(0,s.Zn)(this.options.apiKey,Object.assign(Object.assign({agent_id:this.agentId,run_id:P.id,request_id:P.requestId,runtime:U,model:null!==(b=null==E?void 0:E.id)&&void 0!==b?b:"default"},q&&q.length>0?{model_params:JSON.stringify(q)}:{}),{prompt_length:A.text.length,has_images:(null!==(I=null===(_=A.images)||void 0===_?void 0:_.length)&&void 0!==I?I:0)>0,is_resume:!D,mcp_server_count:Object.keys(null!=k?k:{}).length,cloud_repo_count:null===(O=null===(S=this.options.cloud)||void 0===S?void 0:S.repos)||void 0===O?void 0:O.length,cloud_auto_create_pr:null===(j=this.options.cloud)||void 0===j?void 0:j.autoCreatePR})),this.activeRuns.add(P);const T=this.options.apiKey,$=this.agentId,L=P.id;return P.wait().then((t=>{(0,s.G5)(T,{agent_id:$,run_id:L,request_id:P.requestId,runtime:U,end_reason:"finished"===t.status?"success":"cancelled"===t.status?"abort":"error"})})).finally((()=>{this.activeRuns.delete(P)})),P.ensureStreamStarted(),P}catch(t){throw(0,o.Nt)(t,{operation:"agent.send"})}}))}close(){for(const t of this.activeRuns)t.abortClientStream();(0,s.rd)()}reload(){return v(this,void 0,void 0,(function*(){}))}[Symbol.asyncDispose](){return v(this,void 0,void 0,(function*(){yield Promise.allSettled(Array.from(this.activeRuns,(t=>t.disposeClientStream()))),yield(0,s.rd)()}))}listArtifacts(){return v(this,void 0,void 0,(function*(){try{return this.serverCreated?(yield this.client.listArtifacts(this.agentId)).items.map((t=>({path:t.path,sizeBytes:t.sizeBytes,updatedAt:t.updatedAt}))):[]}catch(t){throw(0,o.Nt)(t,{operation:"agent.listArtifacts"})}}))}downloadArtifact(t){return v(this,void 0,void 0,(function*(){try{if(!this.serverCreated)throw new o.j1("Agent has not been created yet; call send() first.",{isRetryable:!1});const{url:e}=yield this.client.getArtifactDownloadUrl({agentId:this.agentId,path:t});let i;try{i=yield fetch(e)}catch(t){throw new o.Dr("Failed to download artifact",{cause:t,isRetryable:!0})}if(!i.ok)throw new o.Dr(`Failed to download artifact: ${i.status}`,{status:i.status,isRetryable:i.status>=500});return Buffer.from(yield i.arrayBuffer())}catch(t){throw(0,o.Nt)(t,{operation:"agent.downloadArtifact"})}}))}}function C(t){return void 0!==t&&Object.keys(t).length>0}function A(t){var e,i;const s=g(t.apiKey);if(void 0!==t.agentId&&C(null===(e=t.cloud)||void 0===e?void 0:e.envVars))throw new o.j1("cloud.envVars cannot be combined with agentId; omit agentId so the server can mint an agent id.",{isRetryable:!1});const a=new r.N(s),d=null!==(i=t.agentId)&&void 0!==i?i:(0,n.M2)();return new j(d,a,t,!1)}function D(t){return v(this,arguments,void 0,(function*({apiKey:t,model:e}){const i="string"==typeof e?e.trim():e.id.trim();if(0===i.length)throw new o.j1("Model id is required. Pass a non-empty `model.id` or `model: '<model-id>'`.",{isRetryable:!1,code:"invalid_model"});let n,s;try{n=g(t)}catch(t){if(t instanceof o.j1)return;throw t}try{s=(yield new r.N(n).listModels()).items}catch(t){if(t instanceof o.Dr||t instanceof o.v3||t instanceof o.OE)return;throw t}const a=s.some((t=>{var e;return t.id===i||!0===(null===(e=t.aliases)||void 0===e?void 0:e.includes(i))}));if(!a)throw new o.j1(`Model '${i}' is not available or invalid. Call Cursor.models.list() to see valid model ids.`,{isRetryable:!1,code:"invalid_model"})}))}function k(t,e){const i=g(e.apiKey),n=new r.N(i);return new j(t,n,Object.assign({},e),!0)}function E(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new r.N(e),n=yield i.listAgents({limit:t.limit,cursor:t.cursor,prUrl:t.prUrl,includeArchived:t.includeArchived});return{items:n.items.map(K),nextCursor:n.nextCursor}}))}function M(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new r.N(i),s=yield n.listRuns(t,{limit:e.limit,cursor:e.cursor});return{items:s.items.map((t=>new R(n,t))),nextCursor:s.nextCursor}}))}function N(t,e){return v(this,void 0,void 0,(function*(){y(t),p(e.agentId);const i=g(e.apiKey),n=new r.N(i),s=yield n.getRun({agentId:e.agentId,runId:t});return new R(n,s)}))}function x(t,e){return v(this,void 0,void 0,(function*(){y(t),p(e.agentId);const i=g(e.apiKey),n=new r.N(i);yield n.cancelRun({agentId:e.agentId,runId:t})}))}function K(t){var e,i,n;return{agentId:t.id,name:null!==(e=t.name)&&void 0!==e?e:"",summary:null!==(i=t.name)&&void 0!==i?i:"",lastModified:new Date(t.updatedAt).getTime(),createdAt:new Date(t.createdAt).getTime(),archived:"ARCHIVED"===t.status,runtime:"cloud",env:t.env,repos:null===(n=t.repos)||void 0===n?void 0:n.map((t=>t.url))}}function P(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new r.N(i);return K(yield n.getAgent(t))}))}function U(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new r.N(i);yield n.archiveAgent(t)}))}function q(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new r.N(i);yield n.unarchiveAgent(t)}))}function T(t,e){return v(this,void 0,void 0,(function*(){const i=g(e.apiKey),n=new r.N(i);yield n.deleteAgent(t)}))}function $(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey);return new r.N(e).getMe()}))}function L(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new r.N(e);return(yield i.listModels()).items}))}function F(t){return v(this,void 0,void 0,(function*(){const e=g(t.apiKey),i=new r.N(e);return(yield i.listRepositories()).items}))}}};
|