@zortexhq/indra-v2.5 0.4.1 → 0.4.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/README.md +5 -5
- package/bin/codex-postinstall.mjs +1 -1
- package/dist/action-effect.js +1 -0
- package/dist/action-read-progress.js +1 -1
- package/dist/actions-catalog.js +1 -0
- package/dist/auto-sync.js +1 -1
- package/dist/auto-update.js +1 -1
- package/dist/automatic-updates.js +1 -0
- package/dist/bundled-handbook.js +1 -1
- package/dist/cli-run.js +1 -1
- package/dist/cli.js +1 -1
- package/dist/codex-install.js +1 -1
- package/dist/codex-setup.js +1 -1
- package/dist/computer-use-setup.js +1 -0
- package/dist/default-root.js +1 -1
- package/dist/documentation-action.js +1 -0
- package/dist/gateway.js +1 -1
- package/dist/imessage-sync.js +1 -1
- package/dist/local-cloud-policy.js +1 -1
- package/dist/local-cloud.js +1 -1
- package/dist/mcp.js +1 -3
- package/dist/native-connect.js +1 -1
- package/dist/native-level1-setup.js +1 -1
- package/dist/native-ollama-discovery.js +1 -0
- package/dist/native-vault-discovery.js +1 -1
- package/dist/onboard-cli.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/onboarding.js +1 -1
- package/dist/profile.js +1 -1
- package/dist/public-tool.js +4 -1
- package/dist/recovery-authorization-url.js +1 -1
- package/dist/recovery-progress.js +1 -1
- package/dist/recovery.js +1 -1
- package/dist/resident-autopilot.js +1 -0
- package/dist/resident-ensure-ready.js +1 -1
- package/dist/resident-host.js +2 -2
- package/dist/resident-jobs.js +1 -1
- package/dist/resident-platform.js +2 -2
- package/dist/resident-runtime-identity.js +1 -1
- package/dist/resident-startup-state.js +1 -0
- package/dist/resident-telemetry.js +1 -1
- package/dist/shared-action-schemas.js +1 -0
- package/dist/source-data.js +1 -1
- package/dist/storage-compatibility.js +1 -0
- package/dist/supervised-sync.js +1 -1
- package/dist/tools.js +1 -1
- package/dist/update-check.js +1 -1
- package/dist/update-cli.js +1 -1
- package/dist/update-command.js +1 -1
- package/dist/update-recovery.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/durable-dispatcher.js +1 -1
- package/node_modules/@zortexhq/plugin-auto-connect/dist/api/job-contract.js +1 -1
- package/node_modules/@zortexhq/plugin-autopilot/dist/api.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/cua.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/feedback.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/index.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/python-runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/service.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/dist/worker.js +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/package.json +23 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/LICENSE +21 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/PROVENANCE.json +38 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/__init__.py +1 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/agent.py +178 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/browser.py +13 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/indra.patch +57 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/model.py +180 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/questions.py +26 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/jev_ultrafast/transport.py +70 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/strategies.py +154 -0
- package/node_modules/@zortexhq/plugin-autopilot/python/worker.py +260 -0
- package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-computer-files/dist/catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/action-outcome.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/content-acquisition.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/authorization-metrics.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-core/dist/native-principal.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-drive/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/dist/connector.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-gmail/package.json +2 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/compounds.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-google-tasks/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-music-server.js +6 -6
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-native-process.mjs +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-notes-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-helper.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/apple-reminders-server.js +2 -2
- package/node_modules/@zortexhq/plugin-connector-level1/dist/cua-runtime.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/macos-contacts-server.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-apple-native.js +1 -0
- package/node_modules/@zortexhq/plugin-connector-level1/dist/prepared-local.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-outlook/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-slack/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/actions.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-teams/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/auth-state.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-whatsapp/dist/provider.js +1 -1
- package/node_modules/@zortexhq/plugin-connector-youtube/dist/source.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/api/action-schemas.js +1 -0
- package/node_modules/@zortexhq/plugin-context-share/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-context-share/dist/share.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/file-catalog.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/dist/original-adapter.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/account.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n-twin.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
- package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -1
- package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/api/execution-scope.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/api/stdio-transport.js +1 -0
- package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
- package/node_modules/@zortexhq/plugin-process-local/dist/windows-job.js +1 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/index.js +4 -1
- package/node_modules/@zortexhq/plugin-product-account/dist/session-store.js +10 -0
- package/node_modules/@zortexhq/plugin-product-account/dist/storage.js +1 -0
- package/node_modules/@zortexhq/plugin-product-account/package.json +5 -1
- package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/public-result-visibility.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/content-acquisition.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/credentials.js +3 -3
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/keychain.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/public-visibility.js +7 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/recovery-guard.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/runtime.js +1 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/schema.js +2 -0
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/search-records.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-tables.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot-worker.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/snapshot.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/source-sync.js +1 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql-worker.js +2 -1
- package/node_modules/@zortexhq/plugin-vault-sqlite/dist/sql.js +1 -1
- package/package.json +13 -7
- package/profiles/core.yml +2 -0
- package/release-provenance.json +43 -36
- package/update-manifest.json +516 -275
- package/dist/content-find.js +0 -2
- package/dist/find-snapshots.js +0 -1
- package/dist/match-excerpt.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["tasklists","tasks"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers}))}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(fail("resource_exhausted","Tasks source has reached its active call bound"));const task=invokeInner(id,call,options).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return fail("invalid_argument","Tasks has no media-upload method");if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
|
|
1
|
+
import{Original,businessError}from"@zortexhq/plugin-connector-framework/api";import{actionOutcome,actionNotApplied,validateRead,readResult,connectionState}from"@zortexhq/plugin-connector-core/api";import{createHash}from"node:crypto";import{METHODS,DISCOVERY_PIN}from"./generated.js";import{createTasksConnector}from"./connector.js";import{createTasksCompounds}from"./compounds.js";import{COMPOUND_METHODS}from"./compound-generated.js";import{record,protectedAuthority,safeProvider,validate}from"./guards.js";export function createTasksSource({parts,auth,vault,transport,transportSync,compoundCustody,compoundReceipts,now=()=>new Date().toISOString()}){const info={source:"google-tasks",label:"Google Tasks",group:"Connector / Google",auth:"oauth-browser",data:{history:"sync",updates:"rescan",retention:"durable",resources:["tasklists","tasks"],limitations:[]}},stop=new AbortController,pending=new Set;let closed=false,principal=null,activeScopes=[];const fail=(code,message,layer="connector")=>businessError(code,message,layer);const methods=new Map(METHODS.flatMap(row=>[[row.id,row],[row.contract,row]]));const mutationReceipts=new Map;const method=id=>methods.has(id)?Original.ok(structuredClone(methods.get(id))):fail("not_found","Google Tasks method is not in the pinned provider catalog");const publicMethod=id=>{const compound=COMPOUND_METHODS.find(row=>row.id===id),selected=compound?Original.ok(structuredClone(compound)):method(id);return"ok"in selected?Original.ok({...selected.ok,httpMethod:selected.ok.method,...compound?{}:{level:1,effect:selected.ok.method==="GET"?"read":"write"}}):selected};async function resolveGrant(){if(closed)return fail("aborted","Tasks source is inactive");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(!selected.ok||selected.ok.state!=="connected")return fail("unauthenticated","Connect Google Tasks before reading or acting","auth");if(typeof selected.ok.accountId!=="string"||!selected.ok.accountId.trim())return fail("failed_precondition","Google Tasks requires a verified OIDC subject; an email or grant id is not an account identity","auth");principal=selected.ok.accountId;activeScopes=[...selected.ok.scopes];return Original.ok({id:"0"+createHash("sha256").update(principal).digest("hex").slice(0,25).toUpperCase(),source:"google-tasks",account:principal,scopes:activeScopes,expiresAt:"2036-01-01T00:00:00.000Z"})}function prepare(row,call){if(protectedAuthority(call))return fail("invalid_argument","Credential or resource-key authority is forbidden in source action parameters");const invalid=validate(row.params,call);if(invalid)return fail("invalid_argument",invalid);if(!record(call)||!record(call.params))return fail("invalid_argument","Provider calls require the declared params object");const max=call.params["maxResults"];if(max!==void 0&&(typeof max!=="number"||max<1||max>(row.resource==="tasklists"?1e3:100)))return fail("invalid_argument","Google Tasks maxResults is outside the documented page bound");let path=row.path;const query=new URLSearchParams;for(const[key,value]of Object.entries(call.params)){if(row.parameterLocations[key]==="path"){if(typeof value!=="string"||!value||value==="."||value===".."||value.length>4096)return fail("invalid_argument","Tasks provider identity is invalid");path=path.replace("{"+key+"}",encodeURIComponent(value))}else query.set(key,String(value))}if(path.includes("{"))return fail("invalid_argument","Google Tasks call is missing a required path identity");const url="https://tasks.googleapis.com/"+path+(query.size?"?"+query:"");const body=call.body===void 0?void 0:JSON.stringify(call.body);if(body!==void 0&&Buffer.byteLength(body)>2097152)return fail("resource_exhausted","Tasks input body exceeds the custody bound");return Original.ok({url,...body===void 0?{}:{body}})}function decode(row,raw){if(Buffer.byteLength(raw.body)>2097152)return fail("resource_exhausted","Tasks provider response exceeds the custody bound");if(raw.status>=400){let diagnostic={};try{diagnostic=safeProvider(JSON.parse(raw.body)).data}catch{}const googleRule=parts.googleStatusOverrideV1(JSON.stringify(diagnostic));return actionOutcome(Original.errResult(parts.webStatusFailureV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:status2=>status2===400?{code:"invalid_argument",retryability:"non-retryable",meaning:"provider rejected the Tasks request"}:googleRule(status2),headers:raw.headers})),raw.status===400?"not_applied":"unknown")}let object;if(raw.status===204&&raw.body==="")object={};else try{object=JSON.parse(raw.body)}catch{return fail("data_loss","Google Tasks returned invalid JSON")}if(!record(object))return fail("data_loss","Google Tasks returned a non-object response");const safe=safeProvider(object);const status=parts.webStatusErrorV1(raw.status,{provider:"Google Tasks",what:row.id,bodyOverride:parts.googleStatusOverrideV1(JSON.stringify(safe.data)),headers:raw.headers});if(status)return Original.errResult(status);const payload=safe.data;const isList=row.operation==="list";if(isList&&payload["items"]!==void 0&&!Array.isArray(payload["items"]))return fail("data_loss","Google Tasks returned invalid items");const items=isList?payload["items"]??[]:row.method==="GET"?[payload]:[];if(!Array.isArray(items)||items.some(item=>!record(item)))return fail("data_loss","Google Tasks returned a malformed item collection");const next=payload["nextPageToken"];if(next!==void 0&&(typeof next!=="string"||next.length>8192||!next))return fail("data_loss","Google Tasks returned an invalid page token");return Original.ok({method:row.id,resource:row.resource,data:payload,items,...typeof next==="string"?{nextPageToken:next}:{},warnings:safe.withheld?["Protected assignment resource-key authority was withheld; origin-document access is not implied."]:[],effect:row.method==="GET"?"read":"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}})}async function invokeInner(id,call,options={},dispatched=()=>{}){call=structuredClone(call);if(closed||options.signal?.aborted)return fail("aborted","Tasks source request was stopped");const row=method(id);if(!("ok"in row))return row;const prepared=prepare(row.ok,call);if(!("ok"in prepared))return prepared;const grant=await resolveGrant();if(!("ok"in grant))return grant;const boundPrincipal=principal;if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied",row.ok.method==="GET"?"Google Tasks read scope is missing":"Google Tasks write scope requires separate user consent","auth");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=await invoke("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}},options);if(!("ok"in target))return target;if(record(target.ok.data["assignmentInfo"]))return fail("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted");if(principal!==boundPrincipal)return fail("permission_denied","Tasks account changed before conditional field mutation","auth")}const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;const request={method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"},signal};dispatched();const response=transport?await transport("google-tasks",prepared.ok.url,request):await auth.requestRaw("google-tasks",prepared.ok.url,request);if(closed||signal.aborted)return fail("aborted","Tasks response arrived after cancellation");const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;if(selected.ok?.accountId!==boundPrincipal||principal!==boundPrincipal)return fail("permission_denied","Tasks account changed while the provider request was active","auth");return"ok"in response?decode(row.ok,response.ok):response}function invoke(id,call,options={}){if(pending.size>=32)return Promise.resolve(actionNotApplied(fail("resource_exhausted","Tasks source has reached its active call bound")));let dispatched=false;const task=invokeInner(id,call,options,()=>{dispatched=true}).then(result=>dispatched?actionOutcome(result,"unknown"):actionNotApplied(result),()=>actionOutcome(fail(options.signal?.aborted?"aborted":"unavailable","Tasks request did not complete."),dispatched?"unknown":"not_applied")).finally(()=>pending.delete(task));pending.add(task);return task}function invokeSync(id,call){call=structuredClone(call);if(!transportSync)return parts.gateRefusal("Google Tasks synchronous request","fixture-oracle only");if(!principal)return parts.gateRefusal("Google Tasks synchronous identity","bind verified account first");const row=method(id);if(!("ok"in row))return"err"in row?row:parts.connectorError("data_loss","Tasks method lookup was unconfirmed");const prepared=prepare(row.ok,call);if(!("ok"in prepared))return"err"in prepared?prepared:parts.connectorError("data_loss","Tasks input validation was unconfirmed");if(!row.ok.scopes.some(scope=>activeScopes.includes(scope)))return parts.connectorError("permission_denied","Google Tasks scope is missing");if(row.ok.resource==="tasks"&&["patch","update"].includes(row.ok.operation)&&record(call.body)&&Object.hasOwn(call.body,"deleted")){const target=invokeSync("tasks.tasks.get",{params:{tasklist:call.params["tasklist"],task:call.params["task"]}});if(!Original.isOk(target))return target;if(record(target.ok.data["assignmentInfo"]))return parts.connectorError("permission_denied","Task.deleted is readonly for assigned tasks; no source write was attempted")}const response=transportSync("google-tasks",prepared.ok.url,{method:row.ok.method,...prepared.ok.body===void 0?{}:{body:prepared.ok.body,contentType:"application/json"}});return"ok"in response?decode(row.ok,response.ok):"err"in response?response:parts.connectorError("data_loss","Tasks fixture response was unconfirmed")}const asOriginal=async(id,call,options)=>{const reply=await invoke(id,call,options);return"empty"in reply?parts.connectorError("data_loss","Tasks provider read was unconfirmed"):reply};const connector=createTasksConnector({parts,accountId:()=>principal,request:asOriginal,...transportSync?{requestSync:invokeSync}:{},now,live:()=>!closed});const rawCompounds=createTasksCompounds({invoke,account:()=>principal,...compoundCustody?{conditional:{async compareAndMutate(input){const selected=method(input.method);if(!("ok"in selected))return selected;const valid=prepare(selected.ok,input.call);if(!("ok"in valid))return valid;const grant=await resolveGrant();if(!("ok"in grant))return grant;if(input.accountId!==principal||!selected.ok.scopes.some(scope=>activeScopes.includes(scope)))return fail("permission_denied","Compound mutation authority is not bound to the verified write account","auth");return compoundCustody.compareAndMutate(input)}}}:{},...compoundReceipts?{receipts:compoundReceipts}:{}});function owned(task){const settled=task.finally(()=>pending.delete(settled));pending.add(settled);return settled}const compOptions=read=>({signal:read?.signal?AbortSignal.any([read.signal,stop.signal]):stop.signal});const compounds={execute(name,input,key,read){input=structuredClone(input);return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.execute(name,input,key,compOptions(read))})())},compensate(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.compensate(key,compOptions(read))})())},probe(key){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return Original.ok({reading:"unknown"});return rawCompounds.probe(key)})())},recover(key,read){return owned((async()=>{const grant=await resolveGrant();if(!("ok"in grant))return grant;return rawCompounds.recover(key,compOptions(read))})())}};const arms={},probes={};for(const row of METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!row.scopes.some(scope=>grant.scopes.includes(scope)))return parts.connectorError("permission_denied","Tasks action grant does not authorize this method");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Tasks action must use the discovered input wrapper");const input=call.params,reply=await asOriginal(row.id,input,{signal:call.signal});if(!Original.isOk(reply))return reply;if(row.method==="GET")return Original.ok({result:reply.ok.data});if(mutationReceipts.size>=256)mutationReceipts.delete(mutationReceipts.keys().next().value);mutationReceipts.set(call.idempotencyKey,{method:row,call:structuredClone(input),reply:reply.ok});return Original.ok({evidenceHint:"google-tasks provider accepted mutation; verification required"})};if(row.method!=="GET")probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const receipt=mutationReceipts.get(call.idempotencyKey);if(!receipt)return Original.ok({reading:"unknown"});const params=receipt.call.params,body=receipt.call.body;if(row.operation==="clear"||row.operation==="move"||row.operation==="delete"||record(receipt.reply.data["assignmentInfo"]))return Original.ok({reading:"unknown"});const id=typeof receipt.reply.data["id"]==="string"?receipt.reply.data["id"]:params[row.resource==="tasklists"?"tasklist":"task"];if(typeof id!=="string")return Original.ok({reading:"unknown"});const lookup=row.resource==="tasklists"?{tasklist:id}:{tasklist:params["tasklist"],task:id};const answer=await invoke(row.resource==="tasklists"?"tasks.tasklists.get":"tasks.tasks.get",{params:lookup});if("err"in answer){if(row.operation==="delete"&&answer.err.code==="not_found")return Original.ok({reading:"effected"});return Original.ok({reading:"unknown"})}if(!("ok"in answer))return Original.ok({reading:"unknown"});if(row.operation==="delete")return Original.ok({reading:"absent"});if(!record(body))return Original.ok({reading:"unknown"});const matches=Object.entries(body).every(([key,value])=>JSON.stringify(answer.ok.data[key])===JSON.stringify(value));return Original.ok({reading:matches?"effected":"absent"})}}}connector.actionRail=parts.defineConnectorActions({arms,probes});for(const row of COMPOUND_METHODS){arms[row.contract]=async(grant,call)=>{if(grant.source!=="google-tasks"||!grant.scopes.includes("https://www.googleapis.com/auth/tasks"))return parts.connectorError("permission_denied","Personal compound requires an authorized Tasks write grant");if(!record(call.params)||!record(call.params["params"]))return parts.connectorError("invalid_argument","Personal compound requires generated wrapper parameters");const result=await compounds.execute(row.contract,call.params,call.idempotencyKey,{signal:call.signal});return"ok"in result?Original.ok({evidenceHint:"google-tasks-compound:"+result.ok.receiptKey}):"err"in result?result:parts.connectorError("data_loss","Compound execution was unconfirmed")};probes[row.contract+".verify"]={confidentAfterMs:0,read:async(_grant,call)=>{const result=await compounds.probe(call.idempotencyKey);return"ok"in result?Original.ok(result.ok):"err"in result?result:parts.connectorError("data_loss","Compound probe was unconfirmed")}}}connector.actionRail=parts.defineConnectorActions({arms,probes});const service={info,connector,compounds,resolveGrant,status:()=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):connectionState(vault,info),connect:options=>closed?Promise.resolve(fail("aborted","Tasks source is inactive")):auth.connect("google-tasks",options),job:id=>closed?fail("aborted","Tasks source is inactive"):auth.job(id),cancelJob:id=>auth.cancelJob(id),method,invoke,catalog(options={}){const limit=options.limit??20,cursor=options.cursor??0;if(!Number.isInteger(limit)||limit<1||limit>100||!Number.isInteger(cursor)||cursor<0)return fail("invalid_argument","Catalog limit/cursor is invalid");const rows=METHODS.filter(row=>(!options.resource||row.resource===options.resource)&&(!options.query||(row.id+" "+row.description).toLowerCase().includes(options.query.toLowerCase())));return Original.ok({total:rows.length,methods:rows.slice(cursor,cursor+limit).map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),...cursor+limit<rows.length?{next:cursor+limit}:{},pin:DISCOVERY_PIN,gaps:["Tasks API exposes dates only, no due time of day, reminders, recurrence rule, attachments, author or complete revision history.","Assignment resource keys are protected; fetching its Docs/Chat origin requires that source authorization."]})},async*pages(id,params,options={}){const row=method(id);if(!("ok"in row)){yield row;return}if(row.ok.method!=="GET"||row.ok.operation!=="list"){yield fail("invalid_argument","Pagination only applies to Tasks read-list methods");return}const max=options.maxPages??1e4;if(!Number.isInteger(max)||max<1||max>1e5){yield fail("invalid_argument","maxPages is invalid");return}let current={...params};const seen=new Set;for(let page=0;page<max;page++){const answer=await invoke(id,{params:current},options);yield answer;if(!("ok"in answer)||!answer.ok.nextPageToken)return;const token=answer.ok.nextPageToken;if(seen.has(token)||current["pageToken"]===token){yield fail("data_loss","Google Tasks page token repeated; collection was not exhausted");return}seen.add(token);current={...current,pageToken:token}}yield fail("resource_exhausted","Requested pagination bound reached; collection is incomplete")},async check(options={}){if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const accountId=grant.ok.account;const answer=await invoke("tasks.tasklists.list",{params:{maxResults:1}},options);if(!("ok"in answer))return answer;const current=await vault.connection("google-tasks");if(closed||options.signal?.aborted)return fail("aborted","Tasks check was stopped");if(!("ok"in current))return current;if(current.ok?.state!=="connected"||current.ok.accountId!==accountId||!current.ok.scopes.some(scope=>scope==="https://www.googleapis.com/auth/tasks.readonly"||scope==="https://www.googleapis.com/auth/tasks"))return fail("permission_denied","Tasks check connection or scope changed","auth");if(answer.ok.items.length>1)return fail("data_loss","Tasks readiness response exceeded the requested one-record bound");return Original.ok({source:"google-tasks",basis:"read",operation:{state:"succeeded",returned:answer.ok.items.length}})},async read(request,options={}){const invalid=validateRead(request);if(invalid)return invalid;const signal=options.signal?AbortSignal.any([options.signal,stop.signal]):stop.signal;if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const grant=await resolveGrant();if(!("ok"in grant))return grant;const selected=await vault.connection("google-tasks");if(!("ok"in selected))return selected;const captured=structuredClone(selected.ok);if(!captured||captured.state!=="connected"||captured.accountId!==grant.ok.account)return fail("permission_denied","Tasks account changed before the selected read","auth");const readScope="https://www.googleapis.com/auth/tasks.readonly",writeScope="https://www.googleapis.com/auth/tasks",requiredScope=captured.scopes.includes(readScope)?readScope:captured.scopes.includes(writeScope)?writeScope:null;if(!requiredScope)return fail("permission_denied","Google Tasks read scope is missing","auth");const boundPrincipal=captured.accountId,boundGrant=structuredClone(grant.ok),limit=request.limit??1;const records=[],warnings=new Set;let scanned=0,matched=0;const fence=async()=>{if(closed||signal.aborted)return fail("aborted","Tasks read was stopped");const current=await vault.connection("google-tasks");if(!("ok"in current))return current;if(!current.ok||current.ok.state!=="connected"||current.ok.account!==captured.account||current.ok.accountId!==boundPrincipal||!current.ok.scopes.includes(requiredScope))return fail("permission_denied","Tasks read connection or scope changed","auth");return Original.ok(void 0)};const reading=createTasksConnector({parts,accountId:()=>boundPrincipal,request:async(id,call)=>{const before=await fence();if(!("ok"in before))return"err"in before?before:parts.connectorError("data_loss","Tasks read fence was unconfirmed");const answer2=await asOriginal(id,call,{signal});const after=await fence();return"ok"in after?answer2:"err"in after?after:parts.connectorError("data_loss","Tasks read fence was unconfirmed")},now,live:()=>!closed&&!signal.aborted});for await(const page of reading.scan(boundGrant,null)){if(signal.aborted||closed)return fail("aborted","Tasks read was stopped");if(!Original.isOk(page))return page;scanned+=page.ok.items.length;for(const note of page.ok.notes??[])warnings.add(note);for(const item of page.ok.items){const proto=reading.normalize(item),fields=record(proto.payload)?proto.payload:{};if(fields["deleted"]===true)continue;const text=proto.body??"";if(request.query&&!text.toLowerCase().includes(request.query.toLowerCase()))continue;if(request.since&&Date.parse(proto.ts)<Date.parse(request.since)||request.until&&Date.parse(proto.ts)>Date.parse(request.until))continue;matched++;records.push({source:"google-tasks",sourceId:encodeURIComponent(boundPrincipal)+":"+proto.nk.sourceId,stream:proto.nk.stream,kind:proto.kind,ts:proto.ts,body:text,fields});records.sort((a,b)=>(b.ts??"").localeCompare(a.ts??"")||(a.sourceId??"").localeCompare(b.sourceId??""));if(records.length>limit)records.length=limit}}const beforeReturn=await fence();if(!("ok"in beforeReturn))return beforeReturn;const answer=readResult("google-tasks",records,[...warnings]);return"ok"in answer?Original.ok({...answer.ok,scanned,matched}):answer},async close(){closed=true;stop.abort();await Promise.allSettled([...pending]);mutationReceipts.clear();principal=null;activeScopes=[]}};const ownedRead=service.read.bind(service);service.read=(request,options)=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedRead(request,options).finally(()=>pending.delete(task));pending.add(task);return task};const ownedCheck=service.check.bind(service);service.check=options=>{if(closed)return Promise.resolve(fail("aborted","Tasks source is inactive"));const task=ownedCheck(options).finally(()=>pending.delete(task));pending.add(task);return task};service.actions={catalog(input){if(input?.profile&&input.profile!=="data")return fail("invalid_argument","Tasks supports the data profile only");if(input?.resource==="personal"||input?.resource==="personal-deleted"){const selected=COMPOUND_METHODS.filter(row=>row.resource===input.resource);return Original.ok({total:selected.length,methods:selected.map(row=>({id:row.id,contract:row.contract,resource:row.resource,method:row.method,scopes:row.scopes,body:row.body,media:false})),pin:"zortex-personal-task-compound@1",gaps:["Requires host atomic target+collection guard custody and durable private receipts"]})}const raw=service.catalog(input);return"ok"in raw?Original.ok({...raw.ok,additionalOperationResources:["personal","personal-deleted"]}):raw},method:publicMethod,async invoke(id,input,options){if(input.media!==void 0)return actionNotApplied(fail("invalid_argument","Tasks has no media-upload method"));if(COMPOUND_METHODS.some(row=>row.id===id)){const receiptKey=Original.ulid();const result=await compounds.execute(id,input,receiptKey,options);return"ok"in result?Original.ok({method:id,resource:"personal",data:result.ok,items:[],warnings:["Private compound accepted; query its receipt/probe before claiming an effect"],effect:"unverified",coverage:{wholeUserCorpus:false,scope:"selected-method"}}):result}return invoke(id,input,options)}};return service}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{appleMusicTools}from"./apple-music-tools.js";const runFile=promisify(execFile);const prelude=`const app=Application('Music');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";import{appleMusicTools}from"./apple-music-tools.js";const runFile=promisify(execFile);const prelude=`const app=Application('Music');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
5
5
|
const libraries=()=>app.libraryPlaylists();
|
|
6
6
|
const library=()=>{const xs=libraries();if(!xs.length)throw Error('Music library not found');return xs[0]};
|
|
7
|
-
const playlistRow=p=>({id:safe(()=>p.
|
|
8
|
-
const trackRow=t=>({id:safe(()=>t.
|
|
7
|
+
const playlistRow=p=>({id:safe(()=>p.persistentID()),name:safe(()=>p.name(),''),kind:String(safe(()=>p.specialKind(),'none')),duration:Number(safe(()=>p.duration(),0)),trackCount:Number(safe(()=>p.tracks().length,0)),visible:Boolean(safe(()=>p.visible(),true))});
|
|
8
|
+
const trackRow=t=>({id:safe(()=>t.persistentID()),databaseId:Number(safe(()=>t.databaseID(),0)),name:safe(()=>t.name(),''),artist:safe(()=>t.artist(),''),album:safe(()=>t.album(),''),albumArtist:safe(()=>t.albumArtist(),''),composer:safe(()=>t.composer(),''),genre:safe(()=>t.genre(),''),duration:Number(safe(()=>t.duration(),0)),dateAdded:iso(safe(()=>t.dateAdded())),playedDate:iso(safe(()=>t.playedDate())),playedCount:Number(safe(()=>t.playedCount(),0)),rating:Number(safe(()=>t.rating(),0)),favorited:Boolean(safe(()=>t.favorited(),false)),cloudStatus:String(safe(()=>t.cloudStatus(),'unknown'))});
|
|
9
9
|
const allPlaylists=()=>app.playlists();
|
|
10
|
-
const playlistById=id=>{for(const p of allPlaylists())if(String(safe(()=>p.
|
|
11
|
-
const userPlaylistById=id=>{for(const p of app.userPlaylists())if(String(safe(()=>p.
|
|
10
|
+
const playlistById=id=>{for(const p of allPlaylists())if(String(safe(()=>p.persistentID(),''))===id)return p;throw Error('Playlist not found')};
|
|
11
|
+
const userPlaylistById=id=>{for(const p of app.userPlaylists())if(String(safe(()=>p.persistentID(),''))===id)return p;throw Error('User playlist not found')};`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Music is available only on macOS.");const script=`(()=>{${prelude}
|
|
12
12
|
const a=${JSON.stringify(args)};
|
|
13
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-music-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.music.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-music-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
13
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-music-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.music.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-music-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Music helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr||"Music returned no result."),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Music (-1743).");if(/timed out|-1712/i.test(message))throw Error("Music did not answer before the action deadline (-1712).");throw Error(`Music action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`const l=library(),s=app.sources()[0];return JSON.stringify({libraryId:l.persistentID(),libraryName:l.name(),sourceName:s?s.name():null,applicationVersion:app.version()});`,a);if(name==="list_playlists")return jxa(`return JSON.stringify({playlists:allPlaylists().slice(0,a.limit||100).map(playlistRow)});`,a);if(name==="list_tracks")return jxa(`const p=a.playlistId?playlistById(a.playlistId):library();return JSON.stringify({playlist:playlistRow(p),tracks:p.tracks().slice(0,a.limit||100).map(trackRow)});`,a);if(name==="search_tracks")return jxa(`const p=a.playlistId?playlistById(a.playlistId):library(),xs=app.search(p,{for:a.query,only:'all'});return JSON.stringify({playlist:playlistRow(p),tracks:xs.slice(0,a.limit||50).map(trackRow)});`,a);if(name==="get_track")return jxa(`for(const t of library().tracks())if(String(safe(()=>t.persistentID(),''))===a.trackId)return JSON.stringify(trackRow(t));throw Error('Track not found');`,a);if(name==="get_playback")return jxa(`const t=safe(()=>app.currentTrack());return JSON.stringify({state:String(safe(()=>app.playerState(),'stopped')),position:Number(safe(()=>app.playerPosition(),0)),currentTrack:t?trackRow(t):null,currentPlaylist:safe(()=>playlistRow(app.currentPlaylist()))});`,a);if(name==="create_playlist")return jxa(`const p=app.UserPlaylist({name:a.name});app.userPlaylists.push(p);return JSON.stringify(playlistRow(p));`,a);if(name==="rename_playlist")return jxa(`const p=userPlaylistById(a.playlistId);p.name=a.name;return JSON.stringify(playlistRow(p));`,a);if(name==="delete_playlist")return jxa(`const p=userPlaylistById(a.playlistId);app.delete(p);return JSON.stringify({deleted:true,playlistId:a.playlistId});`,a);throw Error("This operation is not exposed.")}export function createAppleMusicServer(){const server=new Server({name:"zortex-apple-music",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleMusicTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleMusicServer(),{onerror:()=>process.stderr.write("Apple Music MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const NATIVE_CHILD_TIMEOUT=2e4;export const NATIVE_HELPER_TIMEOUT=3e4;export function nativeProcessError(result){const error=result.error;if(error?.code==="ETIMEDOUT"||error?.killed&&error?.signal==="SIGTERM")return"Native macOS read timed out.";return result.stderr||error?.message||(error?String(error):"Native macOS process returned no result.")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},noteId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_note",openWorldHint:false,idempotentHint:readOnly||name==="delete_note"}});export const appleNotesTools=[tool("get_identity","Read the default macOS Notes account that identifies the local Notes store.",{}),tool("list_folders","List Notes folders, including their owning account.",{}),tool("list_notes","List note metadata without note bodies.",{folderId:noteId,limit:{type:"integer",minimum:1,maximum:500}}),tool("search_notes","Search note titles in the local Notes store.",{query:text,limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_note","Read one note, including its body when it is unlocked.",{noteId},["noteId"]),tool("list_attachments","List attachment metadata for one note.",{noteId},["noteId"]),tool("create_note","Create a note in a selected folder.",{folderId:noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["folderId","title"],false),tool("update_note","Update the title or body of one note.",{noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["noteId"],false),tool("delete_note","Move one note to Notes Recently Deleted.",{noteId},["noteId"],false)];const prelude=`const app=Application('Notes');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},noteId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_note",openWorldHint:false,idempotentHint:readOnly||name==="delete_note"}});export const appleNotesTools=[tool("get_identity","Read the default macOS Notes account that identifies the local Notes store.",{}),tool("list_folders","List Notes folders, including their owning account.",{}),tool("list_notes","List note metadata without note bodies.",{folderId:noteId,limit:{type:"integer",minimum:1,maximum:500}}),tool("search_notes","Search note titles in the local Notes store.",{query:text,limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_note","Read one note, including its body when it is unlocked.",{noteId},["noteId"]),tool("list_attachments","List attachment metadata for one note.",{noteId},["noteId"]),tool("create_note","Create a note in a selected folder.",{folderId:noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["folderId","title"],false),tool("update_note","Update the title or body of one note.",{noteId,title:{type:"string",minLength:1,maxLength:255},body:{type:"string",maxLength:1e5}},["noteId"],false),tool("delete_note","Move one note to Notes Recently Deleted.",{noteId},["noteId"],false)];const prelude=`const app=Application('Notes');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
@@ -10,4 +10,4 @@ const folderById=id=>{for(const x of allFolders())if(x.id===id)return x.f;throw
|
|
|
10
10
|
const noteById=id=>{for(const x of allFolders()){try{const n=x.f.notes.byId(id);n.id();return n}catch(_){}}throw Error('Note not found in the selected account')};
|
|
11
11
|
const noteRow=(n,withBody=false)=>{const row={id:n.id(),name:safe(()=>n.name(),''),creationDate:iso(safe(()=>n.creationDate())),modificationDate:iso(safe(()=>n.modificationDate())),passwordProtected:safe(()=>n.passwordProtected(),false),shared:safe(()=>n.shared(),false)};if(withBody){try{row.body=n.body();row.bodyUnreadable=false}catch(_){row.body='';row.bodyUnreadable=true}}return row};`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Notes is available only on macOS.");const script=`(()=>{${prelude}
|
|
12
12
|
const a=${JSON.stringify(args)};
|
|
13
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-notes-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.notes.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-notes-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
13
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-notes-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.notes.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-notes-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Notes helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Notes (-1743).");if(/timed out|-1712/i.test(message))throw Error("Notes did not answer before the action deadline (-1712).");throw Error(`Notes action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`return JSON.stringify(identity());`,a);if(name==="list_folders")return jxa(`const who=identity();return JSON.stringify({identity:who,folders:allFolders().map(x=>({id:x.id,name:safe(()=>x.f.name()),shared:safe(()=>x.f.shared(),false)}))});`,a);if(name==="list_notes")return jxa(`const out=[];for(const x of allFolders()){if(a.folderId&&x.id!==a.folderId)continue;for(const n of safe(()=>x.f.notes(),[])){out.push({...noteRow(n),folderId:x.id,folderName:safe(()=>x.f.name())});if(out.length>=(a.limit||100))return JSON.stringify({notes:out})}}return JSON.stringify({notes:out});`,a);if(name==="search_notes")return jxa(`const q=a.query.toLocaleLowerCase(),out=[];for(const x of allFolders()){const ns=x.f.notes,ids=safe(()=>ns.id(),[]),names=safe(()=>ns.name(),[]),created=safe(()=>ns.creationDate(),[]),modified=safe(()=>ns.modificationDate(),[]),protectedValues=safe(()=>ns.passwordProtected(),[]),sharedValues=safe(()=>ns.shared(),[]);for(let i=0;i<ids.length;i++)if(String(names[i]||'').toLocaleLowerCase().includes(q)){out.push({id:ids[i],name:names[i]||'',creationDate:iso(created[i]),modificationDate:iso(modified[i]),passwordProtected:Boolean(protectedValues[i]),shared:Boolean(sharedValues[i]),folderId:x.id,folderName:safe(()=>x.f.name())});if(out.length>=(a.limit||50))return JSON.stringify({notes:out})}}return JSON.stringify({notes:out});`,a);if(name==="get_note")return jxa(`return JSON.stringify(noteRow(noteById(a.noteId),true));`,a);if(name==="list_attachments")return jxa(`const n=noteById(a.noteId),out=[],seen={};for(const x of safe(()=>n.attachments(),[])){const id=safe(()=>x.id());if(!id||seen[id])continue;seen[id]=1;out.push({id,name:safe(()=>x.name()),contentIdentifier:safe(()=>x.contentIdentifier()),creationDate:iso(safe(()=>x.creationDate())),modificationDate:iso(safe(()=>x.modificationDate())),url:safe(()=>x.url()),shared:safe(()=>x.shared(),false)})}return JSON.stringify({attachments:out});`,a);if(name==="create_note")return jxa(`const f=folderById(a.folderId),n=app.Note({body:noteHtml(a.title,a.body||'')});f.notes.push(n);return JSON.stringify(noteRow(n,true));`,a);if(name==="update_note")return jxa(`const n=noteById(a.noteId);if(a.title===undefined&&a.body===undefined)throw Error('Provide title or body');if(a.body!==undefined)n.body=noteHtml(a.title===undefined?n.name():a.title,a.body);else n.name=a.title;return JSON.stringify(noteRow(n,true));`,a);if(name==="delete_note")return jxa(`const n=noteById(a.noteId);app.delete(n);return JSON.stringify({deleted:true,noteId:a.noteId});`,a);throw Error("This operation is not exposed.")}export function createAppleNotesServer(){const server=new Server({name:"zortex-apple-notes",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleNotesTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleNotesServer(),{onerror:()=>process.stderr.write("Apple Notes MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{spawnSync}from"node:child_process";import{readFile,writeFile}from"node:fs/promises";const[inputPath,outputPath]=process.argv.slice(2);if(!inputPath||!outputPath)process.exit(2);let result;try{const script=await readFile(inputPath,"utf8");const child=spawnSync("/usr/bin/osascript",["-l","JavaScript","-e",script],{encoding:"utf8",timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});result={code:child.status??1,stdout:child.stdout??"",stderr:nativeProcessError(child)}}catch(error){result={code:1,stdout:"",stderr:String(error)}}await writeFile(outputPath,JSON.stringify(result),{encoding:"utf8",mode:384});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},nativeId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_reminder",openWorldHint:false,idempotentHint:readOnly||name==="delete_reminder"||name==="set_completed"}});export const appleRemindersTools=[tool("get_identity","Read the default macOS Reminders account that identifies the local store.",{}),tool("list_lists","List Reminders lists and their owning accounts.",{}),tool("list_reminders","List bounded reminder metadata.",{listId:nativeId,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:500}}),tool("search_reminders","Search reminder titles and notes.",{query:text,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_reminder","Read one reminder.",{reminderId:nativeId},["reminderId"]),tool("create_reminder","Create a reminder in a selected list.",{listId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["listId","title"],false),tool("update_reminder","Update the title, notes, priority, or flagged state of one reminder.",{reminderId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["reminderId"],false),tool("set_completed","Complete or reopen one reminder.",{reminderId:nativeId,completed:{type:"boolean"}},["reminderId","completed"],false),tool("delete_reminder","Delete one reminder.",{reminderId:nativeId},["reminderId"],false)];const prelude=`const app=Application('Reminders');
|
|
1
|
+
import{NATIVE_HELPER_TIMEOUT}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{mkdtemp,readFile,rm,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join}from"node:path";import{fileURLToPath}from"node:url";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const runFile=promisify(execFile),text={type:"string",minLength:1,maxLength:512},nativeId={...text,pattern:"^[^\\r\\n]+$"};const tool=(name,description,properties,required=[],readOnly=true)=>({name,description,inputSchema:{type:"object",properties,required,additionalProperties:false},annotations:{readOnlyHint:readOnly,destructiveHint:name==="delete_reminder",openWorldHint:false,idempotentHint:readOnly||name==="delete_reminder"||name==="set_completed"}});export const appleRemindersTools=[tool("get_identity","Read the default macOS Reminders account that identifies the local store.",{}),tool("list_lists","List Reminders lists and their owning accounts.",{}),tool("list_reminders","List bounded reminder metadata.",{listId:nativeId,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:500}}),tool("search_reminders","Search reminder titles and notes.",{query:text,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:100}},["query"]),tool("get_reminder","Read one reminder.",{reminderId:nativeId},["reminderId"]),tool("create_reminder","Create a reminder in a selected list.",{listId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["listId","title"],false),tool("update_reminder","Update the title, notes, priority, or flagged state of one reminder.",{reminderId:nativeId,title:{type:"string",minLength:1,maxLength:255},notes:{type:"string",maxLength:1e5},priority:{type:"integer",minimum:0,maximum:9},flagged:{type:"boolean"}},["reminderId"],false),tool("set_completed","Complete or reopen one reminder.",{reminderId:nativeId,completed:{type:"boolean"}},["reminderId","completed"],false),tool("delete_reminder","Delete one reminder.",{reminderId:nativeId},["reminderId"],false)];const prelude=`const app=Application('Reminders');
|
|
2
2
|
app.name();
|
|
3
3
|
const safe=(f,d=null)=>{try{return f()}catch(_){return d}};
|
|
4
4
|
const iso=d=>d&&d.toISOString?d.toISOString():null;
|
|
@@ -8,4 +8,4 @@ const listById=id=>{for(const x of allLists())if(x.id===id)return x.l;throw Erro
|
|
|
8
8
|
const reminderById=id=>{for(const x of allLists())for(const r of safe(()=>x.l.reminders(),[]))if(safe(()=>r.id())===id)return{r,list:x.l};throw Error('Reminder not found')};
|
|
9
9
|
const row=(r,l)=>({id:r.id(),name:safe(()=>r.name(),''),body:safe(()=>r.body(),''),completed:Boolean(safe(()=>r.completed(),false)),completionDate:iso(safe(()=>r.completionDate())),creationDate:iso(safe(()=>r.creationDate())),modificationDate:iso(safe(()=>r.modificationDate())),dueDate:iso(safe(()=>r.dueDate())),allDayDueDate:iso(safe(()=>r.alldayDueDate())),remindMeDate:iso(safe(()=>r.remindMeDate())),priority:Number(safe(()=>r.priority(),0)),flagged:Boolean(safe(()=>r.flagged(),false)),listId:l.id(),listName:safe(()=>l.name(),''),accountId:safe(()=>l.container().id()),accountName:safe(()=>l.container().name())});`;async function jxa(body,args){if(process.platform!=="darwin")throw Error("Apple Reminders is available only on macOS.");const script=`(()=>{${prelude}
|
|
10
10
|
const a=${JSON.stringify(args)};
|
|
11
|
-
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-reminders-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.reminders.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-reminders-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+
|
|
11
|
+
${body}})()`;const dir=await mkdtemp(join(tmpdir(),"zortex-reminders-")),input=join(dir,"input.js"),output=join(dir,"output.json"),label=`zortex.reminders.${process.pid}.${Date.now()}`;try{await writeFile(input,script,{encoding:"utf8",mode:384});await runFile("/bin/launchctl",["submit","-l",label,"--",process.execPath,fileURLToPath(new URL("./apple-reminders-helper.js",import.meta.url)),input,output],{timeout:5e3,maxBuffer:65536,env:{PATH:"/usr/bin:/bin"}});const deadline=Date.now()+NATIVE_HELPER_TIMEOUT;let raw="";while(Date.now()<deadline){try{raw=await readFile(output,"utf8");break}catch{await new Promise(done=>setTimeout(done,50))}}await runFile("/bin/launchctl",["remove",label],{timeout:5e3,maxBuffer:65536}).catch(()=>{});if(!raw)throw Error("Reminders helper timed out.");const result=JSON.parse(raw);if(result.code!==0)throw Object.assign(Error(result.stderr||"Reminders returned no result."),{stderr:result.stderr});return JSON.parse(result.stdout)}catch(error){const message=String(error?.stderr??error?.message??error);if(/-1743|not authorized to send apple events/i.test(message))throw Error("macOS denied Automation access to Reminders (-1743).");if(/timed out|-1712/i.test(message))throw Error("Reminders did not answer before the action deadline (-1712).");throw Error(`Reminders action failed: ${(message.split("\n")[0]??"unknown failure").slice(0,360)}`)}finally{await rm(dir,{recursive:true,force:true})}}async function call(name,a){if(name==="get_identity")return jxa(`return JSON.stringify(identity());`,a);if(name==="list_lists")return jxa(`const who=identity();return JSON.stringify({identity:who,lists:allLists().map(x=>({id:x.id,name:safe(()=>x.l.name(),''),color:safe(()=>x.l.color()),emblem:safe(()=>x.l.emblem()),accountId:safe(()=>x.l.container().id()),accountName:safe(()=>x.l.container().name())}))});`,a);if(name==="list_reminders")return jxa(`const out=[];for(const x of allLists()){if(a.listId&&x.id!==a.listId)continue;for(const r of safe(()=>x.l.reminders(),[])){const v=row(r,x.l);if(a.completed!==undefined&&v.completed!==a.completed)continue;out.push(v);if(out.length>=(a.limit||100))return JSON.stringify({reminders:out})}}return JSON.stringify({reminders:out});`,a);if(name==="search_reminders")return jxa(`const q=a.query.toLocaleLowerCase(),out=[];for(const x of allLists())for(const r of safe(()=>x.l.reminders(),[])){const v=row(r,x.l);if(a.completed!==undefined&&v.completed!==a.completed)continue;if((v.name+' '+v.body).toLocaleLowerCase().includes(q)){out.push(v);if(out.length>=(a.limit||50))return JSON.stringify({reminders:out})}}return JSON.stringify({reminders:out});`,a);if(name==="get_reminder")return jxa(`const x=reminderById(a.reminderId);return JSON.stringify(row(x.r,x.list));`,a);if(name==="create_reminder")return jxa(`const l=listById(a.listId),r=app.Reminder({name:a.title,body:a.notes||''});l.reminders.push(r);if(a.priority!==undefined)r.priority=a.priority;if(a.flagged!==undefined)r.flagged=a.flagged;return JSON.stringify(row(r,l));`,a);if(name==="update_reminder")return jxa(`const x=reminderById(a.reminderId),r=x.r;if(a.title===undefined&&a.notes===undefined&&a.priority===undefined&&a.flagged===undefined)throw Error('Provide a field to update');if(a.title!==undefined)r.name=a.title;if(a.notes!==undefined)r.body=a.notes;if(a.priority!==undefined)r.priority=a.priority;if(a.flagged!==undefined)r.flagged=a.flagged;return JSON.stringify(row(r,x.list));`,a);if(name==="set_completed")return jxa(`const x=reminderById(a.reminderId);x.r.completed=a.completed;return JSON.stringify(row(x.r,x.list));`,a);if(name==="delete_reminder")return jxa(`const x=reminderById(a.reminderId);app.delete(x.r);return JSON.stringify({deleted:true,reminderId:a.reminderId});`,a);throw Error("This operation is not exposed.")}export function createAppleRemindersServer(){const server=new Server({name:"zortex-apple-reminders",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:appleRemindersTools}));server.setRequestHandler("tools/call",async request=>{try{const value=await call(request.params.name,request.params.arguments??{});return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){return{content:[{type:"text",text:String(error.message).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createAppleRemindersServer(),{onerror:()=>process.stderr.write("Apple Reminders MCP operation failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{accessSync,constants}from"node:fs";import{mkdir,mkdtemp,rename,rm,stat}from"node:fs/promises";import{createConnection}from"node:net";import{homedir}from"node:os";import{dirname,join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{promisify}from"node:util";export const cuaVersion="0.28.2";const releases={arm64:["arm64","818ddefa0fa8ba2ec9cba837c7aa634a4b064221c748752cf49c5b08e2c94e8c"],x64:["x86_64","9e00cc92480a8f3d32bbcb7cb45cbc42293b7bd13c1808f5047f1f73a8b64f24"]};const invoke=promisify(execFile);const bundle="CuaDriver.app";const archiveLimit=8e7;const managedApp=join(homedir(),"Applications","Zortex",bundle);const appLocations=[managedApp,"/Applications/"+bundle,join(homedir(),"Applications",bundle)];const executable=app=>join(app,"Contents","MacOS","cua-driver");
|
|
1
|
+
import{execFile}from"node:child_process";import{createHash}from"node:crypto";import{accessSync,constants,statSync}from"node:fs";import{mkdir,mkdtemp,rename,rm,stat}from"node:fs/promises";import{createConnection}from"node:net";import{homedir,userInfo}from"node:os";import{dirname,join}from"node:path";import{setTimeout as delay}from"node:timers/promises";import{promisify}from"node:util";export const cuaVersion="0.28.2";const releases={arm64:["arm64","818ddefa0fa8ba2ec9cba837c7aa634a4b064221c748752cf49c5b08e2c94e8c"],x64:["x86_64","9e00cc92480a8f3d32bbcb7cb45cbc42293b7bd13c1808f5047f1f73a8b64f24"]};const invoke=promisify(execFile);const bundle="CuaDriver.app";const archiveLimit=8e7;const managedApp=join(homedir(),"Applications","Zortex",bundle);const appLocations=[...new Set([managedApp,"/Applications/"+bundle,join(homedir(),"Applications",bundle),join(loginHome(),"Applications","Zortex",bundle),join(loginHome(),"Applications",bundle)])];const executable=app=>join(app,"Contents","MacOS","cua-driver");const socketAt=home=>join(home,"Library","Caches","cua-driver","cua-driver.sock");function loginHome(){try{return userInfo().homedir}catch{return homedir()}}function isSocket(path){try{return statSync(path).isSocket()}catch{return false}}export function resolveCuaSocket(options={}){if((options.platform??process.platform)!=="darwin")return void 0;const override=(options.env??process.env).ZORTEX_CUA_SOCKET?.trim();if(override)return override;const homes=[options.home??homedir(),options.loginHome??loginHome()];const candidates=[...new Set(homes.map(socketAt))];return candidates.find(options.isSocket??isSocket)??socketAt(homes[1])}export let cuaSocket=resolveCuaSocket();function installed(app){try{accessSync(executable(app),constants.X_OK);return true}catch{return false}}export function macCuaApp(){return cuaSocket&&appLocations.find(installed)}export function cuaCommand(){const app=macCuaApp();return app?executable(app):"cua-driver"}async function run(command,args,timeout=15e3){return invoke(command,args,{timeout,maxBuffer:64*1024,windowsHide:true})}async function install(driverArch,sha256){const parent=dirname(managedApp);await mkdir(parent,{recursive:true});const stage=await mkdtemp(join(parent,".cua-driver-"));try{const asset=`cua-driver-rs-${cuaVersion}-darwin-${driverArch}`;const url=`https://github.com/trycua/cua/releases/download/cua-driver-rs-v${cuaVersion}/${asset}.tar.gz`;const{stdout:archive}=await invoke("/usr/bin/curl",["--disable","--fail","--silent","--show-error","--location","--proto","=https","--proto-redir","=https","--max-filesize",String(archiveLimit),url],{encoding:"buffer",timeout:12e4,maxBuffer:archiveLimit});if(createHash("sha256").update(archive).digest("hex")!==sha256)throw Error("The CUA Driver download failed its checksum.");const extraction=invoke("/usr/bin/tar",["-xzf","-","-C",stage,"--strip-components","1",`${asset}/${bundle}`],{timeout:3e4,maxBuffer:64*1024});extraction.child.stdin?.on("error",()=>{});extraction.child.stdin?.end(archive);await extraction;const app=join(stage,bundle);await run("/usr/bin/codesign",["--verify","--deep","--strict",app]);try{await rename(app,managedApp)}catch(error){if(!installed(managedApp))throw error}return managedApp}finally{await rm(stage,{recursive:true,force:true})}}async function serviceRunning(){cuaSocket=resolveCuaSocket();const socket=cuaSocket;if(!socket||!(await stat(socket).catch(()=>void 0))?.isSocket())return false;return new Promise(resolve=>{const client=createConnection(socket);const finish=connected=>{client.destroy();resolve(connected)};client.setTimeout(400,()=>finish(false));client.once("error",()=>finish(false));client.once("connect",()=>finish(true))})}let starting;async function startApp(app){if(await serviceRunning())return true;await run("/usr/bin/open",["-n","-g","-a",app,"--args","serve","--no-overlay","--no-permissions-gate"]);for(let attempt=0;attempt<30;attempt++){if(await serviceRunning())return true;await delay(200)}return false}function start(app){return starting??=startApp(app).finally(()=>{starting=void 0})}function managedCuaBootDelayMs(env=process.env){const value=env.ZORTEX_MANAGED_CUA_BOOT_DELAY_MS?.trim();const raw=value?Number(value):NaN;return Number.isFinite(raw)&&raw>=0&&raw<=3e4?Math.floor(raw):2500}export async function startManagedCua(options={}){const env=options.env??process.env;if(options.signal?.aborted)return;if(/^(1|true|yes|on)$/i.test((env.ZORTEX_DISABLE_AUTO_CUA??"").trim()))return;const app=macCuaApp();if(!app)return;const bootDelay=options.immediate?0:managedCuaBootDelayMs(env);if(bootDelay>0){try{await delay(bootDelay,void 0,{ref:false,...options.signal?{signal:options.signal}:{}})}catch(error){if(options.signal?.aborted)return;throw error}}if(options.signal?.aborted)return;if(installed(app))await start(app)}export async function setupCua({grantPermissions=false}={}){const release=releases[process.arch];if(!cuaSocket||!release)return{state:"unsupported-platform"};let app;try{app=macCuaApp()??await install(release[0],release[1])}catch(error){const failure=error;if(failure.code==="ENOSPC"||failure.stderr?.includes("No space left on device")){return{state:"install-failed",reason:"disk-full",next:"Free disk space, then retry indra setup computer-use."}}return{state:"install-failed",next:"Retry indra setup computer-use to download and verify CUA Driver."}}try{if(grantPermissions)await run(executable(app),["permissions","grant"],12e4);if(await start(app)){const{stdout}=await run(executable(app),["permissions","status","--json"]);const permissions=JSON.parse(stdout);if(permissions.accessibility&&permissions.screen_recording&&permissions.screen_recording_capturable!==false){return{state:"installed",permissions}}return{state:"installed",permissions,next:"Run indra setup computer-use --grant-permissions to finish macOS access."}}}catch{}return{state:"installed",permissions:"unverified",next:"Run indra setup computer-use --grant-permissions to verify macOS access."}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdir,readdir,realpath}from"node:fs/promises";import{dirname,isAbsolute,join}from"node:path";import{isDeepStrictEqual}from"node:util";import{createShallowProvider}from"./shallow.js";import{publicDataSourceIds}from"./public-data/catalog.js";import{withLoopbackTls}from"./loopback-tls.js";import{firstBatch,sentry}from"./sources.js";import{additionalSources}from"./additional-sources.js";import{preparedWork,preparedWorkSourceIds,createPreparedWorkSource}from"./prepared-work.js";import{preparedLocalSourceIds,createPreparedLocalSource,fastmail}from"./prepared-local.js";import{preparedServiceSourceIds,createPreparedServiceSource,createImmichFieldsSource,createLarkFieldsSource,readwise,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark}from"./prepared-services.js";import{preparedGraphSourceIds,createPreparedGraphSource,graphSessionSourceIds,createGraphSessionSource}from"./prepared-graph.js";import{preparedWorkStdioSourceIds,createGhostFieldsSource,createZendeskFieldsSource,createZendeskOAuthSource,validateZendeskOAuthOptions}from"./prepared-work-stdio.js";import{preparedExistingSourceIds,createPreparedExistingSource}from"./prepared-existing.js";import{preparedDingTalkSourceIds,createPreparedDingTalkSource}from"./prepared-dingtalk.js";import{preparedDiscordSourceIds,createPreparedDiscordSource}from"./prepared-discord.js";import{preparedTelegramSourceIds,createPreparedTelegramSource}from"./prepared-telegram.js";import{createPreparedWordPressSource}from"./prepared-wordpress.js";import{prepareConfiguration,validateLevel1Selection}from"./provisioning.js";import{replaceSettings,updateSettings,withSettingsReadLock,withSettingsStartupLock,recoverInterruptedJoplinSettings}from"./settings-transaction.js";import{fullActionCatalog}from"./action-policy.js";import{deferredSource}from"./deferred-box.js";import{attachComputerFiles}from"./computer-files.js";export function level1Catalog(specs=firstBatch){return specs.map(spec=>{if(spec.server.transport==="http"){const url=new URL(spec.server.url),local=["127.0.0.1","[::1]"].includes(url.hostname);return{source:spec.source,execution:{kind:local?"local-http-mcp":"hosted-mcp",url:url.href},licenseMode:local?"open-source":"hosted"}}if(spec.server.command==="npx"&&spec.origin.package&&spec.server.args.includes(spec.origin.package)&&/@\d+\.\d+\.\d+$/.test(spec.origin.package))return{source:spec.source,execution:{kind:"npm-stdio",package:spec.origin.package,command:"npx",args:[...spec.server.args]},licenseMode:"open-source"};if(spec.server.command==="uvx"&&spec.origin.package&&spec.server.args.includes(spec.origin.package)&&/==\d+\.\d+\.\d+$/.test(spec.origin.package))return{source:spec.source,execution:{kind:"python-stdio",package:spec.origin.package,command:"uvx",args:[...spec.server.args]},licenseMode:"open-source"};if(spec.origin.artifact&&/@\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/.test(spec.origin.artifact))return{source:spec.source,execution:{kind:"local-executable",artifact:spec.origin.artifact,command:spec.server.command,args:[...spec.server.args]},licenseMode:"open-source"};throw Error(`${spec.source} has no exact executable artifact contract.`)})}export{createShallowProvider,toolRow,setLoginPoll,proxyEnv}from"./shallow.js";export{firstBatch,onPath,stripe,calendly,openrouter,cloudflare,posthog,notionL1,github,gitlab,jira,confluence,linear,asana,clickup,todoist,ticktick,microsoftTodo,appleNotes,appleReminders,appleMusic,sentry,shopify,reddit,spotify,tiktok,notebooklm,cua}from"./sources.js";export{additionalSources,appstore,rednote}from"./additional-sources.js";export{publicDataSourceIds}from"./public-data/catalog.js";export{preparedWork}from"./prepared-work.js";export{preparedWorkSourceIds,createPreparedWorkSource}from"./prepared-work.js";export{createGhostFieldsSource,createZendeskFieldsSource,createZendeskOAuthSource}from"./prepared-work-stdio.js";export{preparedLocalSourceIds,createPreparedLocalSource,preparedLocalRootsAudience,preparedLocalNativeSelection,fastmail}from"./prepared-local.js";export{prepareMacAptOptions,createPreparedMacAptSource}from"./prepared-macapt.js";export{preparedServiceSourceIds,createPreparedServiceSource,createImmichFieldsSource,createLarkFieldsSource,readwise,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark}from"./prepared-services.js";export{preparedGraphSourceIds,createPreparedGraphSource}from"./prepared-graph.js";export{preparedExistingSourceIds,createPreparedExistingSource}from"./prepared-existing.js";export{preparedDingTalkSourceIds,createPreparedDingTalkSource}from"./prepared-dingtalk.js";export{preparedDiscordSourceIds,createPreparedDiscordSource,preparedDiscordAudience}from"./prepared-discord.js";export{preparedTelegramSourceIds,createPreparedTelegramSource,preparedTelegramAudience}from"./prepared-telegram.js";export{createPreparedWordPressSource}from"./prepared-wordpress.js";export{reviewedToolSchemaHash}from"./custodied.js";export const name="zortex-connector-level1",inject=["zortexConnectorHub","zortexConnectorEnrollment","zortexVaultStore","zortexConnectorHttp"];const runtimeSources=new Set([...preparedGraphSourceIds,...preparedWorkStdioSourceIds]);function deploymentOptions(source,options,deployment){return deployment.runtimeDirectory&&runtimeSources.has(source)&&options.runtimeDirectory===void 0?{...options,runtimeDirectory:join(deployment.runtimeDirectory,source)}:options}async function prepareRuntimeDirectories(deployment,sources){if(deployment.runtimeDirectory===void 0)return{};if(typeof deployment.runtimeDirectory!=="string"||!isAbsolute(deployment.runtimeDirectory))throw Error("Level 1 runtime directory must be an absolute product-owned path.");await mkdir(deployment.runtimeDirectory,{recursive:true,mode:448});const runtimeDirectory=await realpath(deployment.runtimeDirectory);for(const source of sources)if(runtimeSources.has(source))await mkdir(join(runtimeDirectory,source),{recursive:true,mode:448});for(const source of sources)if(graphSessionSourceIds.includes(source))await mkdir(join(runtimeDirectory,"server-sessions",source),{recursive:true,mode:448});return{runtimeDirectory}}const preparedFactories=new Map([...preparedWorkSourceIds.map(source=>[source,source==="wordpress"?createConfiguredWordPressSource:source==="ghost"||source==="zendesk"?createConfiguredWorkStdioSource:createPreparedWorkSource]),...preparedLocalSourceIds.map(source=>[source,createPreparedLocalSource]),...preparedServiceSourceIds.map(source=>[source,createPreparedServiceSource]),...preparedGraphSourceIds.map(source=>[source,createConfiguredGraphSource]),...preparedExistingSourceIds.map(source=>[source,createPreparedExistingSource]),...preparedDingTalkSourceIds.map(source=>[source,createPreparedDingTalkSource]),...preparedDiscordSourceIds.map(source=>[source,createPreparedDiscordSource]),...preparedTelegramSourceIds.map(source=>[source,createPreparedTelegramSource])]);function createConfiguredWordPressSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;return mode&&"value"in mode&&mode.value==="self-hosted"?createPreparedWordPressSource(source,options):createPreparedWorkSource(source,options,policy)}function createConfiguredGraphSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;return mode&&"value"in mode&&mode.value==="server-session"?createGraphSessionSource(source,options,policy):createPreparedGraphSource(source,options,policy)}function createConfiguredWorkStdioSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;if(source==="zendesk"&&mode&&"value"in mode&&mode.value==="oauth")return createZendeskOAuthSource(options,policy);return mode&&"value"in mode&&mode.value==="fields"?(source==="ghost"?createGhostFieldsSource:createZendeskFieldsSource)(options,policy):createPreparedWorkSource(source,options,policy)}export function configuredLevel1Sources(config,deployment={}){return configuredLevel1SourcesInternal(config,deployment,false)}function configuredLevel1SourcesInternal(config,deployment,settingsValidation){const declared=[...firstBatch,sentry,readwise,fastmail,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark,...preparedWork,...additionalSources].filter((spec,index,all)=>all.findIndex(item=>item.source===spec.source)===index),selection=config.sources;if(selection!==void 0&&(!Array.isArray(selection)||new Set(selection).size!==selection.length||selection.some(source=>typeof source!=="string"||!declared.some(spec=>spec.source===source)&&!preparedFactories.has(source))))throw Error("Invalid level 1 source selection: every source must be declared and unique.");const requested=config.requestedSources??selection;if(config.requestedSources!==void 0&&(!selection||!Array.isArray(requested)||new Set(requested).size!==requested.length||requested.some(source=>typeof source!=="string"||!declared.some(spec=>spec.source===source)&&!preparedFactories.has(source))||selection.some(source=>!requested.includes(source))))throw Error("Invalid requested level 1 source selection.");if(config.fullActions!==void 0&&(!Array.isArray(config.fullActions)||new Set(config.fullActions).size!==config.fullActions.length||config.fullActions.some(source=>!requested?.includes(source))))throw Error("Invalid level 1 action selection: select each source explicitly.");if(config.oauthSources!==void 0&&(!Array.isArray(config.oauthSources)||new Set(config.oauthSources).size!==config.oauthSources.length||config.oauthSources.some(source=>!requested?.includes(source))))throw Error("Invalid level 1 OAuth resource selection.");const options=config.prepared;if(options!==void 0){if(!options||typeof options!=="object"||Array.isArray(options)||![Object.prototype,null].includes(Object.getPrototypeOf(options)))throw Error("Invalid prepared level 1 source settings.");for(const key of Reflect.ownKeys(options)){if(typeof key!=="string"||!requested?.includes(key)||!preparedFactories.has(key))throw Error("Prepared settings require explicit selection of the matching source.");const descriptor=Object.getOwnPropertyDescriptor(options,key);if(!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid prepared level 1 source settings.")}}for(const[source,value]of Object.entries(options??{}))if(!selection?.includes(source))configuredLevel1SourcesInternal({sources:[source],prepared:{[source]:value},fullActions:config.fullActions?.includes(source)?[source]:[],oauthSources:config.oauthSources?.includes(source)?[source]:[]},deployment,settingsValidation);if(selection===void 0)return configuredLevel1SourcesInternal({...config,sources:firstBatch.map(spec=>spec.source)},deployment,settingsValidation);const ordered=[...declared.filter(spec=>selection.includes(spec.source)).map(spec=>spec.source),...selection.filter(source=>!declared.some(spec=>spec.source===source))];return ordered.filter(source=>{if(settingsValidation&&source==="zendesk"&&options&&Object.hasOwn(options,source)){const value=options[source];const mode=Object.getOwnPropertyDescriptor(value,"mode");if(mode&&"value"in mode&&mode.value==="oauth"&&!Object.hasOwn(value,"runtimeDirectory")){validateZendeskOAuthOptions(value);if(Object.hasOwn(value,"packageDirectory"))throw Error("Zendesk package directory requires a validated runtime.");return false}}return true}).map(source=>{const policy={fullActions:true};if(options&&Object.hasOwn(options,source))return preparedFactories.get(source)(source,deploymentOptions(source,options[source],deployment),policy);if(graphSessionSourceIds.includes(source)&&deployment.runtimeDirectory)return createGraphSessionSource(source,{runtimeDirectory:join(deployment.runtimeDirectory,"server-sessions",source)},policy);if(source==="ghost"&&deployment.runtimeDirectory)return createGhostFieldsSource({mode:"fields",runtimeDirectory:join(deployment.runtimeDirectory,source)},policy);if(source==="zendesk"&&deployment.runtimeDirectory)return createZendeskFieldsSource({mode:"fields",runtimeDirectory:join(deployment.runtimeDirectory,source)},policy);const fixed=declared.find(spec=>spec.source===source);if(fixed)return source==="immich"?createImmichFieldsSource(policy):source==="lark"?createLarkFieldsSource(policy):fixed;if(!options||!Object.hasOwn(options,source))throw Error(`Prepared source '${source}' needs explicit nonsecret provisioning references.`);return preparedFactories.get(source)(source,options[source],policy)}).map(spec=>{if(spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed){const writer=spec.source==="cloudflare"?"workers-kv-storage.write":spec.source==="raindrop"||spec.source==="readwise"?"write":void 0;if(writer)spec={...spec,auth:{...spec.auth,reviewed:{...spec.auth.reviewed,scopes:[...new Set([...spec.auth.reviewed.scopes,writer])]}}}}if(spec.source==="microsoft-todo"&&spec.auth.kind==="oauth-device"){const review=spec.auth.reviewed;spec={...spec,auth:{...spec.auth,reviewed:{...review,scopes:review.scopes.map(scope=>scope==="Tasks.Read"?"Tasks.ReadWrite":scope)}}}}if(config.oauthSources?.includes(spec.source)){const bearer=spec.server.transport==="http"?new URL(spec.server.url).protocol==="https:"&&(!spec.server.authorization||spec.server.authorization.kind==="bearer"):typeof spec.server.tokenEnv==="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(spec.server.tokenEnv);if(spec.auth.kind!=="custodied"||!["mcp-token","rest-token"].includes(spec.auth.credentialKind)||!bearer||new URL(spec.auth.issuer).protocol!=="https:"||spec.auth.requiredScopes.length>32)throw Error("Existing OAuth resources require an explicit bearer route or stdio token environment.");const hosted=spec.server.transport==="http"?spec.server.url:void 0,issuer=spec.auth.issuer,audience=spec.auth.audience;const box=spec.source==="box"&&issuer==="https://api.box.com"&&["https://mcp.box.com","https://mcp.box.com/"].includes(hosted??"")&&["https://mcp.box.com","https://mcp.box.com/"].includes(audience);const googleResource=spec.source==="google-contacts"?"https://people.googleapis.com/mcp/v1":spec.source==="google-chat"?"https://chatmcp.googleapis.com/mcp/v1":void 0;const google=googleResource!==void 0&&issuer==="https://accounts.google.com"&&hosted===googleResource&&audience===googleResource;const allowedOrigins=box?["https://api.box.com","https://account.box.com"]:google?["https://accounts.google.com","https://oauth2.googleapis.com"]:[new URL(issuer).origin];spec={...spec,auth:{...spec.auth,credentialKind:"oauth",oauth:{allowedOrigins}}}}const nativeRead=spec.auth.kind==="custodied"&&spec.auth.credentialKind==="local-no-secret"||["front","hubspot"].includes(spec.source)&&spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed?.registration?.kind==="pre-registered";return fullActionCatalog(withLoopbackTls(spec,deployment.runtimeDirectory),{fullActions:true},nativeRead)})}export function level1SourceIds(){return[...new Set([...firstBatch,sentry,readwise,fastmail,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark,...preparedWork,...additionalSources].map(spec=>spec.source).concat([...preparedFactories.keys()]))]}export function automaticLevel1SourceIds(){return level1SourceIds()}export async function prepareLevel1Configuration(vault,config={},deployment={}){const ids=level1SourceIds();validateLevel1Selection(config,ids);const sources=config.requestedSources??config.sources??automaticLevel1SourceIds();const runtime=await prepareRuntimeDirectories(deployment,sources);const plan=await prepareConfiguration(vault,{...config,sources},ids,value=>configuredLevel1Sources(value,runtime),[...preparedFactories.keys()]);if(runtime.runtimeDirectory){for(const source of plan.configuration.sources)if(graphSessionSourceIds.includes(source)&&!Object.hasOwn(plan.configuration.prepared,source))plan.configuration.prepared[source]={mode:"server-session",runtimeDirectory:join(runtime.runtimeDirectory,"server-sessions",source)}}if(runtime.runtimeDirectory){for(const source of["ghost","zendesk"])if(plan.configuration.sources.includes(source)&&!Object.hasOwn(plan.configuration.prepared,source))plan.configuration.prepared[source]={mode:"fields",runtimeDirectory:join(runtime.runtimeDirectory,source)}}for(const[source,options]of Object.entries(plan.configuration.prepared))plan.configuration.prepared[source]=deploymentOptions(source,options,runtime);return plan}function withoutDisabledJoplin(config){if(config.prepared?.joplin?.mode==="paired-plugin")return config;const without=items=>items?.filter(source=>source!=="joplin");const omit=values=>values&&Object.fromEntries(Object.entries(values).filter(([source])=>source!=="joplin"));return{...config,...config.sources?{sources:without(config.sources)}:{},...config.requestedSources?{requestedSources:without(config.requestedSources)}:{},...config.fullActions?{fullActions:without(config.fullActions)}:{},...config.oauthSources?{oauthSources:without(config.oauthSources)}:{},...config.prepared?{prepared:omit(config.prepared)}:{},...config.bindings?{bindings:omit(config.bindings)}:{}}}export function validateLevel1Configuration(value){validateLevel1Selection(value,level1SourceIds());configuredLevel1SourcesInternal(withoutDisabledJoplin(value),{},true)}export function readLevel1Configuration(file,options={}){return withSettingsReadLock(file,options.partial?value=>validateLevel1Selection(value,level1SourceIds()):validateLevel1Configuration,async current=>current)}export function writeLevel1Configuration(file,config){return replaceSettings(file,config,validateLevel1Configuration)}export function updateLevel1Configuration(file,update,options={}){return updateSettings(file,validateLevel1Configuration,update,options)}export function recoverInterruptedJoplinConfiguration(file,options={}){return recoverInterruptedJoplinSettings(file,validateLevel1Configuration,options)}function nativeFolderRegistration(spec,selection){const source=spec.source,auth=spec.auth,prepared=selection.prepared?.[source];if(auth.kind!=="custodied"||auth.credentialKind!=="local-no-secret"||!Array.isArray(prepared?.roots)||auth.requiredScopes.length!==1||auth.requiredScopes[0]!=="files.read")return void 0;return{prepared,auth,binding:selection.bindings?.[source],fullActions:true,oauth:selection.oauthSources?.includes(source)??false}}export async function apply(ctx,config={}){if(!config||typeof config!=="object"||Array.isArray(config)||Object.keys(config).some(k=>!["transport","sources","requestedSources","prepared","fullActions","oauthSources","bindings","wire","provisioningFile","autoProvision","runtimeDirectory"].includes(k))||config.sources!==void 0&&(!Array.isArray(config.sources)||config.sources.some(s=>typeof s!=="string"))||config.autoProvision!==void 0&&typeof config.autoProvision!=="boolean")throw new Error("Invalid level 1 connector settings.");const start=async(saved,pendingFirst)=>{if(pendingFirst&&config.sources?.includes("joplin")&&config.prepared?.joplin?.mode==="paired-plugin")throw Error("Level 1 setup requires interrupted-commit recovery.");const deployment=config.runtimeDirectory===void 0?{}:{runtimeDirectory:config.runtimeDirectory};const disabledJoplin=(config.sources??saved?.requestedSources??saved?.sources??[]).includes("joplin");const safeSaved=saved?withoutDisabledJoplin(saved):void 0;const automatic=config.sources===void 0&&(safeSaved?.requestedSources!==void 0||config.autoProvision&&safeSaved===void 0)?await prepareLevel1Configuration(ctx.zortexVaultStore,safeSaved??{},deployment):void 0;const selection=withoutDisabledJoplin(config.sources!==void 0?config:automatic?.configuration??safeSaved??config);const runtime=await prepareRuntimeDirectories(deployment,selection.sources??[]);const specs=configuredLevel1Sources(selection,runtime);const catalog=level1Catalog(specs);const publicConnections=runtime.runtimeDirectory&&join(runtime.runtimeDirectory,"enabled-public-sources");async function makeProvider(spec,providerSelection=selection){const rememberPublicConnection=publicConnections&&publicDataSourceIds.includes(spec.source)?async()=>{await mkdir(join(publicConnections,spec.source),{recursive:true,mode:448})}:void 0;const provider=createShallowProvider(spec,{metrics:()=>ctx.get("zortexTelemetry"),vault:ctx.zortexVaultStore,enrollment:ctx.zortexConnectorEnrollment,transport:config.transport??ctx.zortexConnectorHttp,...config.wire?{wire:config.wire}:{},...rememberPublicConnection?{rememberPublicConnection}:{}});const sqlite=ctx.get("zortexSqliteVault");if(spec.source==="computer-files"&&spec.auth.kind==="custodied"&&sqlite&&nativeFolderRegistration(spec,providerSelection)){const excludeRoots=[...config.provisioningFile?[dirname(config.provisioningFile)]:[],...runtime.runtimeDirectory?[runtime.runtimeDirectory]:[]];return attachComputerFiles(provider,{vault:ctx.zortexVaultStore,sqlite,auth:spec.auth,selection:providerSelection,...config.sources===void 0&&config.provisioningFile?{settingsFile:config.provisioningFile}:{},excludeRoots})}return{provider,files:void 0}}const preparedProviders=await Promise.all(specs.map(spec=>makeProvider(spec)));const providers=preparedProviders.map(row=>row.provider);const loadedFolders=new Map(specs.map(spec=>[spec.source,nativeFolderRegistration(spec,selection)]));const withdraws=providers.map(p=>ctx.zortexConnectorHub.register(p));const computerFiles=preparedProviders.find(row=>row.files)?.files;if(computerFiles)ctx.reflect.provide("zortexComputerFiles",computerFiles);const deferred=new Map;if(disabledJoplin&&!ctx.zortexConnectorHub.hasSource?.("joplin")){const placeholder=deferredSource("joplin");withdraws.push(ctx.zortexConnectorHub.register(placeholder));deferred.set("joplin",placeholder)}if(automatic&&ctx.zortexConnectorHub.hasSource){const candidates=new Set(automatic.pending.map(item=>item.source));for(const source of candidates)if(preparedFactories.has(source)&&!ctx.zortexConnectorHub.hasSource(source)){const placeholder=deferredSource(source);withdraws.push(ctx.zortexConnectorHub.register(placeholder));deferred.set(source,placeholder)}}const sources=providers.map(p=>p.info.source),pending=automatic?.pending??[];let disposed=false,activationQueue=Promise.resolve();const activate=source=>{const work=activationQueue.then(async()=>{if(disposed)return{status:"restart-required",reason:"plugin-disposed"};if(config.sources!==void 0)return{status:"restart-required",reason:"inline-selection"};if(!config.provisioningFile)return{status:"restart-required",reason:"no-settings-file"};const loadedFolder=loadedFolders.get(source);if(!loadedFolder&&providers.some(p=>p.info.source===source))return{status:"restart-required",reason:"provider-already-active"};if(!preparedFactories.has(source))return{status:"unavailable",reason:"unsupported-source"};if(!ctx.zortexConnectorHub.hasSource)return{status:"restart-required",reason:"registry-inspection-unavailable"};try{return await withSettingsReadLock(config.provisioningFile,validateLevel1Configuration,async saved2=>{if(disposed)return{status:"restart-required",reason:"plugin-disposed"};if(!saved2?.sources?.includes(source))return{status:"unavailable",reason:"source-not-configured"};const placeholder=deferred.get(source);if(placeholder&&!ctx.zortexConnectorHub.replaceDeferred)return{status:"restart-required",reason:"deferred-upgrade-unavailable"};if(!placeholder&&!loadedFolder&&ctx.zortexConnectorHub.hasSource(source))return{status:"restart-required",reason:"provider-already-active"};const single={sources:[source],requestedSources:[source],...saved2.prepared?.[source]?{prepared:{[source]:saved2.prepared[source]}}:{},...saved2.fullActions?{fullActions:saved2.fullActions.includes(source)?[source]:[]}:{},...saved2.oauthSources?{oauthSources:saved2.oauthSources.includes(source)?[source]:[]}:{},...saved2.bindings?.[source]?{bindings:{[source]:saved2.bindings[source]}}:{}};const plan=await prepareLevel1Configuration(ctx.zortexVaultStore,single,deployment);if(disposed)return{status:"restart-required",reason:"plugin-disposed"};const denied=plan.pending.find(item=>item.source===source);if(denied){for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);pending.push(denied);return{status:"unavailable",reason:denied.reason}}if(!plan.configuration.sources.includes(source))return{status:"unavailable",reason:"source-not-configured"};const runtime2=await prepareRuntimeDirectories(deployment,[source]);if(disposed)return{status:"restart-required",reason:"plugin-disposed"};const spec=configuredLevel1Sources(plan.configuration,runtime2).find(item=>item.source===source);if(!spec)return{status:"unavailable",reason:"source-not-configured"};if(loadedFolder){if(!ctx.zortexConnectorHub.hasSource(source)||!isDeepStrictEqual(loadedFolder,nativeFolderRegistration(spec,plan.configuration)))return{status:"restart-required",reason:"provider-already-active"};for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);return{status:"activated"}}const entry=level1Catalog([spec])[0];if(!placeholder&&ctx.zortexConnectorHub.hasSource(source))return{status:"restart-required",reason:"provider-already-active"};const{provider,files}=await makeProvider(spec,plan.configuration);try{const withdraw=placeholder?ctx.zortexConnectorHub.replaceDeferred(placeholder,provider):ctx.zortexConnectorHub.register(provider);if(!withdraw){await provider.close();return{status:"restart-required",reason:"deferred-provider-changed"}}if(placeholder)deferred.delete(source);loadedFolders.set(source,nativeFolderRegistration(spec,plan.configuration));withdraws.push(withdraw);providers.push(provider);sources.push(source);catalog.push(entry);if(files)ctx.reflect.provide("zortexComputerFiles",files);for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);return{status:"activated"}}catch{await provider.close();return{status:"restart-required",reason:"registration-failed"}}})}catch{return{status:"restart-required",reason:"settings-unavailable"}}});activationQueue=work.then(()=>{},()=>{});return work};if(publicConnections){const entries=await readdir(publicConnections,{withFileTypes:true}).catch(error=>{if(["ENOENT","EACCES","EPERM","ENOTDIR"].includes(error.code??""))return[];throw error});const enabled=new Set(entries.filter(entry=>entry.isDirectory()).map(entry=>entry.name));const restore=providers.filter(p=>enabled.has(p.info.source)&&publicDataSourceIds.includes(p.info.source));for(let offset=0;offset<restore.length;offset+=4){await Promise.all(restore.slice(offset,offset+4).map(p=>p.check?.({signal:AbortSignal.timeout(15e3)})))}}ctx.reflect.provide("zortexLevel1Connectors",{sources,catalog,pending,provider:source=>providers.find(p=>p.info.source===source),activate});const owner=ctx;owner.effect(()=>async()=>{disposed=true;await activationQueue;for(const w of withdraws)w();await Promise.allSettled(providers.map(p=>p.close()))},"connector-level1:sources")};if(config.provisioningFile)await withSettingsStartupLock(config.provisioningFile,validateLevel1Configuration,start);else await start(void 0,false)}export{createJoplinPairing,readPairedJoplinBridge}from"./joplin-pairing.js";
|
|
1
|
+
import{isBundledAppleSource}from"./prepared-apple-native.js";import{mkdir,readdir,realpath}from"node:fs/promises";import{dirname,isAbsolute,join}from"node:path";import{isDeepStrictEqual}from"node:util";import{createShallowProvider}from"./shallow.js";import{publicDataSourceIds}from"./public-data/catalog.js";import{withLoopbackTls}from"./loopback-tls.js";import{firstBatch,sentry}from"./sources.js";import{additionalSources}from"./additional-sources.js";import{preparedWork,preparedWorkSourceIds,createPreparedWorkSource}from"./prepared-work.js";import{preparedLocalSourceIds,createPreparedLocalSource,fastmail}from"./prepared-local.js";import{preparedServiceSourceIds,createPreparedServiceSource,createImmichFieldsSource,createLarkFieldsSource,readwise,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark}from"./prepared-services.js";import{preparedGraphSourceIds,createPreparedGraphSource,graphSessionSourceIds,createGraphSessionSource}from"./prepared-graph.js";import{preparedWorkStdioSourceIds,createGhostFieldsSource,createZendeskFieldsSource,createZendeskOAuthSource,validateZendeskOAuthOptions}from"./prepared-work-stdio.js";import{preparedExistingSourceIds,createPreparedExistingSource}from"./prepared-existing.js";import{preparedDingTalkSourceIds,createPreparedDingTalkSource}from"./prepared-dingtalk.js";import{preparedDiscordSourceIds,createPreparedDiscordSource}from"./prepared-discord.js";import{preparedTelegramSourceIds,createPreparedTelegramSource}from"./prepared-telegram.js";import{createPreparedWordPressSource}from"./prepared-wordpress.js";import{prepareConfiguration,validateLevel1Selection}from"./provisioning.js";import{replaceSettings,updateSettings,withSettingsReadLock,withSettingsStartupLock,recoverInterruptedJoplinSettings}from"./settings-transaction.js";import{fullActionCatalog}from"./action-policy.js";import{deferredSource}from"./deferred-box.js";import{attachComputerFiles}from"./computer-files.js";export function level1Catalog(specs=firstBatch){return specs.map(spec=>{if(spec.server.transport==="http"){const url=new URL(spec.server.url),local=["127.0.0.1","[::1]"].includes(url.hostname);return{source:spec.source,execution:{kind:local?"local-http-mcp":"hosted-mcp",url:url.href},licenseMode:local?"open-source":"hosted"}}if(spec.server.command==="npx"&&spec.origin.package&&spec.server.args.includes(spec.origin.package)&&/@\d+\.\d+\.\d+$/.test(spec.origin.package))return{source:spec.source,execution:{kind:"npm-stdio",package:spec.origin.package,command:"npx",args:[...spec.server.args]},licenseMode:"open-source"};if(spec.server.command==="uvx"&&spec.origin.package&&spec.server.args.includes(spec.origin.package)&&/==\d+\.\d+\.\d+$/.test(spec.origin.package))return{source:spec.source,execution:{kind:"python-stdio",package:spec.origin.package,command:"uvx",args:[...spec.server.args]},licenseMode:"open-source"};if(spec.origin.artifact&&/@\d+\.\d+\.\d+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/.test(spec.origin.artifact))return{source:spec.source,execution:{kind:"local-executable",artifact:spec.origin.artifact,command:spec.server.command,args:[...spec.server.args]},licenseMode:"open-source"};throw Error(`${spec.source} has no exact executable artifact contract.`)})}export{createShallowProvider,toolRow,setLoginPoll,proxyEnv}from"./shallow.js";export{firstBatch,onPath,stripe,calendly,openrouter,cloudflare,posthog,notionL1,github,gitlab,jira,confluence,linear,asana,clickup,todoist,ticktick,microsoftTodo,appleNotes,appleReminders,appleMusic,sentry,shopify,reddit,spotify,tiktok,notebooklm,cua}from"./sources.js";export{additionalSources,appstore,rednote}from"./additional-sources.js";export{publicDataSourceIds}from"./public-data/catalog.js";export{preparedWork}from"./prepared-work.js";export{preparedWorkSourceIds,createPreparedWorkSource}from"./prepared-work.js";export{createGhostFieldsSource,createZendeskFieldsSource,createZendeskOAuthSource}from"./prepared-work-stdio.js";export{preparedLocalSourceIds,createPreparedLocalSource,preparedLocalRootsAudience,preparedLocalNativeSelection,fastmail}from"./prepared-local.js";export{prepareMacAptOptions,createPreparedMacAptSource}from"./prepared-macapt.js";export{preparedServiceSourceIds,createPreparedServiceSource,createImmichFieldsSource,createLarkFieldsSource,readwise,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark}from"./prepared-services.js";export{preparedGraphSourceIds,createPreparedGraphSource}from"./prepared-graph.js";export{preparedExistingSourceIds,createPreparedExistingSource}from"./prepared-existing.js";export{preparedDingTalkSourceIds,createPreparedDingTalkSource}from"./prepared-dingtalk.js";export{preparedDiscordSourceIds,createPreparedDiscordSource,preparedDiscordAudience}from"./prepared-discord.js";export{preparedTelegramSourceIds,createPreparedTelegramSource,preparedTelegramAudience}from"./prepared-telegram.js";export{createPreparedWordPressSource}from"./prepared-wordpress.js";export{reviewedToolSchemaHash}from"./custodied.js";export const name="zortex-connector-level1",inject=["zortexConnectorHub","zortexConnectorEnrollment","zortexVaultStore","zortexConnectorHttp"];const runtimeSources=new Set([...preparedGraphSourceIds,...preparedWorkStdioSourceIds]);function deploymentOptions(source,options,deployment){return deployment.runtimeDirectory&&runtimeSources.has(source)&&options.runtimeDirectory===void 0?{...options,runtimeDirectory:join(deployment.runtimeDirectory,source)}:options}async function prepareRuntimeDirectories(deployment,sources){if(deployment.runtimeDirectory===void 0)return{};if(typeof deployment.runtimeDirectory!=="string"||!isAbsolute(deployment.runtimeDirectory))throw Error("Level 1 runtime directory must be an absolute product-owned path.");await mkdir(deployment.runtimeDirectory,{recursive:true,mode:448});const runtimeDirectory=await realpath(deployment.runtimeDirectory);for(const source of sources)if(runtimeSources.has(source))await mkdir(join(runtimeDirectory,source),{recursive:true,mode:448});for(const source of sources)if(graphSessionSourceIds.includes(source))await mkdir(join(runtimeDirectory,"server-sessions",source),{recursive:true,mode:448});return{runtimeDirectory}}const preparedFactories=new Map([...preparedWorkSourceIds.map(source=>[source,source==="wordpress"?createConfiguredWordPressSource:source==="ghost"||source==="zendesk"?createConfiguredWorkStdioSource:createPreparedWorkSource]),...preparedLocalSourceIds.map(source=>[source,createPreparedLocalSource]),...preparedServiceSourceIds.map(source=>[source,createPreparedServiceSource]),...preparedGraphSourceIds.map(source=>[source,createConfiguredGraphSource]),...preparedExistingSourceIds.map(source=>[source,createPreparedExistingSource]),...preparedDingTalkSourceIds.map(source=>[source,createPreparedDingTalkSource]),...preparedDiscordSourceIds.map(source=>[source,createPreparedDiscordSource]),...preparedTelegramSourceIds.map(source=>[source,createPreparedTelegramSource])]);function createConfiguredWordPressSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;return mode&&"value"in mode&&mode.value==="self-hosted"?createPreparedWordPressSource(source,options):createPreparedWorkSource(source,options,policy)}function createConfiguredGraphSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;return mode&&"value"in mode&&mode.value==="server-session"?createGraphSessionSource(source,options,policy):createPreparedGraphSource(source,options,policy)}function createConfiguredWorkStdioSource(source,options,policy={}){const mode=options&&typeof options==="object"?Object.getOwnPropertyDescriptor(options,"mode"):void 0;if(source==="zendesk"&&mode&&"value"in mode&&mode.value==="oauth")return createZendeskOAuthSource(options,policy);return mode&&"value"in mode&&mode.value==="fields"?(source==="ghost"?createGhostFieldsSource:createZendeskFieldsSource)(options,policy):createPreparedWorkSource(source,options,policy)}export function configuredLevel1Sources(config,deployment={}){return configuredLevel1SourcesInternal(config,deployment,false)}function configuredLevel1SourcesInternal(config,deployment,settingsValidation){const declared=[...firstBatch,sentry,readwise,fastmail,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark,...preparedWork,...additionalSources].filter((spec,index,all)=>all.findIndex(item=>item.source===spec.source)===index),selection=config.sources;if(selection!==void 0&&(!Array.isArray(selection)||new Set(selection).size!==selection.length||selection.some(source=>typeof source!=="string"||!declared.some(spec=>spec.source===source)&&!preparedFactories.has(source))))throw Error("Invalid level 1 source selection: every source must be declared and unique.");const requested=config.requestedSources??selection;if(config.requestedSources!==void 0&&(!selection||!Array.isArray(requested)||new Set(requested).size!==requested.length||requested.some(source=>typeof source!=="string"||!declared.some(spec=>spec.source===source)&&!preparedFactories.has(source))||selection.some(source=>!requested.includes(source))))throw Error("Invalid requested level 1 source selection.");if(config.fullActions!==void 0&&(!Array.isArray(config.fullActions)||new Set(config.fullActions).size!==config.fullActions.length||config.fullActions.some(source=>!requested?.includes(source))))throw Error("Invalid level 1 action selection: select each source explicitly.");if(config.oauthSources!==void 0&&(!Array.isArray(config.oauthSources)||new Set(config.oauthSources).size!==config.oauthSources.length||config.oauthSources.some(source=>!requested?.includes(source))))throw Error("Invalid level 1 OAuth resource selection.");const options=config.prepared;if(options!==void 0){if(!options||typeof options!=="object"||Array.isArray(options)||![Object.prototype,null].includes(Object.getPrototypeOf(options)))throw Error("Invalid prepared level 1 source settings.");for(const key of Reflect.ownKeys(options)){if(typeof key!=="string"||!requested?.includes(key)||!preparedFactories.has(key))throw Error("Prepared settings require explicit selection of the matching source.");const descriptor=Object.getOwnPropertyDescriptor(options,key);if(!descriptor.enumerable||!("value"in descriptor))throw Error("Invalid prepared level 1 source settings.")}}for(const[source,value]of Object.entries(options??{}))if(!selection?.includes(source))configuredLevel1SourcesInternal({sources:[source],prepared:{[source]:value},fullActions:config.fullActions?.includes(source)?[source]:[],oauthSources:config.oauthSources?.includes(source)?[source]:[]},deployment,settingsValidation);if(selection===void 0)return configuredLevel1SourcesInternal({...config,sources:firstBatch.map(spec=>spec.source)},deployment,settingsValidation);const ordered=[...declared.filter(spec=>selection.includes(spec.source)).map(spec=>spec.source),...selection.filter(source=>!declared.some(spec=>spec.source===source))];return ordered.filter(source=>{if(settingsValidation&&source==="zendesk"&&options&&Object.hasOwn(options,source)){const value=options[source];const mode=Object.getOwnPropertyDescriptor(value,"mode");if(mode&&"value"in mode&&mode.value==="oauth"&&!Object.hasOwn(value,"runtimeDirectory")){validateZendeskOAuthOptions(value);if(Object.hasOwn(value,"packageDirectory"))throw Error("Zendesk package directory requires a validated runtime.");return false}}return true}).map(source=>{const policy={fullActions:true};if(options&&Object.hasOwn(options,source))return preparedFactories.get(source)(source,deploymentOptions(source,options[source],deployment),policy);if(graphSessionSourceIds.includes(source)&&deployment.runtimeDirectory)return createGraphSessionSource(source,{runtimeDirectory:join(deployment.runtimeDirectory,"server-sessions",source)},policy);if(source==="ghost"&&deployment.runtimeDirectory)return createGhostFieldsSource({mode:"fields",runtimeDirectory:join(deployment.runtimeDirectory,source)},policy);if(source==="zendesk"&&deployment.runtimeDirectory)return createZendeskFieldsSource({mode:"fields",runtimeDirectory:join(deployment.runtimeDirectory,source)},policy);const fixed=declared.find(spec=>spec.source===source);if(fixed)return source==="immich"?createImmichFieldsSource(policy):source==="lark"?createLarkFieldsSource(policy):fixed;if(!options||!Object.hasOwn(options,source))throw Error(`Prepared source '${source}' needs explicit nonsecret provisioning references.`);return preparedFactories.get(source)(source,options[source],policy)}).map(spec=>{if(spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed){const writer=spec.source==="cloudflare"?"workers-kv-storage.write":spec.source==="raindrop"||spec.source==="readwise"?"write":void 0;if(writer)spec={...spec,auth:{...spec.auth,reviewed:{...spec.auth.reviewed,scopes:[...new Set([...spec.auth.reviewed.scopes,writer])]}}}}if(spec.source==="microsoft-todo"&&spec.auth.kind==="oauth-device"){const review=spec.auth.reviewed;spec={...spec,auth:{...spec.auth,reviewed:{...review,scopes:review.scopes.map(scope=>scope==="Tasks.Read"?"Tasks.ReadWrite":scope)}}}}if(config.oauthSources?.includes(spec.source)){const bearer=spec.server.transport==="http"?new URL(spec.server.url).protocol==="https:"&&(!spec.server.authorization||spec.server.authorization.kind==="bearer"):typeof spec.server.tokenEnv==="string"&&/^[A-Z][A-Z0-9_]{0,127}$/u.test(spec.server.tokenEnv);if(spec.auth.kind!=="custodied"||!["mcp-token","rest-token"].includes(spec.auth.credentialKind)||!bearer||new URL(spec.auth.issuer).protocol!=="https:"||spec.auth.requiredScopes.length>32)throw Error("Existing OAuth resources require an explicit bearer route or stdio token environment.");const hosted=spec.server.transport==="http"?spec.server.url:void 0,issuer=spec.auth.issuer,audience=spec.auth.audience;const box=spec.source==="box"&&issuer==="https://api.box.com"&&["https://mcp.box.com","https://mcp.box.com/"].includes(hosted??"")&&["https://mcp.box.com","https://mcp.box.com/"].includes(audience);const googleResource=spec.source==="google-contacts"?"https://people.googleapis.com/mcp/v1":spec.source==="google-chat"?"https://chatmcp.googleapis.com/mcp/v1":void 0;const google=googleResource!==void 0&&issuer==="https://accounts.google.com"&&hosted===googleResource&&audience===googleResource;const allowedOrigins=box?["https://api.box.com","https://account.box.com"]:google?["https://accounts.google.com","https://oauth2.googleapis.com"]:[new URL(issuer).origin];spec={...spec,auth:{...spec.auth,credentialKind:"oauth",oauth:{allowedOrigins}}}}const nativeRead=spec.auth.kind==="custodied"&&spec.auth.credentialKind==="local-no-secret"||["front","hubspot"].includes(spec.source)&&spec.auth.kind==="mcp-oauth"&&spec.auth.reviewed?.registration?.kind==="pre-registered";return fullActionCatalog(withLoopbackTls(spec,deployment.runtimeDirectory),{fullActions:true},nativeRead)})}export function level1SourceIds(){return[...new Set([...firstBatch,sentry,readwise,fastmail,raindrop,calcom,harvest,toggl,immich,karakeep,matrix,lark,...preparedWork,...additionalSources].map(spec=>spec.source).concat([...preparedFactories.keys()]))]}export function automaticLevel1SourceIds(){return level1SourceIds()}export async function prepareLevel1Configuration(vault,config={},deployment={}){const ids=level1SourceIds();validateLevel1Selection(config,ids);const sources=config.requestedSources??config.sources??automaticLevel1SourceIds();const runtime=await prepareRuntimeDirectories(deployment,sources);const plan=await prepareConfiguration(vault,{...config,sources},ids,value=>configuredLevel1Sources(value,runtime),[...preparedFactories.keys()],config.sources??[]);if(runtime.runtimeDirectory){for(const source of plan.configuration.sources)if(graphSessionSourceIds.includes(source)&&!Object.hasOwn(plan.configuration.prepared,source))plan.configuration.prepared[source]={mode:"server-session",runtimeDirectory:join(runtime.runtimeDirectory,"server-sessions",source)}}if(runtime.runtimeDirectory){for(const source of["ghost","zendesk"])if(plan.configuration.sources.includes(source)&&!Object.hasOwn(plan.configuration.prepared,source))plan.configuration.prepared[source]={mode:"fields",runtimeDirectory:join(runtime.runtimeDirectory,source)}}for(const[source,options]of Object.entries(plan.configuration.prepared))plan.configuration.prepared[source]=deploymentOptions(source,options,runtime);return plan}function withoutDisabledJoplin(config){if(config.prepared?.joplin?.mode==="paired-plugin")return config;const without=items=>items?.filter(source=>source!=="joplin");const omit=values=>values&&Object.fromEntries(Object.entries(values).filter(([source])=>source!=="joplin"));return{...config,...config.sources?{sources:without(config.sources)}:{},...config.requestedSources?{requestedSources:without(config.requestedSources)}:{},...config.fullActions?{fullActions:without(config.fullActions)}:{},...config.oauthSources?{oauthSources:without(config.oauthSources)}:{},...config.prepared?{prepared:omit(config.prepared)}:{},...config.bindings?{bindings:omit(config.bindings)}:{}}}export function validateLevel1Configuration(value){validateLevel1Selection(value,level1SourceIds());configuredLevel1SourcesInternal(withoutDisabledJoplin(value),{},true)}export function readLevel1Configuration(file,options={}){return withSettingsReadLock(file,options.partial?value=>validateLevel1Selection(value,level1SourceIds()):validateLevel1Configuration,async current=>current)}export function writeLevel1Configuration(file,config){return replaceSettings(file,config,validateLevel1Configuration)}export function updateLevel1Configuration(file,update,options={}){return updateSettings(file,validateLevel1Configuration,update,options)}export function recoverInterruptedJoplinConfiguration(file,options={}){return recoverInterruptedJoplinSettings(file,validateLevel1Configuration,options)}function nativeFolderRegistration(spec,selection){const source=spec.source,auth=spec.auth,prepared=selection.prepared?.[source];if(auth.kind!=="custodied"||auth.credentialKind!=="local-no-secret"||!prepared||!(source==="ollama"||isBundledAppleSource(source)&&prepared.executable===void 0)&&(!Array.isArray(prepared.roots)||auth.requiredScopes.length!==1||auth.requiredScopes[0]!=="files.read"))return void 0;return{prepared,auth,binding:selection.bindings?.[source],fullActions:true,oauth:selection.oauthSources?.includes(source)??false}}export async function apply(ctx,config={}){if(!config||typeof config!=="object"||Array.isArray(config)||Object.keys(config).some(k=>!["transport","sources","requestedSources","prepared","fullActions","oauthSources","bindings","wire","provisioningFile","autoProvision","runtimeDirectory"].includes(k))||config.sources!==void 0&&(!Array.isArray(config.sources)||config.sources.some(s=>typeof s!=="string"))||config.autoProvision!==void 0&&typeof config.autoProvision!=="boolean")throw new Error("Invalid level 1 connector settings.");const start=async(saved,pendingFirst)=>{if(pendingFirst&&config.sources?.includes("joplin")&&config.prepared?.joplin?.mode==="paired-plugin")throw Error("Level 1 setup requires interrupted-commit recovery.");const deployment=config.runtimeDirectory===void 0?{}:{runtimeDirectory:config.runtimeDirectory};const disabledJoplin=(config.sources??saved?.requestedSources??saved?.sources??[]).includes("joplin");const safeSaved=saved?withoutDisabledJoplin(saved):void 0;const automatic=config.sources===void 0&&(safeSaved?.requestedSources!==void 0||config.autoProvision&&safeSaved===void 0)?await prepareLevel1Configuration(ctx.zortexVaultStore,safeSaved??{},deployment):void 0;const selection=withoutDisabledJoplin(config.sources!==void 0?config:automatic?.configuration??safeSaved??config);const runtime=await prepareRuntimeDirectories(deployment,selection.sources??[]);const specs=configuredLevel1Sources(selection,runtime);const catalog=level1Catalog(specs);const publicConnections=runtime.runtimeDirectory&&join(runtime.runtimeDirectory,"enabled-public-sources");async function makeProvider(spec,providerSelection=selection){const rememberPublicConnection=publicConnections&&publicDataSourceIds.includes(spec.source)?async()=>{await mkdir(join(publicConnections,spec.source),{recursive:true,mode:448})}:void 0;const provider=createShallowProvider(spec,{metrics:()=>ctx.get("zortexTelemetry"),vault:ctx.zortexVaultStore,enrollment:ctx.zortexConnectorEnrollment,transport:config.transport??ctx.zortexConnectorHttp,...config.wire?{wire:config.wire}:{},...rememberPublicConnection?{rememberPublicConnection}:{}});const sqlite=ctx.get("zortexSqliteVault");if(spec.source==="computer-files"&&spec.auth.kind==="custodied"&&sqlite&&nativeFolderRegistration(spec,providerSelection)){const excludeRoots=[...config.provisioningFile?[dirname(config.provisioningFile)]:[],...runtime.runtimeDirectory?[runtime.runtimeDirectory]:[]];return attachComputerFiles(provider,{vault:ctx.zortexVaultStore,sqlite,auth:spec.auth,selection:providerSelection,...config.sources===void 0&&config.provisioningFile?{settingsFile:config.provisioningFile}:{},excludeRoots})}return{provider,files:void 0}}const preparedProviders=await Promise.all(specs.map(spec=>makeProvider(spec)));const providers=preparedProviders.map(row=>row.provider);const loadedFolders=new Map(specs.map(spec=>[spec.source,nativeFolderRegistration(spec,selection)]));const withdraws=providers.map(p=>ctx.zortexConnectorHub.register(p));const computerFiles=preparedProviders.find(row=>row.files)?.files;if(computerFiles)ctx.reflect.provide("zortexComputerFiles",computerFiles);const deferred=new Map;if(disabledJoplin&&!ctx.zortexConnectorHub.hasSource?.("joplin")){const placeholder=deferredSource("joplin");withdraws.push(ctx.zortexConnectorHub.register(placeholder));deferred.set("joplin",placeholder)}if(automatic&&ctx.zortexConnectorHub.hasSource){const candidates=new Set(automatic.pending.map(item=>item.source));for(const source of candidates)if(preparedFactories.has(source)&&!ctx.zortexConnectorHub.hasSource(source)){const placeholder=deferredSource(source);withdraws.push(ctx.zortexConnectorHub.register(placeholder));deferred.set(source,placeholder)}}const sources=providers.map(p=>p.info.source),pending=automatic?.pending??[];let disposed=false,activationQueue=Promise.resolve();const activate=source=>{const work=activationQueue.then(async()=>{if(disposed)return{status:"restart-required",reason:"plugin-disposed"};if(config.sources!==void 0)return{status:"restart-required",reason:"inline-selection"};if(!config.provisioningFile)return{status:"restart-required",reason:"no-settings-file"};const loadedFolder=loadedFolders.get(source);if(!loadedFolder&&providers.some(p=>p.info.source===source))return{status:"restart-required",reason:"provider-already-active"};if(!preparedFactories.has(source))return{status:"unavailable",reason:"unsupported-source"};if(!ctx.zortexConnectorHub.hasSource)return{status:"restart-required",reason:"registry-inspection-unavailable"};try{return await withSettingsReadLock(config.provisioningFile,validateLevel1Configuration,async saved2=>{if(disposed)return{status:"restart-required",reason:"plugin-disposed"};if(!saved2?.sources?.includes(source))return{status:"unavailable",reason:"source-not-configured"};const placeholder=deferred.get(source);if(placeholder&&!ctx.zortexConnectorHub.replaceDeferred)return{status:"restart-required",reason:"deferred-upgrade-unavailable"};if(!placeholder&&!loadedFolder&&ctx.zortexConnectorHub.hasSource(source))return{status:"restart-required",reason:"provider-already-active"};const single={sources:[source],requestedSources:[source],...saved2.prepared?.[source]?{prepared:{[source]:saved2.prepared[source]}}:{},...saved2.fullActions?{fullActions:saved2.fullActions.includes(source)?[source]:[]}:{},...saved2.oauthSources?{oauthSources:saved2.oauthSources.includes(source)?[source]:[]}:{},...saved2.bindings?.[source]?{bindings:{[source]:saved2.bindings[source]}}:{}};const plan=await prepareLevel1Configuration(ctx.zortexVaultStore,single,deployment);if(disposed)return{status:"restart-required",reason:"plugin-disposed"};const denied=plan.pending.find(item=>item.source===source);if(denied){for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);pending.push(denied);return{status:"unavailable",reason:denied.reason}}if(!plan.configuration.sources.includes(source))return{status:"unavailable",reason:"source-not-configured"};const runtime2=await prepareRuntimeDirectories(deployment,[source]);if(disposed)return{status:"restart-required",reason:"plugin-disposed"};const spec=configuredLevel1Sources(plan.configuration,runtime2).find(item=>item.source===source);if(!spec)return{status:"unavailable",reason:"source-not-configured"};if(loadedFolder){if(!ctx.zortexConnectorHub.hasSource(source)||!isDeepStrictEqual(loadedFolder,nativeFolderRegistration(spec,plan.configuration)))return{status:"restart-required",reason:"provider-already-active"};for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);return{status:"activated"}}const entry=level1Catalog([spec])[0];if(!placeholder&&ctx.zortexConnectorHub.hasSource(source))return{status:"restart-required",reason:"provider-already-active"};const{provider,files}=await makeProvider(spec,plan.configuration);try{const withdraw=placeholder?ctx.zortexConnectorHub.replaceDeferred(placeholder,provider):ctx.zortexConnectorHub.register(provider);if(!withdraw){await provider.close();return{status:"restart-required",reason:"deferred-provider-changed"}}if(placeholder)deferred.delete(source);loadedFolders.set(source,nativeFolderRegistration(spec,plan.configuration));withdraws.push(withdraw);providers.push(provider);sources.push(source);catalog.push(entry);if(files)ctx.reflect.provide("zortexComputerFiles",files);for(let i=pending.length-1;i>=0;i--)if(pending[i].source===source)pending.splice(i,1);return{status:"activated"}}catch{await provider.close();return{status:"restart-required",reason:"registration-failed"}}})}catch{return{status:"restart-required",reason:"settings-unavailable"}}});activationQueue=work.then(()=>{},()=>{});return work};if(publicConnections){const entries=await readdir(publicConnections,{withFileTypes:true}).catch(error=>{if(["ENOENT","EACCES","EPERM","ENOTDIR"].includes(error.code??""))return[];throw error});const enabled=new Set(entries.filter(entry=>entry.isDirectory()).map(entry=>entry.name));const restore=providers.filter(p=>enabled.has(p.info.source)&&publicDataSourceIds.includes(p.info.source));for(let offset=0;offset<restore.length;offset+=4){await Promise.all(restore.slice(offset,offset+4).map(p=>p.check?.({signal:AbortSignal.timeout(15e3)})))}}ctx.reflect.provide("zortexLevel1Connectors",{sources,catalog,pending,provider:source=>providers.find(p=>p.info.source===source),activate});const owner=ctx;owner.effect(()=>async()=>{disposed=true;await activationQueue;for(const w of withdraws)w();await Promise.allSettled(providers.map(p=>p.close()))},"connector-level1:sources")};if(config.provisioningFile)await withSettingsStartupLock(config.provisioningFile,validateLevel1Configuration,start);else await start(void 0,false)}export{createJoplinPairing,readPairedJoplinBridge}from"./joplin-pairing.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{NATIVE_CHILD_TIMEOUT,nativeProcessError}from"./apple-native-process.mjs";import{execFile}from"node:child_process";import{promisify}from"node:util";import{Server}from"@modelcontextprotocol/server";import{serveStdio}from"@modelcontextprotocol/server/stdio";const run=promisify(execFile);const tool={name:"list_contacts",description:"Read bounded contact names from the signed-in macOS Contacts store.",inputSchema:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:500}},required:[],additionalProperties:false},annotations:{readOnlyHint:true,destructiveHint:false,openWorldHint:false,idempotentHint:true}};export function createMacosContactsServer(){const server=new Server({name:"zortex-macos-contacts",version:"0.1.0"},{capabilities:{tools:{}}});server.setRequestHandler("tools/list",()=>({tools:[tool]}));server.setRequestHandler("tools/call",async request=>{try{if(process.platform!=="darwin"||request.params.name!==tool.name)throw Error("Contacts is available only on macOS.");const limit=request.params.arguments?.limit??100;if(!Number.isInteger(limit)||Number(limit)<1||Number(limit)>500)throw Error("Invalid contact limit.");const script=`(()=>{const app=Application('Contacts');const contacts=app.people().slice(0,${limit}).map(p=>({id:p.id(),name:p.name()}));return JSON.stringify({contacts});})()`;const{stdout}=await run("/usr/bin/osascript",["-l","JavaScript","-e",script],{timeout:NATIVE_CHILD_TIMEOUT,maxBuffer:1048576});const value=JSON.parse(stdout);return{content:[{type:"text",text:JSON.stringify(value)}],structuredContent:value}}catch(error){const value=error;return{content:[{type:"text",text:nativeProcessError({stderr:value.stderr,error:value}).slice(0,500)}],isError:true}}});return server}const handle=serveStdio(()=>createMacosContactsServer(),{onerror:()=>process.stderr.write("Contacts MCP read failed.\n")});await new Promise(done=>{process.stdin.once("end",()=>{void handle.close().finally(done)});process.once("SIGINT",()=>{void handle.close().finally(done)})});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fileURLToPath}from"node:url";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";import{reviewedToolSchemaHash}from"./custodied.js";const bundledServers={"apple-notes":new URL("./apple-notes-server.js",import.meta.url),"apple-reminders":new URL("./apple-reminders-server.js",import.meta.url),"apple-music":new URL("./apple-music-server.js",import.meta.url),"macos-contacts":new URL("./macos-contacts-server.js",import.meta.url)};export const bundledAppleSources=["apple-notes","apple-reminders","apple-music","macos-contacts"];export const isBundledAppleSource=source=>bundledAppleSources.includes(source);export function bundledAppleSelection(source){const scope={"apple-notes":"notes.read","apple-reminders":"reminders.read","apple-music":"music.read","macos-contacts":"contacts.read"}[source];return{options:{},audience:`indra-apple-runtime:${source}:bundled`,scope}}export function preparedAppleNative(source,auth){const nativeId={type:"string",minLength:1,maxLength:512,pattern:"^[^\\r\\n]+$"};const selected={"apple-notes":{label:"Apple Notes",tool:"list_notes",field:"notes",properties:{folderId:nativeId,limit:{type:"integer",minimum:1,maximum:500}}},"apple-reminders":{label:"Apple Reminders",tool:"list_reminders",field:"reminders",properties:{listId:nativeId,completed:{type:"boolean"},limit:{type:"integer",minimum:1,maximum:500}}},"apple-music":{label:"Apple Music",tool:"list_tracks",field:"tracks",properties:{playlistId:{...nativeId,pattern:"^[A-Fa-f0-9]+$"},limit:{type:"integer",minimum:1,maximum:500}}},"macos-contacts":{label:"macOS Contacts",tool:"list_contacts",field:"contacts",properties:{limit:{type:"integer",minimum:1,maximum:500}}}}[source];const records=(id,structured)=>{const rows=structured?.[selected.field];if(!Array.isArray(rows)||rows.length>100||rows.some(row=>!row||typeof row!=="object"||typeof row.id!=="string"))return;return rows.map(row=>({source:id,sourceId:row.id,kind:source==="apple-notes"?"note":source==="apple-reminders"?"reminder":source==="apple-music"?"track":"contact",body:typeof row.name==="string"?row.name:"",fields:JSON.parse(JSON.stringify(row))}))};return{source,label:selected.label,group:"Connector / Local and native",auth,readOnly:true,server:{transport:"stdio",command:process.execPath,args:[fileURLToPath(bundledServers[source])]},allowedTools:[selected.tool],reviewedReadTools:{[selected.tool]:{inputSchemaSha256:reviewedToolSchemaHash({type:"object",properties:selected.properties,required:[],additionalProperties:false})}},validateParams(tool,args){return tool===selected.tool&&Object.keys(args).every(key=>key==="limit")&&Number.isInteger(args.limit)&&Number(args.limit)>=1&&Number(args.limit)<=100?ok(void 0):businessError("invalid_argument","Use a bounded native read of at most 100 items.","plugin")},validateResult(tool,result){return tool===selected.tool&&records(source,result.structured)?ok(void 0):businessError("data_loss","The native application returned invalid item metadata.","plugin")},liveRead:{tool:selected.tool,args:{limit:100},records:(id,structured)=>records(id,structured)},unavailable:()=>process.platform==="darwin"?void 0:"This source requires macOS.",origin:{official:true,repo:"Apple/macOS-scripting-dictionaries",artifact:"indra-apple-native-read@1.0.0",check:"Bounded local metadata reads through the installed macOS scripting dictionary; OS Automation and Contacts permissions remain authoritative."}}}
|