@crewx/sdk 0.9.0-rc.227 → 0.9.0-rc.229
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app-sync/index.js +23 -23
- package/dist/config/canonicalize-agent-options.d.ts +11 -0
- package/dist/config/models.generated.d.ts +2 -2
- package/dist/esm/app-sync/index.js +23 -23
- package/dist/esm/index.js +291 -291
- package/dist/esm/plugins/index.js +44 -44
- package/dist/esm/repository/index.js +72 -72
- package/dist/index.browser.js +3 -3
- package/dist/index.d.ts +6 -4
- package/dist/index.js +283 -283
- package/dist/plugins/index.js +44 -44
- package/dist/provider/cli/adapters/claude-task-events.d.ts +48 -0
- package/dist/repository/index.js +72 -72
- package/dist/route/index.d.ts +2 -2
- package/dist/route/types.d.ts +115 -0
- package/dist/task-log/claude-background-task.d.ts +30 -0
- package/dist/types/index.d.ts +40 -0
- package/package.json +1 -1
package/dist/app-sync/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
'use strict';var fs$1=require('fs'),ne=require('path'),Ko=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder'),require('fs/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var Ko__default=/*#__PURE__*/_interopDefault(Ko);var xt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var d=k(()=>{});function jo(t){if(t===":memory:")return t;let e=ne.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let s=ne.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=fs$1.realpathSync(n);for(let s of r)o=ne.join(o,s);return ne.resolve(o)}function cd(t,e){let n=jo(t),r=jo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Qe(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&ud.some(e=>cd(t,ne.join(Ko__default.default.homedir(),".crewx",e))))throw new Error(`${dd}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var dd,ud,D,P=k(()=>{d();dd="[crewx] Refusing to open the real CrewX database from a test process";ud=["crewx.db","logs.db"];D=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||ne.join(Ko__default.default.homedir(),".crewx","crewx.db");return Qe(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});var L=k(()=>{d();});function x(t,e={}){let n=Qe(t),r=xt("better-sqlite3"),{drizzle:o}=xt("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${_n}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,a=[])=>s.prepare(i).run(...a),close:()=>s.close()}}var _n,M=k(()=>{d();P();_n=32*1024*1024;});function ht(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function _d(t,e){if(e>0||!ht(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(pd))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function fd(t,e,n){if(!ht(t,"__drizzle_migrations")||!ht(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=gd[i.tag];if(!a)continue;let c=ne__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(c))continue;let u=fs$1.readFileSync(c,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let
|
|
1
|
+
'use strict';var fs$1=require('fs'),ne=require('path'),Ko=require('os'),crypto=require('crypto'),sqliteCore=require('drizzle-orm/sqlite-core'),drizzleOrm=require('drizzle-orm'),child_process=require('child_process');require('string_decoder'),require('fs/promises');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ne__default=/*#__PURE__*/_interopDefault(ne);var Ko__default=/*#__PURE__*/_interopDefault(Ko);var xt=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var k=(t,e)=>()=>(t&&(e=t(t=0)),e);var d=k(()=>{});function jo(t){if(t===":memory:")return t;let e=ne.resolve(t),n=e,r=[];for(;!fs$1.existsSync(n);){let s=ne.dirname(n);if(s===n)return e;r.unshift(n.slice(s.length+1)),n=s;}let o=fs$1.realpathSync(n);for(let s of r)o=ne.join(o,s);return ne.resolve(o)}function cd(t,e){let n=jo(t),r=jo(e);return process.platform==="win32"?n.toLowerCase()===r.toLowerCase():n===r}function Qe(t){if((process.env.NODE_ENV==="test"||process.env.VITEST!==void 0)&&ud.some(e=>cd(t,ne.join(Ko__default.default.homedir(),".crewx",e))))throw new Error(`${dd}: ${t}. Set CREWX_DB to an isolated temporary path or :memory:.`);return t}var dd,ud,D,P=k(()=>{d();dd="[crewx] Refusing to open the real CrewX database from a test process";ud=["crewx.db","logs.db"];D=class{resolveDbPath(){if(process.env.CREWX_TRACES_DB!==void 0)throw new Error(`CREWX_TRACES_DB is removed. Use CREWX_DB instead. (got: ${process.env.CREWX_TRACES_DB})`);let e=process.env.CREWX_DB||ne.join(Ko__default.default.homedir(),".crewx","crewx.db");return Qe(e)}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return fs$1.existsSync(e??this.resolveDbPath())}};});var L=k(()=>{d();});function x(t,e={}){let n=Qe(t),r=xt("better-sqlite3"),{drizzle:o}=xt("drizzle-orm/better-sqlite3"),s=e.readOnly?new r(n,{readonly:true,fileMustExist:true}):new r(n);return e.readOnly||(s.exec("PRAGMA journal_mode = WAL"),s.exec(`PRAGMA journal_size_limit = ${_n}`),s.exec("PRAGMA busy_timeout = 5000"),s.exec("PRAGMA foreign_keys = ON"),s.exec("PRAGMA analysis_limit = 400")),{db:o(s),sqlite:s,runRaw:(i,a=[])=>s.prepare(i).run(...a),close:()=>s.close()}}var _n,M=k(()=>{d();P();_n=32*1024*1024;});function ht(t,e){return (t.get(`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='${e}'`)?.cnt??0)>0}function _d(t,e){if(e>0||!ht(t,"tasks"))return;let n=t.all("PRAGMA table_info(tasks)"),r=new Set(n.map(o=>o.name));for(let[o,s]of Object.entries(pd))r.has(o)||t.run(`ALTER TABLE tasks ADD COLUMN ${o} ${s}`);}function fd(t,e,n){if(!ht(t,"__drizzle_migrations")||!ht(t,"tasks"))return;let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=gd[i.tag];if(!a)continue;let c=ne__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(c))continue;let u=fs$1.readFileSync(c,"utf-8"),p=crypto.createHash("sha256").update(u).digest("hex");if(o.has(p))continue;let f=t.all("PRAGMA table_info(tasks)"),_=new Set(f.map(S=>S.name));for(let[S,w]of Object.entries(a))_.has(S)||(t.run(`ALTER TABLE tasks ADD COLUMN ${S} ${w}`),_.add(S));}}function Yo(t){let e=t.trim().replace(/;+\s*$/,"").trim(),n=e.match(/^ALTER\s+TABLE\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ADD\s+(?:COLUMN\s+)?[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(n)return {kind:"add-column",table:n[1],column:n[2]};let r=e.match(/^CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+NOT\s+EXISTS)?\s+[`"]?([A-Za-z_][\w$]*)[`"]?\s+ON\s+/i);if(r)return {kind:"create-index",name:r[1]};let o=e.match(/^DROP\s+INDEX\s+IF\s+EXISTS\s+[`"]?([A-Za-z_][\w$]*)[`"]?/i);if(o)return {kind:"drop-index",name:o[1]}}function Jo(t){return t.split(/-->\s*statement-breakpoint/).map(e=>e.trim()).filter(Boolean)}function hd(t,e,n){return t.all(`PRAGMA table_info("${e}")`).some(s=>s.name===n)}function md(t,e){return t.all(`SELECT name FROM sqlite_master WHERE type = 'index' AND name = '${e}'`).length>0}function gn(t,e){return e.kind==="add-column"?hd(t,e.table,e.column):md(t,e.name)}function Xo(t,e,n){let r=t;for(let o of Jo(e)){let s=Yo(o);s?.kind==="add-column"&&gn(r,s)||s?.kind==="create-index"&&gn(r,s)||s?.kind==="drop-index"&&!gn(r,s)||r.run(n.raw(o));}}function yd(t,e,n){let r=t.all(n`SELECT hash FROM __drizzle_migrations`),o=new Set(r.map(i=>i.hash)),s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8"));for(let i of s.entries){let a=ne__default.default.join(e,`${i.tag}.sql`);if(!fs$1.existsSync(a))continue;let c=fs$1.readFileSync(a,"utf-8"),u=crypto.createHash("sha256").update(c).digest("hex");if(o.has(u))continue;let f=Jo(c).map(Yo);if(f.some(S=>!S))continue;let _=f;_.some(S=>S.kind==="add-column")&&_.some(S=>gn(t,S))&&(t.transaction(S=>{Xo(S,c,n),S.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${u}, ${i.when})`);},{behavior:"immediate"}),o.add(u),console.error(`[crewx] Reconciled additive migration ${i.tag} from existing schema objects.`));}}function kd(t,e){let{sql:n}=xt("drizzle-orm"),r=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")),s=["0025_task_heartbeat","0025_thread_app_instance_ledger","0026_mcp_action_source","0027_ui_instance_active_unique"].map(i=>{let a=r.entries.find(u=>u.tag===i);if(!a)throw new Error(`Missing release/App compatibility migration: ${i}`);let c=fs$1.readFileSync(ne__default.default.join(e,`${i}.sql`),"utf-8");return {entry:a,content:c,hash:crypto.createHash("sha256").update(c).digest("hex")}});t.transaction(i=>{let a=new Set(i.all(n`SELECT hash FROM __drizzle_migrations`).map(c=>c.hash));if(a.has(s[0].hash))for(let c of s.slice(1))a.has(c.hash)||(Xo(i,c.content,n),i.run(n`INSERT INTO __drizzle_migrations (hash, created_at) VALUES (${c.hash}, ${c.entry.when})`),a.add(c.hash),console.error(`[crewx] Replayed release/App migration ${c.entry.tag} safely.`));},{behavior:"immediate"});}function Ed(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:f})=>f===Sd);if(!s)return;let i=ne__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!ht(t,"tasks"))return {hash:a,affectedRows:0};let c=t.all("PRAGMA table_info(tasks)"),u=new Set(c.map(f=>f.name));if(!u.has("stop_requested_at")||!u.has("stop_requested_epoch"))return {hash:a,affectedRows:0};let p=t.get(n`
|
|
2
2
|
SELECT count(*) AS count
|
|
3
3
|
FROM tasks
|
|
4
4
|
WHERE status IN ('success', 'failed')
|
|
5
5
|
AND (stop_requested_at IS NOT NULL OR stop_requested_epoch IS NOT NULL)
|
|
6
|
-
`);return {hash:a,affectedRows:p?.count??0}}function Td(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:
|
|
6
|
+
`);return {hash:a,affectedRows:p?.count??0}}function Td(t,e,n,r){let s=JSON.parse(fs$1.readFileSync(ne__default.default.join(e,"meta/_journal.json"),"utf-8")).entries.find(({tag:f})=>f===wd);if(!s)return;let i=ne__default.default.join(e,`${s.tag}.sql`);if(!fs$1.existsSync(i))return;let a=crypto.createHash("sha256").update(fs$1.readFileSync(i,"utf-8")).digest("hex");if(r&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a))return;if(!ht(t,"threads"))return {hash:a,markedPointers:0};if(!t.all("PRAGMA table_info(threads)").some(f=>f.name==="created_by_task_id"))return {hash:a,markedPointers:0};let u=ht(t,zo)?`AND NOT EXISTS (
|
|
7
7
|
SELECT 1
|
|
8
8
|
FROM ${zo} AS marked
|
|
9
9
|
WHERE marked.thread_id = current.id
|
|
@@ -17,9 +17,9 @@
|
|
|
17
17
|
WHERE type = 'trigger'
|
|
18
18
|
AND name = '${Rd}'
|
|
19
19
|
)
|
|
20
|
-
${u}`);return {hash:a,markedPointers:p?.count??0}}function fn(t){let{migrate:e}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),r=[ne__default.default.join(__dirname,"../migrations"),ne__default.default.join(__dirname,"migrations"),ne__default.default.join(__dirname,"../../../../drizzle/migrations"),ne__default.default.join(process.cwd(),"drizzle/migrations")],o=r.find(
|
|
20
|
+
${u}`);return {hash:a,markedPointers:p?.count??0}}function fn(t){let{migrate:e}=xt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=xt("drizzle-orm"),r=[ne__default.default.join(__dirname,"../migrations"),ne__default.default.join(__dirname,"migrations"),ne__default.default.join(__dirname,"../../../../drizzle/migrations"),ne__default.default.join(process.cwd(),"drizzle/migrations")],o=r.find(f=>fs$1.existsSync(ne__default.default.join(f,"meta/_journal.json")));if(!o)throw new Error(`migrations folder not found. Searched:
|
|
21
21
|
${r.join(`
|
|
22
|
-
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),_d(t,i),s?.cnt&&(kd(t,o),yd(t,o,n),fd(t,o,n));let a=Ed(t,o,n,!!s?.cnt),c=Td(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let p=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(p>0){let g=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${g} (${p} migration${p>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a.hash)&&console.error(`[crewx] Task stop-marker cleanup (${a.affectedRows} success/failed row(s) affected).`),c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function B(t,e){Vo.has(e)||(fn(t),Vo.add(e));}var Vo,pd,gd,Sd,wd,Rd,zo,q=k(()=>{d();Vo=new Set,pd={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};gd={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};Sd="0027_task_stop_scope_cleanup",wd="0033_thread_creator_boundary_guard",Rd="trg_threads_creator_late_fill_guard",zo="thread_creator_unverified";});var Se,hn=k(()=>{d();Se=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var V,b_,C_,mt=k(()=>{d();V=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:b_,...C_}=drizzleOrm.getTableColumns(V);});var ts=k(()=>{d();mt();sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var rs=k(()=>{d();mt();sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Fd,Ud,G,yt=k(()=>{d();hn();Fd="json_extract(metadata, '$.threadTitle.state')",Ud="json_extract(metadata, '$.threadTitle.priority')",G=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Se.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Fd)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Ud))}));});var is=k(()=>{d();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var gr,ds=k(()=>{d();mt();gr=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>gr.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var us=k(()=>{d();mt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var _s=k(()=>{d();yt();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var fs,hs=k(()=>{d();yt();fs=sqliteCore.sqliteTable("thread_branches",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),parent_thread_id:sqliteCore.text("parent_thread_id").notNull().references(()=>G.id),child_thread_id:sqliteCore.text("child_thread_id").notNull().unique().references(()=>G.id,{onDelete:"cascade"}),branch_point_task_id:sqliteCore.text("branch_point_task_id").notNull(),branch_answer_no:sqliteCore.integer("branch_answer_no").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),parent_title:sqliteCore.text("parent_title").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),payload_hash:sqliteCore.text("payload_hash").notNull(),snapshot_version:sqliteCore.integer("snapshot_version").notNull(),carry_json:sqliteCore.text("carry_json").notNull(),carried_turns:sqliteCore.integer("carried_turns").notNull(),carried_chars:sqliteCore.integer("carried_chars").notNull(),carried_truncated:sqliteCore.integer("carried_truncated").notNull().default(0),status:sqliteCore.text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:sqliteCore.text("created_at").notNull(),undone_at:sqliteCore.text("undone_at")},t=>({idx_thread_branches_parent_point:sqliteCore.index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:sqliteCore.unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:sqliteCore.check("thread_branches_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:sqliteCore.check("thread_branches_carried_truncated_ck",drizzleOrm.sql`${t.carried_truncated} IN (0, 1)`)})),sqliteCore.sqliteTable("thread_branch_sources",{branch_id:sqliteCore.text("branch_id").primaryKey().references(()=>fs.id,{onDelete:"cascade"}),source_json:sqliteCore.text("source_json").notNull(),bytes:sqliteCore.integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:sqliteCore.check("thread_branch_sources_bytes_ck",drizzleOrm.sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var ys=k(()=>{d();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var ks=k(()=>{d();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var Rs=k(()=>{d();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Es=k(()=>{d();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var As=k(()=>{d();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var bs=k(()=>{d();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Cs=k(()=>{d();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Os=k(()=>{d();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
|
|
22
|
+
`)}`);let s=t.get(n`SELECT count(*) as cnt FROM sqlite_master WHERE type='table' AND name='__drizzle_migrations'`),i=0;s?.cnt&&(i=t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0),_d(t,i),s?.cnt&&(kd(t,o),yd(t,o,n),fd(t,o,n));let a=Ed(t,o,n,!!s?.cnt),c=Td(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let p=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(p>0){let f=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${f} (${p} migration${p>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===a.hash)&&console.error(`[crewx] Task stop-marker cleanup (${a.affectedRows} success/failed row(s) affected).`),c&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(_=>_.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function B(t,e){Vo.has(e)||(fn(t),Vo.add(e));}var Vo,pd,gd,Sd,wd,Rd,zo,q=k(()=>{d();Vo=new Set,pd={agent_id:"TEXT",status:"TEXT DEFAULT 'running'",started_at:"TEXT",trace_id:"TEXT",parent_task_id:"TEXT",crewx_version:"TEXT",pid:"INTEGER",thread_id:"TEXT",workspace_id:"TEXT",workspace_ref:"TEXT",workspace_name:"TEXT",project_id:"TEXT",project_name:"TEXT",command:"TEXT",metadata:"TEXT"};gd={"0002_normalize_task_names":{workspace_name:"TEXT",project_name:"TEXT"},"0015_panoramic_gorilla_man":{project_id:"TEXT",workspace_id:"TEXT"},"0019_backfill_task_thread_ids":{command:"TEXT",thread_id:"TEXT"},"0024_storage_metadata":{prompt:"TEXT",rendered_prompt:"TEXT",result:"TEXT",input_tokens:"INTEGER DEFAULT 0",output_tokens:"INTEGER DEFAULT 0",cost_usd:"REAL DEFAULT 0"},"0044_clammy_bruce_banner":{metadata:"TEXT"}};Sd="0027_task_stop_scope_cleanup",wd="0033_thread_creator_boundary_guard",Rd="trg_threads_creator_late_fill_guard",zo="thread_creator_unverified";});var Se,hn=k(()=>{d();Se=sqliteCore.sqliteTable("workspaces",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull().unique(),name:sqliteCore.text("name").notNull(),workspace_path:sqliteCore.text("workspace_path"),description:sqliteCore.text("description"),is_active:sqliteCore.integer("is_active").notNull().default(1),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),starred:sqliteCore.integer("starred").notNull().default(0)});});var V,C_,N_,mt=k(()=>{d();V=sqliteCore.sqliteTable("tasks",{id:sqliteCore.text("id").primaryKey(),agent_id:sqliteCore.text("agent_id").notNull(),user_id:sqliteCore.text("user_id"),actor_kind:sqliteCore.text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:sqliteCore.text("actor_id"),prompt:sqliteCore.text("prompt").notNull(),mode:sqliteCore.text("mode").notNull().default("execute"),status:sqliteCore.text("status").notNull().default("running"),result:sqliteCore.text("result"),error:sqliteCore.text("error"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),metadata:sqliteCore.text("metadata"),workspace_id:sqliteCore.text("workspace_id"),trace_id:sqliteCore.text("trace_id"),parent_task_id:sqliteCore.text("parent_task_id"),caller_agent_id:sqliteCore.text("caller_agent_id"),model:sqliteCore.text("model"),platform:sqliteCore.text("platform").default("cli"),crewx_version:sqliteCore.text("crewx_version"),input_tokens:sqliteCore.integer("input_tokens").default(0),output_tokens:sqliteCore.integer("output_tokens").default(0),cost_usd:sqliteCore.real("cost_usd").default(0),pid:sqliteCore.integer("pid"),pid_started_at:sqliteCore.text("pid_started_at"),heartbeat_at:sqliteCore.text("heartbeat_at"),stop_requested_at:sqliteCore.text("stop_requested_at"),stop_requested_epoch:sqliteCore.integer("stop_requested_epoch"),rendered_prompt:sqliteCore.text("rendered_prompt"),security_key:sqliteCore.text("security_key"),command:sqliteCore.text("command"),coding_agent_command:sqliteCore.text("coding_agent_command"),exit_code:sqliteCore.integer("exit_code"),logs:sqliteCore.text("logs"),log_storage:sqliteCore.text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:sqliteCore.integer("last_log_seq").notNull().default(0),log_revision:sqliteCore.integer("log_revision").notNull().default(0),thread_id:sqliteCore.text("thread_id"),workspace_ref:sqliteCore.text("workspace_ref"),cwd:sqliteCore.text("cwd"),project_id:sqliteCore.text("project_id"),project_ref:sqliteCore.text("project_ref"),cached_input_tokens:sqliteCore.integer("cached_input_tokens").default(0),run_epoch:sqliteCore.integer("run_epoch").default(0),rating:sqliteCore.text("rating",{enum:["up","down"]}),rated_at:sqliteCore.text("rated_at"),workflow_run_id:sqliteCore.text("workflow_run_id"),schedule_id:sqliteCore.text("schedule_id")},t=>({log_storage_check:sqliteCore.check("tasks_log_storage_ck",drizzleOrm.sql`${t.log_storage} IN ('blob', 'events')`),rating_check:sqliteCore.check("tasks_rating_ck",drizzleOrm.sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:sqliteCore.index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:sqliteCore.index("idx_tasks_status").on(t.status),idx_tasks_started_at:sqliteCore.index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:sqliteCore.index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:sqliteCore.index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:sqliteCore.index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:sqliteCore.index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:sqliteCore.index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:sqliteCore.index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:sqliteCore.index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:sqliteCore.index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:sqliteCore.index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:sqliteCore.index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:sqliteCore.index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:sqliteCore.index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(drizzleOrm.sql`${t.rating} IS NOT NULL`)})),{security_key:C_,...N_}=drizzleOrm.getTableColumns(V);});var ts=k(()=>{d();mt();sqliteCore.sqliteTable("task_provider_inputs",{task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),run_epoch:sqliteCore.integer("run_epoch").notNull(),input:sqliteCore.text("input").notNull(),key_wrap_skipped:sqliteCore.integer("key_wrap_skipped").notNull().default(0),recorded_at:sqliteCore.text("recorded_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.task_id,t.run_epoch]})}));});var rs=k(()=>{d();mt();sqliteCore.sqliteTable("task_log_events",{id:sqliteCore.integer("id").primaryKey(),task_id:sqliteCore.text("task_id").notNull().references(()=>V.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),timestamp:sqliteCore.text("timestamp").notNull(),level:sqliteCore.text("level").notNull(),message:sqliteCore.text("message").notNull()},t=>({taskSeqUnique:sqliteCore.uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:sqliteCore.index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var Fd,Ud,G,yt=k(()=>{d();hn();Fd="json_extract(metadata, '$.threadTitle.state')",Ud="json_extract(metadata, '$.threadTitle.priority')",G=sqliteCore.sqliteTable("threads",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").references(()=>Se.id,{onDelete:"set null"}),created_by_kind:sqliteCore.text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:sqliteCore.text("created_by_id"),created_by_task_id:sqliteCore.text("created_by_task_id"),platform:sqliteCore.text("platform").notNull().default("cli"),title:sqliteCore.text("title"),first_message:sqliteCore.text("first_message"),last_message:sqliteCore.text("last_message"),message_count:sqliteCore.integer("message_count").notNull().default(0),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull(),metadata:sqliteCore.text("metadata"),title_locked:sqliteCore.integer("title_locked").notNull().default(0),pinned:sqliteCore.integer("pinned").notNull().default(0),starred:sqliteCore.integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:sqliteCore.index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:sqliteCore.index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:sqliteCore.index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:sqliteCore.index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:sqliteCore.index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:sqliteCore.index("idx_threads_workspace_thread_state").on(t.workspace_id,drizzleOrm.sql.raw(Fd)),idx_threads_workspace_thread_priority:sqliteCore.index("idx_threads_workspace_thread_priority").on(t.workspace_id,drizzleOrm.sql.raw(Ud))}));});var is=k(()=>{d();sqliteCore.sqliteTable("thread_creator_unverified",{thread_id:sqliteCore.text("thread_id").notNull(),created_by_task_id:sqliteCore.text("created_by_task_id").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var gr,ds=k(()=>{d();mt();gr=sqliteCore.sqliteTable("spans",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"set null"}),parent_span_id:sqliteCore.text("parent_span_id").references(()=>gr.id,{onDelete:"set null"}),name:sqliteCore.text("name").notNull(),kind:sqliteCore.text("kind").notNull().default("internal"),status:sqliteCore.text("status").notNull().default("ok"),started_at:sqliteCore.text("started_at").notNull(),completed_at:sqliteCore.text("completed_at"),duration_ms:sqliteCore.integer("duration_ms"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),error:sqliteCore.text("error"),attributes:sqliteCore.text("attributes")},t=>({idx_spans_task_id:sqliteCore.index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:sqliteCore.index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var us=k(()=>{d();mt();sqliteCore.sqliteTable("tool_calls",{id:sqliteCore.text("id").primaryKey(),task_id:sqliteCore.text("task_id").references(()=>V.id,{onDelete:"cascade"}),session_id:sqliteCore.text("session_id"),tool_name:sqliteCore.text("tool_name").notNull(),files:sqliteCore.text("files"),input:sqliteCore.text("input"),output:sqliteCore.text("output"),duration_ms:sqliteCore.integer("duration_ms"),timestamp:sqliteCore.text("timestamp").notNull()},t=>({idx_tool_calls_task_id:sqliteCore.index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:sqliteCore.index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:sqliteCore.index("idx_tool_calls_timestamp").on(t.timestamp)}));});var _s=k(()=>{d();yt();sqliteCore.sqliteTable("thread_boxes",{id:sqliteCore.text("id").primaryKey(),thread_id:sqliteCore.text("thread_id").notNull().references(()=>G.id,{onDelete:"cascade"}),seq:sqliteCore.integer("seq").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),mid_task_id:sqliteCore.text("mid_task_id").notNull(),last_task_id:sqliteCore.text("last_task_id").notNull(),task_count:sqliteCore.integer("task_count").notNull(),summary:sqliteCore.text("summary"),source_tokens:sqliteCore.integer("source_tokens").notNull(),summary_tokens:sqliteCore.integer("summary_tokens"),created_at:sqliteCore.text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:sqliteCore.index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:sqliteCore.index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:sqliteCore.unique().on(t.thread_id,t.seq)}));});var fs,hs=k(()=>{d();yt();fs=sqliteCore.sqliteTable("thread_branches",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),parent_thread_id:sqliteCore.text("parent_thread_id").notNull().references(()=>G.id),child_thread_id:sqliteCore.text("child_thread_id").notNull().unique().references(()=>G.id,{onDelete:"cascade"}),branch_point_task_id:sqliteCore.text("branch_point_task_id").notNull(),branch_answer_no:sqliteCore.integer("branch_answer_no").notNull(),first_task_id:sqliteCore.text("first_task_id").notNull(),parent_title:sqliteCore.text("parent_title").notNull(),actor_id:sqliteCore.text("actor_id").notNull(),request_id:sqliteCore.text("request_id").notNull(),payload_hash:sqliteCore.text("payload_hash").notNull(),snapshot_version:sqliteCore.integer("snapshot_version").notNull(),carry_json:sqliteCore.text("carry_json").notNull(),carried_turns:sqliteCore.integer("carried_turns").notNull(),carried_chars:sqliteCore.integer("carried_chars").notNull(),carried_truncated:sqliteCore.integer("carried_truncated").notNull().default(0),status:sqliteCore.text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:sqliteCore.text("created_at").notNull(),undone_at:sqliteCore.text("undone_at")},t=>({idx_thread_branches_parent_point:sqliteCore.index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:sqliteCore.unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:sqliteCore.check("thread_branches_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:sqliteCore.check("thread_branches_carried_truncated_ck",drizzleOrm.sql`${t.carried_truncated} IN (0, 1)`)})),sqliteCore.sqliteTable("thread_branch_sources",{branch_id:sqliteCore.text("branch_id").primaryKey().references(()=>fs.id,{onDelete:"cascade"}),source_json:sqliteCore.text("source_json").notNull(),bytes:sqliteCore.integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:sqliteCore.check("thread_branch_sources_bytes_ck",drizzleOrm.sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var ys=k(()=>{d();sqliteCore.sqliteTable("request_logs",{id:sqliteCore.text("id").primaryKey(),path:sqliteCore.text("path").notNull(),method:sqliteCore.text("method").notNull(),status_code:sqliteCore.integer("status_code").notNull(),duration_ms:sqliteCore.integer("duration_ms").notNull(),ip:sqliteCore.text("ip"),request_headers:sqliteCore.text("request_headers"),response_headers:sqliteCore.text("response_headers"),request_body:sqliteCore.text("request_body"),response_body:sqliteCore.text("response_body"),query:sqliteCore.text("query"),user_id:sqliteCore.text("user_id"),project_id:sqliteCore.text("project_id"),partition_key:sqliteCore.text("partition_key").notNull(),timestamp:sqliteCore.text("timestamp").notNull().default(drizzleOrm.sql`(datetime('now'))`),metadata:sqliteCore.text("metadata")},t=>({idx_request_logs_timestamp:sqliteCore.index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:sqliteCore.index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:sqliteCore.index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:sqliteCore.index("idx_request_logs_partition_key").on(t.partition_key)}));});var ks=k(()=>{d();sqliteCore.sqliteTable("request_log_daily",{day:sqliteCore.text("day").notNull(),scope:sqliteCore.text("scope").notNull(),ok:sqliteCore.integer("ok").notNull(),client:sqliteCore.integer("client").notNull(),server:sqliteCore.integer("server").notNull(),p50_ms:sqliteCore.integer("p50_ms"),p95_ms:sqliteCore.integer("p95_ms"),computed_at:sqliteCore.text("computed_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.day,t.scope]})}));});var Rs=k(()=>{d();sqliteCore.sqliteTable("usage_limit_snapshots",{id:sqliteCore.text("id").primaryKey(),provider:sqliteCore.text("provider").notNull(),account_ref:sqliteCore.text("account_ref").notNull().default("default"),limit_window:sqliteCore.text("limit_window").notNull(),bucket_start:sqliteCore.text("bucket_start").notNull(),captured_at:sqliteCore.text("captured_at").notNull(),used_percent:sqliteCore.integer("used_percent").notNull(),remaining_percent:sqliteCore.integer("remaining_percent").notNull(),resets_at:sqliteCore.text("resets_at"),source:sqliteCore.text("source").notNull(),metadata:sqliteCore.text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:sqliteCore.uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:sqliteCore.index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Es=k(()=>{d();sqliteCore.sqliteTable("usage_reports",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),month:sqliteCore.text("month").notNull(),generated_at:sqliteCore.text("generated_at").notNull(),source_range:sqliteCore.text("source_range").notNull(),tier:sqliteCore.text("tier").notNull(),total_tokens:sqliteCore.integer("total_tokens").notNull(),total_cost_usd:sqliteCore.real("total_cost_usd").notNull(),payload:sqliteCore.text("payload").notNull(),payload_hash:sqliteCore.text("payload_hash"),signature:sqliteCore.text("signature"),signed_at:sqliteCore.text("signed_at"),issuer:sqliteCore.text("issuer")},t=>({uniq_usage_reports_ws_month:sqliteCore.uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var As=k(()=>{d();sqliteCore.sqliteTable("notifications",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id"),task_id:sqliteCore.text("task_id"),thread_id:sqliteCore.text("thread_id"),source:sqliteCore.text("source").notNull().default("agent"),level:sqliteCore.text("level").notNull().default("info"),title:sqliteCore.text("title").notNull(),body:sqliteCore.text("body"),target_user_id:sqliteCore.text("target_user_id"),created_at:sqliteCore.text("created_at").notNull(),metadata:sqliteCore.text("metadata")},t=>({idx_notifications_ws_created:sqliteCore.index("idx_notifications_ws_created").on(t.workspace_id,drizzleOrm.sql`${t.created_at} DESC`)})),sqliteCore.sqliteTable("notification_reads",{notification_id:sqliteCore.text("notification_id").notNull(),user_id:sqliteCore.text("user_id").notNull(),read_at:sqliteCore.text("read_at").notNull()},t=>({pk:sqliteCore.primaryKey({columns:[t.notification_id,t.user_id]})}));});var bs=k(()=>{d();sqliteCore.sqliteTable("agent_suggestions",{id:sqliteCore.text("id").primaryKey(),workspace_id:sqliteCore.text("workspace_id").notNull(),agent_id:sqliteCore.text("agent_id").notNull(),task_id:sqliteCore.text("task_id"),type:sqliteCore.text("type").notNull(),status:sqliteCore.text("status").notNull().default("pending"),payload:sqliteCore.text("payload").notNull(),applied_commit_sha:sqliteCore.text("applied_commit_sha"),created_at:sqliteCore.text("created_at").notNull(),updated_at:sqliteCore.text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:sqliteCore.index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:sqliteCore.index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Cs=k(()=>{d();sqliteCore.sqliteTable("ui_instances",{id:sqliteCore.text("id").primaryKey().notNull(),definition_id:sqliteCore.text("definition_id").notNull(),definition_version:sqliteCore.integer("definition_version").notNull(),definition_hash:sqliteCore.text("definition_hash").notNull(),workspace_id:sqliteCore.text("workspace_id").notNull(),thread_id:sqliteCore.text("thread_id").notNull(),app_id:sqliteCore.text("app_id"),anchor_task_id:sqliteCore.text("anchor_task_id"),domain_ref_json:sqliteCore.text("domain_ref_json").notNull(),state_json:sqliteCore.text("state_json").notNull(),revision:sqliteCore.integer("revision").notNull().default(0),status:sqliteCore.text("status").notNull().default("active"),granted_capabilities_json:sqliteCore.text("granted_capabilities_json").notNull().default("[]"),opened_by_json:sqliteCore.text("opened_by_json"),agent_open_request_json:sqliteCore.text("agent_open_request_json"),created_at:sqliteCore.integer("created_at").notNull(),updated_at:sqliteCore.integer("updated_at").notNull()},t=>({idCheck:sqliteCore.check("ui_instances_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:sqliteCore.check("ui_instances_definition_id_ck",drizzleOrm.sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:sqliteCore.check("ui_instances_definition_version_ck",drizzleOrm.sql`${t.definition_version} >= 1`),definitionHashCheck:sqliteCore.check("ui_instances_definition_hash_ck",drizzleOrm.sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:sqliteCore.check("ui_instances_workspace_id_ck",drizzleOrm.sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:sqliteCore.check("ui_instances_thread_id_ck",drizzleOrm.sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:sqliteCore.check("ui_instances_app_id_ck",drizzleOrm.sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:sqliteCore.check("ui_instances_domain_ref_json_ck",drizzleOrm.sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:sqliteCore.check("ui_instances_state_json_ck",drizzleOrm.sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:sqliteCore.check("ui_instances_revision_ck",drizzleOrm.sql`${t.revision} >= 0`),statusCheck:sqliteCore.check("ui_instances_status_ck",drizzleOrm.sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:sqliteCore.check("ui_instances_granted_capabilities_json_ck",drizzleOrm.sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:sqliteCore.check("ui_instances_opened_by_json_ck",drizzleOrm.sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:sqliteCore.check("ui_instances_created_at_ck",drizzleOrm.sql`${t.created_at} >= 0`),updatedAtCheck:sqliteCore.check("ui_instances_updated_at_ck",drizzleOrm.sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:sqliteCore.index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:sqliteCore.uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(drizzleOrm.sql`${t.status} = 'active'`)}));});var Os=k(()=>{d();sqliteCore.sqliteTable("ui_action_receipts",{id:sqliteCore.text("id").primaryKey().notNull(),instance_id:sqliteCore.text("instance_id").notNull(),definition_id:sqliteCore.text("definition_id"),definition_version:sqliteCore.integer("definition_version"),definition_hash:sqliteCore.text("definition_hash"),request_id:sqliteCore.text("request_id").notNull(),action_id:sqliteCore.text("action_id").notNull(),actor_json:sqliteCore.text("actor_json").notNull(),source:sqliteCore.text("source").notNull(),expected_revision:sqliteCore.integer("expected_revision").notNull(),before_revision:sqliteCore.integer("before_revision").notNull(),after_revision:sqliteCore.integer("after_revision"),status:sqliteCore.text("status").notNull(),outcome:sqliteCore.text("outcome"),input_json:sqliteCore.text("input_json").notNull(),result_json:sqliteCore.text("result_json"),error_code:sqliteCore.text("error_code"),requested_at:sqliteCore.integer("requested_at").notNull(),settled_at:sqliteCore.integer("settled_at")},t=>({idCheck:sqliteCore.check("ui_action_receipts_id_ck",drizzleOrm.sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:sqliteCore.check("ui_action_receipts_instance_id_ck",drizzleOrm.sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:sqliteCore.check("ui_action_receipts_request_id_ck",drizzleOrm.sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:sqliteCore.check("ui_action_receipts_action_id_ck",drizzleOrm.sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:sqliteCore.check("ui_action_receipts_actor_json_ck",drizzleOrm.sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:sqliteCore.check("ui_action_receipts_source_ck",drizzleOrm.sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:sqliteCore.check("ui_action_receipts_expected_revision_ck",drizzleOrm.sql`${t.expected_revision} >= 0`),beforeRevisionCheck:sqliteCore.check("ui_action_receipts_before_revision_ck",drizzleOrm.sql`${t.before_revision} >= 0`),afterRevisionCheck:sqliteCore.check("ui_action_receipts_after_revision_ck",drizzleOrm.sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:sqliteCore.check("ui_action_receipts_status_ck",drizzleOrm.sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:sqliteCore.check("ui_action_receipts_outcome_ck",drizzleOrm.sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:sqliteCore.check("ui_action_receipts_input_json_ck",drizzleOrm.sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:sqliteCore.check("ui_action_receipts_result_json_ck",drizzleOrm.sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:sqliteCore.check("ui_action_receipts_requested_at_ck",drizzleOrm.sql`${t.requested_at} >= 0`),settledAtCheck:sqliteCore.check("ui_action_receipts_settled_at_ck",drizzleOrm.sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:sqliteCore.check("ui_action_receipts_status_transition_ck",drizzleOrm.sql`(
|
|
23
23
|
(${t.status} = 'requested' AND ${t.after_revision} IS NULL AND ${t.outcome} IS NULL AND ${t.settled_at} IS NULL)
|
|
24
24
|
OR
|
|
25
25
|
(${t.status} = 'settled' AND ${t.after_revision} IS NOT NULL AND ${t.outcome} IS NOT NULL AND ${t.settled_at} IS NOT NULL)
|
|
@@ -50,34 +50,34 @@ ${r.join(`
|
|
|
50
50
|
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>mu(r,e))}function ce(t){return typeof t=="object"&&t!==null}function _i(t,e){if(e==="assistant"||e==="user"){let n=t.message;return ce(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||ce(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?ce(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function yu(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:_i(t,e)}function ku(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||ce(t.error);if(e==="item.updated"||e.startsWith("thread.")||e.startsWith("turn."))return true;if(e==="item.started"||e==="item.completed"){let n=t.item;return ce(n)&&typeof n.type=="string"}return false}function Su(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||ce(t.part);if(e==="text"||e==="tool_use")return ce(t.part);if(e==="error"){let n=t.error;return ce(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function wu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ce(t.part)||e==="result"&&typeof t.result=="string")}function Ru(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ce(t.data):e==="result"?typeof t.result=="string":false}function Eu(t,e){return e==="message"?typeof t.role=="string":e==="tool_use"?typeof t.tool_name=="string"||typeof t.tool_id=="string":e==="tool_result"?typeof t.tool_id=="string"||typeof t.status=="string":false}function Tu(t,e){return e==="available_commands"?ce(t.tools)||ce(t.commands):e==="usage"?ce(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||ce(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var gi,Au,Qt=k(()=>{d();Kr();xn();gi={claude:_i,codex:ku,opencode:Su,copilot:Ru,gemini:Eu},Au={...gi,claude:yu,opencode:wu,grok:Tu,antigravity:t=>pi(JSON.stringify(t))};});function Pe(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function xe(t,e,n){let r=e.match(/@(\S+)/);return {timestamp:t,type:"agent_call",targetAgent:r?.[1]?.replace(/["']/g,""),toolInput:e,...typeof n=="string"&&n.length>0?{toolUseId:n}:{}}}var Ct=k(()=>{d();});function Cu(t){let e=Nu(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>vu(s.value)),r=Ou(e);return {result:n.length===1&&n[0].index===r?Du(n[0].line.value):null,resultPreview:Lu(e,n),hasReservedLine:n.length>0}}function Le(t,e){let n=Cu(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function Nu(t){let e=[],n=0;for(let r=0;r<t.length;r++){let o=t[r];if(o!==`
|
|
51
51
|
`&&o!=="\r")continue;let s=o==="\r"&&t[r+1]===`
|
|
52
52
|
`?`\r
|
|
53
|
-
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Ou(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function vu(t){return t.trimStart().startsWith(Iu)}function Du(t){let e=t.trim();if(!e.startsWith(fi)||!e.endsWith("]]"))return null;let n=e.slice(fi.length,-2);if(!n)return null;try{return Pu(JSON.parse(n))}catch{return null}}function Pu(t){return xu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function xu(t){if(!Mu(t)||Object.keys(t).some(r=>!bu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?hi(t.taskId)&&hi(t.agentId):t.isError===true}function Lu(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function hi(t){return typeof t=="string"&&t.trim().length>0}function Mu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fi,Iu,bu,Nt=k(()=>{d();fi="[[crewx:delegation-result ",Iu="[[crewx:delegation-result",bu=new Set(["schema","taskId","agentId","isError"]);});function Me(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var Ot=k(()=>{d();});var mi,Ln,zr,Mn=k(()=>{d();mi=["none","minimal","low","medium","high","xhigh","max","ultra"],Ln={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},zr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(zr).map(([t,e])=>[t,e.models]));});function Yr(t){return Uu[t]??t}function Bu(t){return qu.get(t)??t}function Jr(t){if(!t)return {};let e=$u.get(t);return e?{...e}:{model:t}}function Xr(t,e){return t==="antigravity"||t==="cli/antigravity"?Jr(e):e===void 0?{}:{model:Bu(e)}}var Fu,Uu,qu,Hu,$u,Zt=k(()=>{d();Fu=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Uu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};qu=new Map(Fu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Hu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],$u=new Map(Hu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function ju(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ze(t){return en(t).models}function en(t){let e=Gu[t],n=zr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??ju()}function tn(t,e){let n=en(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Qr(t){return en(t).modelOverrides}function yi(){return ze("claude")}function ki(){return ze("codex")}function Si(){return ze("copilot")}function wi(){return ze("antigravity")}var Gu,Ye=k(()=>{d();Mn();On();Zt();Gu={};});function Ri(t){return Ku[t]??t}var Ku,Ei=k(()=>{d();Ye();Zt();Ku={auto:"default"};});function Zr(t,e){return (Ln[t]??[]).includes(e)}function ct(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Vu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ti(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ai(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ii(t){return !t||!Zr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function bi(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Ri(t);return e.has(n)?["--permission-mode",n]:[]}function Ci(t){return t?Zr("claude",t)?["--effort",t]:[]:[]}function Ni(t){if(!t)return [];switch(Yr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Oi(t){return t?Zr("antigravity",t)?["--effort",t]:[]:[]}var Vu,nn=k(()=>{d();Ei();Zt();Mn();Vu=new Set(mi);});function zu(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Yu(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function Ju(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function vi(t){let e=new Map,n;for(let s of t.split(`
|
|
54
|
-
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,c=a?.id,u=a?.usage;if(typeof c!="string"||!u)continue;let p=Number(u.input_tokens??0),
|
|
55
|
-
`))if(r.trim())try{let o=JSON.parse(r),s=
|
|
53
|
+
`:o;e.push({value:t.slice(n,r),separator:s}),r+=s.length-1,n=r+1;}return e.push({value:t.slice(n),separator:""}),e}function Ou(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function vu(t){return t.trimStart().startsWith(Iu)}function Du(t){let e=t.trim();if(!e.startsWith(fi)||!e.endsWith("]]"))return null;let n=e.slice(fi.length,-2);if(!n)return null;try{return Pu(JSON.parse(n))}catch{return null}}function Pu(t){return xu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function xu(t){if(!Mu(t)||Object.keys(t).some(r=>!bu.has(r))||t.schema!==1||typeof t.isError!="boolean")return false;let e=Object.prototype.hasOwnProperty.call(t,"taskId"),n=Object.prototype.hasOwnProperty.call(t,"agentId");return e!==n?false:e?hi(t.taskId)&&hi(t.agentId):t.isError===true}function Lu(t,e){if(e.length===0)return t.map(r=>r.value+r.separator).join("");let n=new Set(e.map(({index:r})=>r));return t.map((r,o)=>n.has(o)?"":r.value+r.separator).join("")}function hi(t){return typeof t=="string"&&t.trim().length>0}function Mu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var fi,Iu,bu,Nt=k(()=>{d();fi="[[crewx:delegation-result ",Iu="[[crewx:delegation-result",bu=new Set(["schema","taskId","agentId","isError"]);});function Me(t){if(typeof t=="string")return t;if(!t||typeof t!="object")return JSON.stringify(t??{});let e=t;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var Ot=k(()=>{d();});var mi,Ln,zr,Mn=k(()=>{d();mi=["none","minimal","low","medium","high","xhigh","max","ultra"],Ln={claude:["low","medium","high","xhigh","max"],codex:["none","minimal","low","medium","high","xhigh","max","ultra"],opencode:[],copilot:["none","low","medium","high","xhigh","max"],antigravity:["low","medium","high"],grok:["low","medium","high","xhigh"]},zr={claude:{models:[{id:"claude-fable-5-1",name:"Claude Fable 5.1",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-fable-5",name:"Claude Fable 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-5-5",name:"Claude Opus 5.5",contextWindowTokens:1e6,tier:"flagship",recommended:true},{id:"claude-opus-5",name:"Claude Opus 5",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-5-5",name:"Claude Sonnet 5.5",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-opus-4-8[1m]",name:"Claude Opus 4.8",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-7[1m]",name:"Claude Opus 4.7",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-opus-4-6[1m]",name:"Claude Opus 4.6",contextWindowTokens:1e6,tier:"flagship"},{id:"claude-sonnet-4-6[1m]",name:"Claude Sonnet 4.6",contextWindowTokens:1e6,tier:"balanced"},{id:"claude-haiku-5-5",name:"Claude Haiku 5.5",contextWindowTokens:1e6,tier:"speed"},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindowTokens:2e5,tier:"speed"}],modes:[{id:"default",name:"Default",description:"Uses Claude's default permission handling with normal approval prompts."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without approval; other permission checks remain in place."},{id:"plan",name:"Plan",description:"Keeps Claude in plan mode so it can inspect and propose changes without applying them."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permissions; only pre-approved tool actions can proceed."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Claude permission checks so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"claude-fable-5-1":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-fable-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-opus-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-sonnet-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-8[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-7[1m]":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"claude-opus-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-sonnet-4-6[1m]":{effort:["low","medium","high","max"],defaultEffort:"high"},"claude-haiku-5-5":{effort:["low","medium","high","xhigh","max"],defaultEffort:"medium"},"claude-haiku-4-5":{effort:[]}},providerOptions:[]},codex:{models:[{id:"gpt-6-astra",name:"GPT-6 Astra",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",contextWindowTokens:105e4,tier:"balanced",recommended:true},{id:"gpt-6.1-terra",name:"GPT-6.1 Terra",contextWindowTokens:5e5,tier:"balanced"},{id:"gpt-6-sol",name:"GPT-6 Sol",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-6-luna",name:"GPT-6 Luna",contextWindowTokens:105e4,tier:"speed",recommended:true},{id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindowTokens:105e4,tier:"flagship"},{id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindowTokens:105e4,tier:"balanced"},{id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindowTokens:105e4,tier:"speed"}],modes:[{id:"agent",name:"Agent",description:"Uses the workspace-write sandbox; can read and modify workspace files without full machine access."},{id:"read-only",name:"Read Only",description:"Uses the read-only sandbox; can inspect files but cannot write to the workspace."},{id:"plan",name:"Plan",description:"Uses the read-only sandbox for planning and inspection; cannot write to the workspace."},{id:"agent-full-access",name:"Agent Full Access",description:"Bypasses approvals and the sandbox; can access and modify files beyond the workspace."},{id:"yolo",name:"YOLO",description:"Bypasses approvals and the sandbox for unrestricted execution and full filesystem access."}],effort:["minimal","low","medium","high"],modelOverrides:{"gpt-6-astra":{effort:["low","medium","high","xhigh","max"],defaultEffort:"xhigh"},"gpt-6.1-sol":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-6.1-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"max"},"gpt-6-sol":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"max"},"gpt-6-luna":{effort:["none","low","medium","high","xhigh","max"],defaultEffort:"medium"},"gpt-5.6-sol":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"xhigh"},"gpt-5.6-terra":{effort:["low","medium","high","xhigh","max","ultra"],defaultEffort:"high"},"gpt-5.6-luna":{effort:["low","medium","high","xhigh","max"],defaultEffort:"high"},"gpt-5.5":{effort:["low","medium","high","xhigh"],defaultEffort:"high"}},providerOptions:[]},opencode:{models:[],suggestedModels:[{id:"opencode-go/glm-5.3-flash",name:"GLM-5.3 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/qwen3.8-flash",name:"Qwen3.8 Flash",contextWindowTokens:1e6,tier:"speed",recommended:true},{id:"opencode-go/minimax-m3",name:"MiniMax M3",contextWindowTokens:1e6,tier:"balanced",recommended:true},{id:"opencode-go/kimi-k2.7-code",name:"Kimi K2.7 Code",contextWindowTokens:262144,tier:"balanced",recommended:true}],modes:[{id:"plan",name:"Plan",description:"Uses the plan agent without --auto; planning follows standard approval behavior."},{id:"plan-auto",name:"Plan \xB7 Auto",description:"Uses the plan agent with --auto; planning uses automatic approvals."},{id:"build",name:"Build",description:"Uses the build agent without --auto; work follows standard approval behavior."},{id:"build-auto",name:"Build \xB7 Auto",description:"Uses the build agent with --auto; work uses automatic approvals."}],effort:[],modelOverrides:{},providerOptions:[]},copilot:{models:[{id:"auto",name:"Auto"},{id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindowTokens:1e6,tier:"balanced"}],modes:[{id:"interactive",name:"Interactive",description:"Passes --mode interactive; tool access follows Copilot's interactive mode behavior."},{id:"plan",name:"Plan",description:"Passes --mode plan; planning and permission behavior follow Copilot's plan mode."},{id:"autopilot",name:"Autopilot",description:"Passes --mode autopilot; execution behavior follows Copilot's autonomous mode."}],effort:["none","low","medium","high","xhigh","max"],modelOverrides:{},providerOptions:[]},antigravity:{models:[{id:"gemini-3.8-flash",name:"Gemini 3.8 Flash",tier:"balanced"},{id:"gemini-3.7-flash",name:"Gemini 3.7 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.6-flash",name:"Gemini 3.6 Flash",contextWindowTokens:1048576,tier:"balanced"},{id:"gemini-3.1-pro",name:"Gemini 3.1 Pro",contextWindowTokens:1048576,tier:"flagship"},{id:"claude-sonnet-5-5-medium",name:"Claude Sonnet 5.5",tier:"balanced"},{id:"claude-opus-5-5-medium",name:"Claude Opus 5.5",tier:"flagship"},{id:"gemini-4-argon",name:"Gemini 4 Argon",tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Antigravity's default permission handling. No extra permission flags are passed."},{id:"plan",name:"Plan",description:"Passes --mode plan. This turns on /plan; it is not a Claude-style permission mode."},{id:"acceptEdits",name:"Accept Edits",description:"Passes --mode accept-edits."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Passes --dangerously-skip-permissions so tools can run without approval prompts."}],effort:["low","medium","high"],modelOverrides:{"gemini-3.8-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.7-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.6-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.5-flash":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-3.1-pro":{effort:["low","high"],defaultEffort:"high"},"claude-sonnet-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"claude-opus-5-5-medium":{effort:["low","medium","high"],defaultEffort:"medium"},"gemini-4-argon":{effort:["low","medium","high"],defaultEffort:"high"},"claude-sonnet-4-6":{effort:[]},"claude-opus-4-6-thinking":{effort:[]},"gpt-oss-120b":{effort:["medium"],defaultEffort:"medium"}},providerOptions:[]},grok:{models:[{id:"grok-4.7",name:"Grok 4.7",contextWindowTokens:5e5,tier:"flagship",recommended:true},{id:"grok-4.6",name:"Grok 4.6",contextWindowTokens:5e5,tier:"flagship"},{id:"grok-4.5",name:"Grok 4.5",contextWindowTokens:5e5,tier:"flagship"}],modes:[{id:"default",name:"Default",description:"Uses Grok's default permission handling."},{id:"acceptEdits",name:"Accept Edits",description:"Allows file edits without changing the selected sandbox profile."},{id:"auto",name:"Auto",description:"Uses Grok automatic permission handling."},{id:"dontAsk",name:"Don't Ask",description:"Does not ask for permission before tool execution."},{id:"bypassPermissions",name:"Bypass Permissions",description:"Bypasses Grok permission checks for tool execution."},{id:"plan",name:"Plan",description:"Keeps Grok in planning mode without applying changes."}],effort:["low","medium","high"],modelOverrides:{"grok-4.7":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.6":{effort:["low","medium","high","xhigh"],defaultEffort:"high"},"grok-4.5":{effort:["low","medium","high"],defaultEffort:"high"}},providerOptions:[{key:"alwaysApprove",type:"boolean"},{key:"sandbox",type:"enum",values:["workspace","read-only","off"]}]}},Object.fromEntries(Object.entries(zr).map(([t,e])=>[t,e.models]));});function Yr(t){return Uu[t]??t}function Bu(t){return qu.get(t)??t}function Jr(t){if(!t)return {};let e=$u.get(t);return e?{...e}:{model:t}}function Xr(t,e){return t==="antigravity"||t==="cli/antigravity"?Jr(e):e===void 0?{}:{model:Bu(e)}}var Fu,Uu,qu,Hu,$u,Zt=k(()=>{d();Fu=[{baseModelId:"claude-opus-4-8",catalogModelId:"claude-opus-4-8[1m]"},{baseModelId:"claude-opus-4-7",catalogModelId:"claude-opus-4-7[1m]"},{baseModelId:"claude-opus-4-6",catalogModelId:"claude-opus-4-6[1m]"},{baseModelId:"claude-sonnet-4-6",catalogModelId:"claude-sonnet-4-6[1m]"}],Uu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};qu=new Map(Fu.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Hu=[{legacyId:"Gemini 3.7 Flash (High)",model:"gemini-3.7-flash",effort:"high"},{legacyId:"Gemini 3.7 Flash (Medium)",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"Gemini 3.7 Flash (Low)",model:"gemini-3.7-flash",effort:"low"},{legacyId:"Gemini 3.6 Flash (High)",model:"gemini-3.6-flash",effort:"high"},{legacyId:"Gemini 3.6 Flash (Medium)",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"Gemini 3.6 Flash (Low)",model:"gemini-3.6-flash",effort:"low"},{legacyId:"Gemini 3.5 Flash (Medium)",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"Gemini 3.5 Flash (High)",model:"gemini-3.5-flash",effort:"high"},{legacyId:"Gemini 3.5 Flash (Low)",model:"gemini-3.5-flash",effort:"low"},{legacyId:"Gemini 3.1 Pro (Low)",model:"gemini-3.1-pro",effort:"low"},{legacyId:"Gemini 3.1 Pro (High)",model:"gemini-3.1-pro",effort:"high"},{legacyId:"Claude Sonnet 4.6 (Thinking)",model:"claude-sonnet-4-6"},{legacyId:"Claude Opus 4.6 (Thinking)",model:"claude-opus-4-6-thinking"},{legacyId:"GPT-OSS 120B (Medium)",model:"gpt-oss-120b",effort:"medium"},{legacyId:"gemini-3.7-flash-high",model:"gemini-3.7-flash",effort:"high"},{legacyId:"gemini-3.7-flash-medium",model:"gemini-3.7-flash",effort:"medium"},{legacyId:"gemini-3.7-flash-low",model:"gemini-3.7-flash",effort:"low"},{legacyId:"gemini-3.6-flash-high",model:"gemini-3.6-flash",effort:"high"},{legacyId:"gemini-3.6-flash-medium",model:"gemini-3.6-flash",effort:"medium"},{legacyId:"gemini-3.6-flash-low",model:"gemini-3.6-flash",effort:"low"},{legacyId:"gemini-3.5-flash-high",model:"gemini-3.5-flash",effort:"high"},{legacyId:"gemini-3.5-flash-medium",model:"gemini-3.5-flash",effort:"medium"},{legacyId:"gemini-3.5-flash-low",model:"gemini-3.5-flash",effort:"low"},{legacyId:"gemini-3.1-pro-high",model:"gemini-3.1-pro",effort:"high"},{legacyId:"gemini-3.1-pro-low",model:"gemini-3.1-pro",effort:"low"},{legacyId:"gpt-oss-120b-medium",model:"gpt-oss-120b",effort:"medium"}],$u=new Map(Hu.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function ju(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function ze(t){return en(t).models}function en(t){let e=Gu[t],n=zr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??ju()}function tn(t,e){let n=en(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Xr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Qr(t){return en(t).modelOverrides}function yi(){return ze("claude")}function ki(){return ze("codex")}function Si(){return ze("copilot")}function wi(){return ze("antigravity")}var Gu,Ye=k(()=>{d();Mn();On();Zt();Gu={};});function Ri(t){return Vu[t]??t}var Vu,Ei=k(()=>{d();Ye();Zt();Vu={auto:"default"};});function Zr(t,e){return (Ln[t]??[]).includes(e)}function ct(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return zu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ti(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["--sandbox","read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ai(t){switch(t){case "agent-full-access":case "yolo":return ["--dangerously-bypass-approvals-and-sandbox"];case "read-only":case "plan":return ["-c","sandbox_mode=read-only"];case "agent":return ["-c","sandbox_mode=workspace-write"];default:return []}}function Ii(t){return !t||!Zr("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function bi(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Ri(t);return e.has(n)?["--permission-mode",n]:[]}function Ci(t){return t?Zr("claude",t)?["--effort",t]:[]:[]}function Ni(t){if(!t)return [];switch(Yr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function Oi(t){return t?Zr("antigravity",t)?["--effort",t]:[]:[]}var zu,nn=k(()=>{d();Ei();Zt();Mn();zu=new Set(mi);});function Yu(t){if(t.type!=="usage"||!("input_tokens"in t))return null;let e=Number(t.input_tokens??0),n=Number(t.output_tokens??0),o="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,s="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:n,cachedInputTokens:i}}function Ju(t){let e=t.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e;if(!("input_tokens"in n))return null;let r=Number(n.input_tokens??0),o=Number(n.output_tokens??0),i="cache_read_input_tokens"in n?Number(n.cache_read_input_tokens):void 0,a="cached_input_tokens"in n?Number(n.cached_input_tokens):void 0,c=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:o,cachedInputTokens:c}}function Xu(t){if(t.type!=="step_finish")return null;let n=t.part?.tokens;if(!n)return null;let r=Number(n.input??0),o=Number(n.output??0)+Number(n.reasoning??0),s=n.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:o,cachedInputTokens:i}}function vi(t){let e=new Map,n;for(let s of t.split(`
|
|
54
|
+
`))if(s.trim())try{let i=JSON.parse(s);if(i.type!=="assistant")continue;let a=i.message,c=a?.id,u=a?.usage;if(typeof c!="string"||!u)continue;let p=Number(u.input_tokens??0),f=Number(u.cache_read_input_tokens??0);e.set(c,{inputTokens:p+f,cachedInputTokens:f});let _=a?.model;typeof _=="string"&&_&&(n=_);}catch{}if(e.size===0)return;let r=0,o=0;for(let s of e.values())r+=s.inputTokens,o+=s.cachedInputTokens;return {inputTokens:r,cachedInputTokens:o,model:n}}function rn(t){if(!t||!t.trim())return;let e=null,n=null;for(let r of t.split(`
|
|
55
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=Xu(o);if(s){n||(n={inputTokens:0,outputTokens:0,cachedInputTokens:0}),n.inputTokens+=s.inputTokens,n.outputTokens+=s.outputTokens,n.cachedInputTokens+=s.cachedInputTokens;continue}let i=Yu(o)??Ju(o);i&&(e=i);}catch{}return n||(e??void 0)}var on=k(()=>{d();});function $e(t,e){if(typeof t!="object"||t===null||Array.isArray(t))return e;let n=t.timestamp;return typeof n!="string"||!Number.isFinite(Date.parse(n))?e:new Date(n).toISOString()}var ut=k(()=>{d();});var Fn,Di=k(()=>{d();Fn=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function xi(t){return t==="all"?[...Pi,...Qu]:Pi}function Li(t){return xi(t).map(e=>`Bash(${e} *)`)}function Mi(t){return xi(t).map(e=>`command(${e})`)}var Pi,Qu,eo=k(()=>{d();Pi=["crewx memory","crewx search","crewx doc","crewx notify"],Qu=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function Fi(t){let e=t.split(`
|
|
56
56
|
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&n.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Ui(t){let e=t.split(`
|
|
57
|
-
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Gi(t){let e=vt(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=
|
|
58
|
-
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=vt(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function
|
|
57
|
+
`).filter(n=>n.trim());for(let n of e.reverse())try{let r=JSON.parse(n);if(typeof r=="object"&&r!==null&&r.type==="result")return r}catch{}}function vt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function Gi(t){let e=vt(t.rate_limit_info);if(t.type==="rate_limit_event"&&e?.status==="rejected")return `Claude rate limit: ${typeof e.rateLimitType=="string"?e.rateLimitType:"unknown"} (status: rejected)`;if(t.error==="rate_limit"){let n=ol(t);return n?`Claude rate limit: ${n}`:"Claude rate limit"}if(t.type==="result"&&t.is_error===true){let n=typeof t.result=="string"?t.result:"";if(sl(n))return `Claude rate limit: ${n}`}}function tl(t){for(let e of t.split(`
|
|
58
|
+
`)){let n=e.trim();if(n){if(n.startsWith("Not logged in"))return n;try{let r=vt(JSON.parse(n));if(r?.type==="result"&&r.is_error===!0&&typeof r.result=="string"&&r.result.startsWith("Not logged in"))return r.result}catch{}}}}function nl(t){let e=vt(t);if(e?.type!=="rate_limit_event")return;let n=vt(vt(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=qi(n.five_hour),o=qi(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function qi(t){let e=vt(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Bi(t){if(t?.is_error===true)return Dn(t.result)}function rl(t){let e=Gi(t);if(e)return e;if(t.type!=="result"||t.is_error!==true)return;let n=typeof t.result=="string"?t.result:"";if(n.trim())return n;let r=typeof t.subtype=="string"?t.subtype:"unknown",o=typeof t.terminal_reason=="string"?t.terminal_reason:"unknown";return `Claude ended without an answer (subtype=${r}, terminal_reason=${o})`}function ol(t){let n=t.message?.content;return Array.isArray(n)?n.map(r=>typeof r.text=="string"?r.text.trim():"").filter(Boolean).join(`
|
|
59
59
|
|
|
60
|
-
`):""}function
|
|
61
|
-
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Le(i,r)}}return null}var
|
|
62
|
-
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,c=a?Object.keys(a)[0]??null:null;return {usage:i,model:c}}}catch{}let n=vi(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=$e(n,e??new Date().toISOString()),s=
|
|
63
|
-
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var
|
|
64
|
-
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Je(t.error)}function Yi(t){let e=Je(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function
|
|
65
|
-
`),a=typeof e.error=="string"?e.error:Je(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||a,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=Me(s);return o==="Bash"&&Pe(i)?xe(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...Le(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(Je(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(a=>String(a.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function fl(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=Me(o);return r==="Bash"&&Pe(s)?xe(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var dl,cl,oo=k(()=>{d();Ve();Qt();on();Ct();Ot();Kr();Nt();nn();Ye();ut();dl=new Set(["turn.started","turn.completed","item.updated"]),cl="cli/codex";({command:"codex",meta:{displayName:"Codex",models:ki(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ct(e.model),s=e.effort??o,i=e.resumeSessionId?Ai(e.mode):Ti(e.mode),a=Ii(s),c=r?["-m",r]:[],u=ll(e.additionalArgs??[]),g=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...g,...i,...a,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...g,...i,...a,...c,...u],stdinMessage:t}},extractText(t){let e=pl(t);if(e)throw new j(e,cl);let n=Ki(t);if(n)return n;let r=t.trim();return dt(r,"codex")?"":r},extractPartialText(t){return Ki(t)},parseResultMeta(t){let e=rn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=ul(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,a]of s.entries()){let c;try{c=JSON.parse(a);}catch{continue}if(!Je(c))continue;let u=c.type;if(!u)continue;let p=$e(c,r);if(zi(c)){let _=Yi(c);o.push({timestamp:p,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Wr(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let g=c.item;if(g){if(u==="item.started"){o.push(..._l(p,g,Vi(g,u,n,i)));continue}if(u==="item.completed"){let _=gl(p,g,Vi(g,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?dl.has(r):!1}catch{return false}}});});var Xi=k(()=>{d();});var Qi=k(()=>{d();});function ml(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function yl(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Zi),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:Zi,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(ml(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function kl(){return process.platform!=="win32"?Promise.resolve(null):(Un||(Un=yl(),Un.then(t=>{},()=>{})),Un)}function Sl(){process.platform==="win32"&&kl();}var Zi,Un,ta=k(()=>{d();Zi=1e3;Sl();});var so=k(()=>{d();});var na=k(()=>{d();});var io=k(()=>{d();Ve();so();na();});var ra=k(()=>{d();ao();Qi();ta();so();io();Ye();});var co=k(()=>{d();Ve();Xi();on();Ot();ut();ra();io();});var oa=k(()=>{d();});function Dt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ol(t,e){return t&&sa.has(t)||Dt(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&sa.has(o)})}function vl(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function Dl(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!Cl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function me(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Pl(t,e){if(!(t?bl.has(t)||ze(uo).some(s=>s.id===t):false)||!t)return e;let r=tn(uo,t),o=Qr(uo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Ge(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function _o(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function go(t){return t.step.step_index}function $(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Dn(e)?.slice(0,500).trim()||void 0}function xl(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Nl.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function Ll(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function da(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=e?$(e.code)??$(e.error_code)??$(n?.code)??$(n?.error_code):void 0,o=typeof t=="string"?$(t):e?$(e.message)??$(e.error)??$(e.reason)??$(n?.message)??$(n?.error)??$(n?.reason):void 0,s=xl(r,o),i=e?Ge(e.retry_after_ms)??Ge(e.retryAfterMs)??Ge(n?.retry_after_ms)??Ge(n?.retryAfterMs):void 0;return {code:s,kind:Ll(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Bn(t){let e=da(t);return new j(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function fo(t){return new j(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Ml(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=po))throw new j(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${po} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function lo(){return new j("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Hn(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function $n(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function Fl(t){let e=$n(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Hn(e.event)?.status!=="SUCCESS"||qn(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=_o(o),i=go(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!me(o.usage)||Ge(o.usage.input_tokens)===void 0||Ge(o.usage.output_tokens)===void 0)return false;return true}function Ul(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function ql(t,e){return me(t)&&me(e)?{...e,...t}:me(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&me(e)?{...e,message:t}:t??e}function Bl(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=me(i)?i:void 0,c=typeof i=="string"?$(i):$(a?.display_name)??$(a?.action);c&&!n.includes(c)&&n.length<5&&n.push(c.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new j("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function qn(t){let e=$n(t);if(!e)return;if(e.event.kind==="agy_error")return Bn(e.event.error);let n=Hn(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Bl(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return fo("Antigravity returned a result with an unsupported status.");let r=n.error,o=ql(r==null||r===""?n:r,Ul(t,e.index));return Bn(o)}function ca(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function Hl(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function $l(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function ua(t){let e=ca(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function Gl(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=($(e?.type)??$(e?.code)??$(e?.error_type)??$(n?.type)??$(n?.code)??$(n?.error_type)??$(r)??"TOOL_ERROR").slice(0,60),s=da(t).message.slice(0,250);return ua({type:o,message:s})??"Antigravity reported a tool error."}function ia(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function aa(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var uo,bl,Cl,sa,po,Nl,ho=k(()=>{d();Ve();oa();Gr();Zt();Ye();nn();xn();eo();uo="antigravity",bl=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Cl=new Set(["--conversation","--resume","--continue"]),sa=new Set(["bypassPermissions","agent-full-access","yolo"]),po=18e4,Nl=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);({command:"agy",maxInitialInputBytes:po,meta:{displayName:"Antigravity",models:wi(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Xt(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){Ml(t);let{model:r,effort:o}=ct(e.model),s=Jr(r),i=s.model,a=e.effort??o??s.effort,c=Pl(i,a),u=e.additionalArgs??[],p=Dl(vl(u,new Set(["--input-format","--output-format"]))),g=i&&!Dt(u,"--model")?["--model",i]:[],_=Dt(u,"--effort")?[]:Oi(c),S=Dt(u,"--mode")||Dt(u,"--dangerously-skip-permissions")?[]:Ni(e.mode),w=Ol(e.mode,u)||Dt(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Mi(e.builtinAllow)}})],E=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...g,..._,...S,...E,...w,...p],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
66
|
-
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=bt(t),n=$n(e)?.event,r=qn(e);if(r)throw r;let o=n?Hn(n):void 0;if(o){if(o.status!=="SUCCESS")throw fo("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw fo("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw lo();return o.response}if(e.length>0)throw lo();let s=t.trim();if(!s)throw lo();return s},extractPartialText(t){let e=bt(t),n=$n(e)?.event;if(!n||n.kind==="agy_error")return;let r=Hn(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=bt(n??""),o=qn(r);return o||(t!==0&&e.trim()?Bn(e):null)},parseResultMeta(t){let e=bt(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!me(c.step.usage))continue;let u=_o(c),p=go(c);if(!u||!Number.isSafeInteger(p))continue;let
|
|
60
|
+
`):""}function sl(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function $i(t){return t.replace(/\s+/g," ").trim()}function il(t,e){let n=t?.description;if(typeof n!="string")return;let r=$i(n);if(!r||r===$i(e))return;if(r.length<=Hi)return r;let o=r.slice(0,Hi-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function al(t,e){let n=e.type;if(n==="text"){let r=String(e.text||"");return r?{timestamp:t,type:"text",content:r}:null}if(n==="thinking"){let r=typeof e.thinking=="string"?e.thinking.trim():"";return r?{timestamp:t,type:"thinking",content:r}:null}if(n==="tool_use"){let r=String(e.name||""),o=e.id,s=e.input,i=Me(s);if(r==="Bash"&&Pe(i))return xe(t,i,o);let a=il(s,i);return {timestamp:t,type:"tool_use",toolUseId:o,toolName:r,toolInput:i,...a?{toolTitle:a}:{}}}if(n==="tool_result"){let r=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
|
|
61
|
+
`):i=JSON.stringify(s),{timestamp:t,type:"tool_result",toolUseId:o,...Le(i,r)}}return null}var Zu,el,to,Hi,no=k(()=>{d();$r();Ve();Gr();Qt();Ct();Nt();Ot();nn();Ye();on();ut();Di();eo();Zu=new Set(["tool_progress"]),el="cli/claude";to={command:"claude",meta:{displayName:"Claude",models:yi(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ct(e.model),s=e.effort??o,i=bi(e.mode),a=Ci(s),c=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...Li(e.builtinAllow)],p=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let _=[...e.additionalArgs];return _.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:Fn}:{args:["--output-format","stream-json","--verbose",...p,...i,...a,...c,...u,..._],stdinMessage:t,env:Fn}}return {args:["-p","--output-format","stream-json","--verbose",...p,...i,...a,...c,...u],stdinMessage:t,env:Fn}},extractText(t){let e=Ui(t);if(e?.is_error===true){let o=to.extractFailure(JSON.stringify(e));if(o)throw o;let s=typeof e.subtype=="string"?e.subtype:"unknown",i=typeof e.terminal_reason=="string"?e.terminal_reason:"unknown";throw new j(Bi(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,el,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Fi(t);if(n)return n;let r=t.trim();return dt(r,"claude")?"":r},extractPartialText(t){return Fi(t)},extractFailure(t){try{let e=JSON.parse(t),n=Gi(e);if(n)return new Jt(n)}catch{}return null},interpretExit(t,e,n){let r=tl(n??"");if(r)return new j(`Claude is not logged in (exit ${t}): ${r}. Sign in to this account with the official "claude auth login".`,"cli/claude",{code:"AUTH_REQUIRED",kind:"config"});let o=Bi(Ui(n??""));return o?new j(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return nl(e)}catch{return}},parseResultMeta(t){let e=t.split(`
|
|
62
|
+
`);for(let r of e)if(r.trim())try{let o=JSON.parse(r);if(o.type==="result"){let s=o.usage,i=s?{inputTokens:Number(s.input_tokens??0)+Number(s.cache_read_input_tokens??0),outputTokens:Number(s.output_tokens??0),cachedInputTokens:Number(s.cache_read_input_tokens??0),costUsd:Number(o.total_cost_usd??0)}:null,a=o.modelUsage,c=a?Object.keys(a)[0]??null:null;return {usage:i,model:c}}}catch{}let n=vi(t);return n?{usage:{inputTokens:n.inputTokens,outputTokens:0,cachedInputTokens:n.cachedInputTokens,costUsd:0},model:n.model??null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];let o=$e(n,e??new Date().toISOString()),s=rl(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];if(r!=="assistant"&&r!=="user")return [];let a=n.message?.content;if(!Array.isArray(a))return [];let c=[];for(let u of a){let p=al(o,u);p&&c.push(p);}return c},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?Zu.has(r):!1}catch{return false}}};Hi=200;});function ji(t){let e=t.split(`
|
|
63
|
+
`).filter(o=>o.trim()),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}var dl,ro=k(()=>{d();Qt();on();Ct();Ot();Nt();Ye();Mn();ut();dl=new Set(["interactive","plan","autopilot"]);({command:"copilot",meta:{displayName:"Copilot",models:Si()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&dl.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Ln.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=ji(t);if(e)return e;let n=t.trim();return dt(n,"copilot")?"":n},extractPartialText(t){return ji(t)},parseResultMeta(t){let e=rn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e){let n;try{n=JSON.parse(t);}catch{return []}let r=n.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let o=n.data;if(!o)return [];let s=$e(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),c=o.arguments,u=Me(c);return (a==="bash"||a==="Bash")&&Pe(u)?[xe(s,u,i)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:u,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Le(String(a.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Le(u,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}});});function ll(t){let e=[],n=0,r=false,o=false,s=0;for(let a=0;a<t.length;a++){let c=t[a];if(o){o=false;continue}if(c==="\\"&&r){o=true;continue}if(c==='"'){r=!r;continue}if(!r){if(c==="{")n++;else if(c==="}"&&(n--,n===0)){let u=t.slice(s,a+1).trim();u&&e.push(u),s=a+1;}}}let i=t.slice(s).trim();return i&&e.push(i),e}function pl(t){return t[0]==="exec"?t.slice(1):t}function Ki(t){let e=t.split(`
|
|
64
|
+
`).map(o=>o.trim()).filter(Boolean),n=[],r=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&n.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}if(n.length>0)return n[n.length-1];if(r)return r}function Je(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function zi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Je(t.error)}function Yi(t){let e=Je(t.error)?t.error:void 0,n=[t.message,t.errorMessage,e?.message,e?.detail,typeof t.error=="string"?t.error:void 0];for(let r of n)if(typeof r=="string"&&r.trim())return r;return t.type==="turn.failed"?"Codex turn failed.":"Codex CLI reported an error."}function _l(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Je(n)&&zi(n))return Yi(n)}}function Vi(t,e,n,r){if(!n||t.type!=="command_execution"&&t.type!=="mcp_tool_call"||typeof t.id!="string"||!t.id.trim()||t.type==="mcp_tool_call"&&e==="item.started"&&(typeof t.server!="string"||typeof t.tool!="string"))return;let o=n.state.get("codex.pending");o||(o=new Map,n.state.set("codex.pending",o));let s=JSON.stringify([t.type,t.id]);if(e==="item.started"){let c=`codex:${JSON.stringify(t.id)}#${n.rowIndex}:${r}`,u=o.get(s)??[];return u.push(c),o.set(s,u),c}let i=o.get(s),a=i?.pop();return i?.length||o.delete(s),a}function gl(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return Pe(o)?[xe(t,o,n)]:[{timestamp:t,type:"tool_use",toolName:"Bash",toolInput:o,...n?{toolUseId:n}:{}}]}return r==="mcp_tool_call"?typeof e.server!="string"||typeof e.tool!="string"?[]:[{timestamp:t,type:"tool_use",toolName:`${e.server}/${e.tool}`,toolInput:Me(e.arguments),...n?{toolUseId:n}:{}}]:[]}function fl(t,e,n){let r=e.type;if(r==="message"||r==="text"){let o=e.content;if(Array.isArray(o))for(let s of o){let i=hl(t,s);if(i)return i}if(typeof e.text=="string")return {timestamp:t,type:"text",content:e.text}}if(r==="agent_message"&&typeof e.text=="string")return {timestamp:t,type:"text",content:e.text};if(r==="reasoning"){let o=typeof e.text=="string"?e.text.trim():"";return o?{timestamp:t,type:"thinking",content:o}:null}if(r==="command_execution"){let o=String(e.aggregated_output||e.output||""),s=!!e.is_error;return {timestamp:t,type:"tool_result",...Le(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Je(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(c=>Je(c)&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
65
|
+
`),a=typeof e.error=="string"?e.error:Je(e.error)&&typeof e.error.message=="string"?e.error.message:"";return {timestamp:t,type:"tool_result",resultPreview:i||a,isError:e.status==="failed"||e.status==="error"||e.is_error===true||e.error!=null,...n?{toolUseId:n}:{}}}if(r==="tool_use"){let o=String(e.name||e.tool_name||""),s=e.input,i=Me(s);return o==="Bash"&&Pe(i)?xe(t,i):{timestamp:t,type:"tool_use",toolName:o,toolInput:i}}if(r==="tool_result"){let o=!!e.is_error,s=String(e.output||e.content||"");return {timestamp:t,type:"tool_result",...Le(s,o)}}if(r==="web_search"){let o=e.action,s;if(o?.type==="search"){let i=o.queries;s=String(o.query||"")||(i?.length?i.join(", "):"")||String(e.query||"");}else s=e.query?"open: "+String(e.query):"";return !s&&!(Je(o)&&o.type==="other"&&e.query==="")?null:{timestamp:t,type:"tool_use",toolName:"WebSearch",toolInput:s}}if(r==="file_change"){let o=e.changes;if(!Array.isArray(o)||o.length===0)return null;let s=o.map(a=>String(a.path||"")).filter(Boolean);if(s.length===0)return null;let i=s.length===1?s[0]:`${s.slice(0,2).join(", ")}${s.length>2?` (+${s.length-2})`:""}`;return {timestamp:t,type:"tool_use",toolName:"Edit",toolInput:i}}return null}function hl(t,e){let n=e.type;if(n==="text")return {timestamp:t,type:"text",content:String(e.text||"")};if(n==="tool_use"){let r=String(e.name||""),o=e.input,s=Me(o);return r==="Bash"&&Pe(s)?xe(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var cl,ul,oo=k(()=>{d();Ve();Qt();on();Ct();Ot();Kr();Nt();nn();Ye();ut();cl=new Set(["turn.started","turn.completed","item.updated"]),ul="cli/codex";({command:"codex",meta:{displayName:"Codex",models:ki(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ct(e.model),s=e.effort??o,i=e.resumeSessionId?Ai(e.mode):Ti(e.mode),a=Ii(s),c=r?["-m",r]:[],u=pl(e.additionalArgs??[]),f=u.includes("--json")||u.includes("--experimental-json")?[]:["--json"];return e.resumeSessionId?{args:["exec","resume",...f,...i,...a,...c,...u,e.resumeSessionId,"-"],stdinMessage:t}:{args:["exec",...f,...i,...a,...c,...u],stdinMessage:t}},extractText(t){let e=_l(t);if(e)throw new j(e,ul);let n=Ki(t);if(n)return n;let r=t.trim();return dt(r,"codex")?"":r},extractPartialText(t){return Ki(t)},parseResultMeta(t){let e=rn(t);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(t,e,n){let r=e??new Date().toISOString(),o=[],s;try{JSON.parse(t),s=[t];}catch{s=ll(t),s.length>1&&console.warn("[codex] parseEvent: falling back to concatenated-JSON split for a malformed line");}for(let[i,a]of s.entries()){let c;try{c=JSON.parse(a);}catch{continue}if(!Je(c))continue;let u=c.type;if(!u)continue;let p=$e(c,r);if(zi(c)){let _=Yi(c);o.push({timestamp:p,type:"error",content:_,errorMessage:_});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Wr(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let f=c.item;if(f){if(u==="item.started"){o.push(...gl(p,f,Vi(f,u,n,i)));continue}if(u==="item.completed"){let _=fl(p,f,Vi(f,u,n,i));_&&o.push(_);continue}}}return o},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?cl.has(r):!1}catch{return false}}});});var Xi=k(()=>{d();});var Qi=k(()=>{d();});function yl(t){let e=t.match(/(?:^|[^0-9])([0-9]{1,5})(?![0-9])/);if(!e)return null;let n=Number(e[1]);return Number.isInteger(n)&&n>0&&n<=65535?n:null}function kl(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),Zi),n.unref();try{child_process.execFile("chcp.com",[],{encoding:"ascii",timeout:Zi,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(yl(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function Sl(){return process.platform!=="win32"?Promise.resolve(null):(Un||(Un=kl(),Un.then(t=>{},()=>{})),Un)}function wl(){process.platform==="win32"&&Sl();}var Zi,Un,ta=k(()=>{d();Zi=1e3;wl();});var so=k(()=>{d();});var na=k(()=>{d();});var io=k(()=>{d();Ve();so();na();});var ra=k(()=>{d();ao();Qi();ta();so();io();Ye();});var co=k(()=>{d();Ve();Xi();on();Ot();ut();ra();io();});var oa=k(()=>{d();});function Dt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function vl(t,e){return t&&sa.has(t)||Dt(e,"--dangerously-skip-permissions")?true:e.some((n,r)=>{let o=n==="--mode"?e[r+1]:n.startsWith("--mode=")?n.slice(7):void 0;return typeof o=="string"&&sa.has(o)})}function Dl(t,e){let n=[];for(let r=0;r<t.length;r+=1){let o=t[r],s=[...e].find(i=>o===i||o.startsWith(`${i}=`));s?o===s&&r+1<t.length&&(r+=1):n.push(o);}return n}function Pl(t){let e=[];for(let n=0;n<t.length;n+=1){let r=t[n],o=r.indexOf("="),s=o>0?r.slice(0,o):r;if(!Nl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function me(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xl(t,e){if(!(t?Cl.has(t)||ze(uo).some(s=>s.id===t):false)||!t)return e;let r=tn(uo,t),o=Qr(uo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function Ge(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function _o(t){return t.kind==="step_update"?typeof t.step.conversation_id=="string"?t.step.conversation_id:void 0:typeof t.envelope.conversation_id=="string"?t.envelope.conversation_id:void 0}function go(t){return t.step.step_index}function $(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Dn(e)?.slice(0,500).trim()||void 0}function Ll(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Ol.has(n))return n;let r=`${n} ${e??""}`.toLowerCase();return /quota|resource_exhausted|usage[ _-]?limit|credits?.{0,20}exhaust/.test(r)?"QUOTA_EXHAUSTED":/rate[ _-]?limit|throttl/.test(r)?"RATE_LIMITED":/auth|sign[ _-]?in|log(?:ged)?[ _-]?in|unauthori[sz]ed|credential/.test(r)?"AUTH_REQUIRED":[/unknown (?:flag|option)/,/flag provided but not defined/,/unrecognized (?:flag|option)/,/invalid value for (?:flag|option)/,/invalid (?:flag|option)/].some(s=>s.test(r))?"INVALID_PROVIDER_FORMAT":/invalid.{0,24}model|model.{0,24}(unknown|unavailable|not found|not recognized)|config/.test(r)?"MODEL_UNAVAILABLE":"UNKNOWN"}function Ml(t){return t==="AUTH_REQUIRED"||t==="TIMEOUT_IDLE"||t==="TIMEOUT_TOTAL"||t==="TIMEOUT_RESUME"||t==="PROVIDER_CRASHED"?"permanent":t==="MODEL_UNAVAILABLE"||t==="INVALID_PROVIDER_FORMAT"||t==="PROVIDER_NOT_FOUND"?"config":"transient"}function da(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=e?$(e.code)??$(e.error_code)??$(n?.code)??$(n?.error_code):void 0,o=typeof t=="string"?$(t):e?$(e.message)??$(e.error)??$(e.reason)??$(n?.message)??$(n?.error)??$(n?.reason):void 0,s=Ll(r,o),i=e?Ge(e.retry_after_ms)??Ge(e.retryAfterMs)??Ge(n?.retry_after_ms)??Ge(n?.retryAfterMs):void 0;return {code:s,kind:Ml(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Bn(t){let e=da(t);return new j(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function fo(t){return new j(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Fl(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=po))throw new j(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${po} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function lo(){return new j("Antigravity CLI returned empty output with exit code 0. agy may have hidden an auth/quota/model error in its log file; inspect ~/.gemini/antigravity-cli/log for details.","cli/antigravity",{code:"EMPTY_OUTPUT",kind:"transient"})}function Hn(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function $n(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n&&(n.kind==="result"||n.kind==="legacy_result"||n.kind==="agy_error"))return {event:n,index:e}}}function Ul(t){let e=$n(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||Hn(e.event)?.status!=="SUCCESS"||qn(t))return false;let r=new Map;for(let o of t){if(o.kind!=="step_update"||o.step.step_type!=="agent_response")continue;let s=_o(o),i=go(o);!s||!Number.isSafeInteger(i)||r.set(JSON.stringify([s,i]),o.step);}if(r.size===0)return false;for(let o of r.values())if(o.state!=="DONE"||!me(o.usage)||Ge(o.usage.input_tokens)===void 0||Ge(o.usage.output_tokens)===void 0)return false;return true}function ql(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function Bl(t,e){return me(t)&&me(e)?{...e,...t}:me(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&me(e)?{...e,message:t}:t??e}function Hl(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=me(i)?i:void 0,c=typeof i=="string"?$(i):$(a?.display_name)??$(a?.action);c&&!n.includes(c)&&n.length<5&&n.push(c.slice(0,80));}let r=Math.max(0,e.length-n.length),o=n.length>0?` (${n.join(", ")}${r>0?`, +${r} more`:""})`:"",s=`Permission denied: Antigravity blocked ${e.length} requested action${e.length===1?"":"s"}${o}.`;return new j("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function qn(t){let e=$n(t);if(!e)return;if(e.event.kind==="agy_error")return Bn(e.event.error);let n=Hn(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Hl(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return fo("Antigravity returned a result with an unsupported status.");let r=n.error,o=Bl(r==null||r===""?n:r,ql(t,e.index));return Bn(o)}function ca(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function $l(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function Gl(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function ua(t){let e=ca(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function jl(t){let e=me(t)?t:void 0,n=e&&me(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=($(e?.type)??$(e?.code)??$(e?.error_type)??$(n?.type)??$(n?.code)??$(n?.error_type)??$(r)??"TOOL_ERROR").slice(0,60),s=da(t).message.slice(0,250);return ua({type:o,message:s})??"Antigravity reported a tool error."}function ia(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function aa(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var uo,Cl,Nl,sa,po,Ol,ho=k(()=>{d();Ve();oa();Gr();Zt();Ye();nn();xn();eo();uo="antigravity",Cl=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Nl=new Set(["--conversation","--resume","--continue"]),sa=new Set(["bypassPermissions","agent-full-access","yolo"]),po=18e4,Ol=new Set(["QUOTA_EXHAUSTED","RATE_LIMITED","EMPTY_OUTPUT","AUTH_REQUIRED","MODEL_UNAVAILABLE","TIMEOUT_IDLE","TIMEOUT_TOTAL","TIMEOUT_RESUME","PROVIDER_NOT_FOUND","INVALID_PROVIDER_FORMAT","PROVIDER_CRASHED","UNKNOWN"]);({command:"agy",maxInitialInputBytes:po,meta:{displayName:"Antigravity",models:wi(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Xt(t);if(e?.kind!=="init")return null;let n=e.envelope.conversation_id;return typeof n=="string"&&n.trim().length>0?n.trim():null},buildArgs(t,e,n){Fl(t);let{model:r,effort:o}=ct(e.model),s=Jr(r),i=s.model,a=e.effort??o??s.effort,c=xl(i,a),u=e.additionalArgs??[],p=Pl(Dl(u,new Set(["--input-format","--output-format"]))),f=i&&!Dt(u,"--model")?["--model",i]:[],_=Dt(u,"--effort")?[]:Oi(c),S=Dt(u,"--mode")||Dt(u,"--dangerously-skip-permissions")?[]:Ni(e.mode),w=vl(e.mode,u)||Dt(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Mi(e.builtinAllow)}})],E=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...f,..._,...S,...E,...w,...p],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
66
|
+
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=bt(t),n=$n(e)?.event,r=qn(e);if(r)throw r;let o=n?Hn(n):void 0;if(o){if(o.status!=="SUCCESS")throw fo("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw fo("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw lo();return o.response}if(e.length>0)throw lo();let s=t.trim();if(!s)throw lo();return s},extractPartialText(t){let e=bt(t),n=$n(e)?.event;if(!n||n.kind==="agy_error")return;let r=Hn(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=bt(n??""),o=qn(r);return o||(t!==0&&e.trim()?Bn(e):null)},parseResultMeta(t){let e=bt(t),n=0,r=0,o=0,s=0,i=new Set;for(let c of e){if(c.kind!=="step_update"||c.step.state!=="DONE"||!me(c.step.usage))continue;let u=_o(c),p=go(c);if(!u||!Number.isSafeInteger(p))continue;let f=JSON.stringify([u,p]);if(i.has(f))continue;let _=c.step.usage,S=Ge(_.input_tokens),w=Ge(_.output_tokens);if(S===void 0||w===void 0)continue;i.add(f);let E=Ge(_.cache_read_tokens)??0;n+=S+E,r+=w,o+=E,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:Ul(e)},model:null}},parseEvent(t,e,n){let r=Xt(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [aa(o,Bn(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let S=qn([r]);return S?[aa(o,S)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=_o(r)??"unknown",a=go(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&ia(n,`antigravity:terminal:${c}`))return [];if(s.step_type==="agent_response")return typeof s.text_delta=="string"&&s.text_delta.length>0?[{timestamp:o,type:"text",content:s.text_delta}]:[];if(s.step_type!=="tool")return [];let u=me(s.tool_info)?s.tool_info:void 0,p=Gl(s,u);if(!p)return [];let f=$l(s);if(s.state==="ACTIVE"){if(ia(n,`antigravity:active:${c}`))return [];let S=ca(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:p,toolUseId:f,...S===void 0?{}:{toolInput:S}}]}let _=s.state==="ERROR"?jl(u?.error):ua(u?.output);return [{timestamp:o,type:"tool_result",toolName:p,toolUseId:f,..._===void 0?{}:{resultPreview:_},...s.state==="ERROR"?{isError:true}:{}}]}});});var pa=k(()=>{d();Ct();Ot();Nt();ut();});var mo=k(()=>{d();Ve();$r();Ye();Nt();nn();ut();});var ao=k(()=>{d();no();ro();oo();co();ho();pa();mo();no();ro();oo();co();ho();mo();Ct();});var _a=k(()=>{d();ai();ao();});var yo=k(()=>{d();_a();On();});var sn,lt=k(()=>{d();sn=["success","completed","done","failed","error","stopped","runner_lost"];});var an=k(()=>{d();});var So=k(()=>{d();Hr();an();});var sp,Pt=k(()=>{d();P();M();q();L();F();Tt();On();Br();Hr();vn();Fr();yo();lt();an();So();an();Tt();sp="0.8.9-rc.13",parseInt(sp.split("rc.")[1]),new Set(sn);});d();d();d();var T="workout-log",Xe="workout-log.records.v1",pt=500,Kn=100,Vn=4096,Lt=6e4,zn=200,Mt=20,dn=6e4;d();var Ft=class{epoch=0;activeSession=null;grantControllers=new Map;get activeAccountKey(){return this.activeSession?.accountKey??null}get activeSessionEpoch(){let e=this.activeSession;return e&&!e.controller.signal.aborted?e.epoch:null}currentToken(e){let n=this.activeSession;return !n||n.accountKey!==e||n.controller.signal.aborted?null:this.toSessionToken(n)}activate(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("INVALID_ACCOUNT_KEY");if(this.activeSession?.accountKey===e&&!this.activeSession.controller.signal.aborted)return this.toSessionToken(this.activeSession);this.abortActiveSession();let n={accountKey:e,epoch:++this.epoch,controller:new AbortController};return this.activeSession=n,this.toSessionToken(n)}captureGrant(e,n,r){if(!this.isCurrent(e))throw new Error("APP_SYNC_SESSION_STALE");if(!n||!Number.isSafeInteger(r)||r<1)throw new Error("INVALID_GRANT_FENCE");let o=new AbortController,s=this.grantKey(e.accountKey,n,r),i=()=>o.abort(e.signal.reason);e.signal.aborted?i():e.signal.addEventListener("abort",i,{once:true});let a=this.grantControllers.get(s)??new Set;return a.add({controller:o,sessionSignal:e.signal,onSessionAbort:i}),this.grantControllers.set(s,a),{accountKey:e.accountKey,epoch:e.epoch,grantId:n,generation:r,signal:o.signal}}isCurrent(e){let n=this.activeSession;return n!==null&&n.accountKey===e.accountKey&&n.epoch===e.epoch&&!n.controller.signal.aborted&&!e.signal.aborted}release(e){let n=this.grantKey(e.accountKey,e.grantId,e.generation),r=this.grantControllers.get(n);if(r){for(let o of r)o.controller.signal===e.signal&&(o.sessionSignal.removeEventListener("abort",o.onSessionAbort),r.delete(o));r.size===0&&this.grantControllers.delete(n);}}cancelGrant(e,n,r){let o=this.grantKey(e,n,r),s=this.grantControllers.get(o);if(s){for(let i of s)i.sessionSignal.removeEventListener("abort",i.onSessionAbort),i.controller.abort("grant_invalidated");this.grantControllers.delete(o);}}suspend(e){this.activeSession&&(e===void 0||this.activeSession.accountKey===e)&&(this.abortActiveSession(),this.epoch+=1);}toSessionToken(e){return {accountKey:e.accountKey,epoch:e.epoch,signal:e.controller.signal}}abortActiveSession(){let e=this.activeSession;if(e){e.controller.abort("session_suspended");for(let[n,r]of this.grantControllers)if(n.startsWith(`${e.accountKey}:${e.epoch}:`)){for(let o of r)o.sessionSignal.removeEventListener("abort",o.onSessionAbort),o.controller.abort("session_suspended");this.grantControllers.delete(n);}this.activeSession=null;}}grantKey(e,n,r){return `${e}:${this.activeSession?.epoch??this.epoch}:${n}:${r}`}};d();var Da=Xe,_e=Object.freeze({root:"docs/apps/workout-log",include:Object.freeze(["exercises.md","routines/<id>.md","workouts/<YYYY-MM-DD>-<id>.md"]),idPattern:"^[A-Za-z0-9_-]{1,40}$",exclude:Object.freeze(["migration/**","*.json","app-state/**",".*","*~","*.tmp","*.swp","*.part",".env*","auth.json","*.key","*.pem"])}),Yn=Object.freeze({exactFiles:Object.freeze(["exercises.md"]),directFolders:Object.freeze(["routines","workouts"]),suffix:".md",maxDepth:1}),Pa=/^[A-Za-z0-9_-]{1,40}$/,No=["root","include","idPattern","exclude"];function Oo(t,e){return Array.isArray(t)&&t.length===e.length&&t.every((n,r)=>n===e[r])}function xa(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function La(t){if(t==="exercises.md")return "exercises";if(/^routines\/[A-Za-z0-9_-]{1,40}\.md$/.test(t))return "routine";let e=/^workouts\/(\d{4})-(\d{2})-(\d{2})-([A-Za-z0-9_-]{1,40})\.md$/.exec(t);if(!e||!Pa.test(e[4]))return null;let[,n,r,o]=e,s=Number(n),i=Number(r),a=Number(o);if(s<1||i<1||i>12||a<1||a>31)return null;let c=new Date(0);return c.setUTCHours(0,0,0,0),c.setUTCFullYear(s,i-1,a),c.getUTCFullYear()!==s||c.getUTCMonth()!==i-1||c.getUTCDate()!==a?null:"workout"}function Ma(t){let n=t.trim().replace(/[ \t]+#.*$/,"").trim();return /^[A-Za-z0-9_-]+$/.test(n)?n:/^"[A-Za-z0-9_-]+"$/.test(n)||/^'[A-Za-z0-9_-]+'$/.test(n)?n.slice(1,-1):null}function Fa(t){if(typeof t!="string")return null;let e=t.indexOf(`
|
|
67
67
|
`);if((e<0?t:t.slice(0,e)).replace(/\r$/,"")!=="---")return null;let r=new Map,o=e<0?t.length:e+1;for(;o<=t.length;){let s=t.indexOf(`
|
|
68
|
-
`,o),i=s<0?t.length:s,a=t.slice(o,i);a.endsWith("\r")&&(a=a.slice(0,-1));let c=s<0?i:s+1;if(Buffer.byteLength(t.slice(0,c),"utf8")>4096)return null;if(a==="---")return r.has("crewx_app")&&r.has("kind")?r:null;let u=/^(crewx_app|kind):[ \t]*(.*)$/.exec(a);if(u){let p=u[1];if(r.has(p))return null;let
|
|
68
|
+
`,o),i=s<0?t.length:s,a=t.slice(o,i);a.endsWith("\r")&&(a=a.slice(0,-1));let c=s<0?i:s+1;if(Buffer.byteLength(t.slice(0,c),"utf8")>4096)return null;if(a==="---")return r.has("crewx_app")&&r.has("kind")?r:null;let u=/^(crewx_app|kind):[ \t]*(.*)$/.exec(a);if(u){let p=u[1];if(r.has(p))return null;let f=Ma(u[2]);if(f===null)return null;r.set(p,f);}if(s<0)break;o=s+1;}return null}var Ut=class{scopeVersion=Xe;definition=_e;matchesDefinition(e,n){return e!==Da||!xa(n)||Object.keys(n).length!==No.length||!No.every(r=>Object.hasOwn(n,r))?false:n.root===_e.root&&n.idPattern===_e.idPattern&&Oo(n.include,_e.include)&&Oo(n.exclude,_e.exclude)}validateRef(e){if(typeof e!="string"||e.length===0||e.length>256)return {valid:false,reason:"out_of_scope"};if(e.includes("\0")||e.includes("\\")||e.startsWith("/")||e.startsWith("~"))return {valid:false,reason:"out_of_scope"};if(e.split("/").some(o=>o===""||o==="."||o===".."))return {valid:false,reason:"out_of_scope"};if(e.startsWith(".")||/(?:^|\/)\./.test(e)||/(?:^|\/)[^/]*(?:~|\.tmp|\.swp|\.part)$/.test(e))return {valid:false,reason:"out_of_scope"};if(/(?:^|\/)(?:auth\.json|[^/]*\.key|[^/]*\.pem)$/.test(e)||/\.env[^/]*$/.test(e))return {valid:false,reason:"out_of_scope"};let r=La(e);return r===null?{valid:false,reason:"out_of_scope"}:{valid:true,kind:r}}validateFrontMatter(e,n){let r=this.validateRef(e);if(!r.valid)return {valid:false,reason:"invalid_front_matter"};let o=Fa(n);return o?o.get("crewx_app")!==T?{valid:false,reason:"app_mismatch"}:o.get("kind")!==r.kind?{valid:false,reason:"kind_mismatch"}:{valid:true,kind:r.kind}:{valid:false,reason:"invalid_front_matter"}}};function U(t){return `sha256:${crypto.createHash("sha256").update(t,"utf8").digest("hex")}`}function _t(t){if(!Array.isArray(t)||t.length===0||t.length>64)return null;let e=[];for(let n of t){if(typeof n!="string"||n.length===0)return null;let r=n.normalize("NFC");if(r==="."||r===".."||r.includes("/")||r.includes("\\")||r.includes("\0")||/^[A-Za-z]:$/.test(r)||r.startsWith("~"))return null;e.push(r);}return e}d();d();var qa=10*6e4,Ba=5e3,je=class extends Error{constructor(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("INVALID_APP_SYNC_BUDGET_RETRY_AT");super("APP_SYNC_BUDGET_DEFERRED");this.retryAt=n;this.name="AppSyncBudgetDeferredError";}retryAt;code="APP_SYNC_BUDGET_DEFERRED"},Jn=class{constructor(e){this.sqlite=e;if(!e||typeof e.prepare!="function"||typeof e.transaction!="function")throw new Error("INVALID_DOC_CREATE_LEDGER_DATABASE")}sqlite;peek(e,n){Xn(e),cn(n),this.deleteExpired(n);let r=this.readWindow(e,n);return r.count<20?{available:true,remaining:20-r.count}:{available:false,retryAt:vo(r,n)}}reserve(e){return Do(e),this.sqlite.transaction(r=>{this.deleteExpired(r.now);let o=this.readWindow(r.accountKey,r.now);return o.count>=20?{ok:false,retryAt:vo(o,r.now)}:(this.insert(r),{ok:true})}).immediate(e)}reserveForced(e){Do(e),this.deleteExpired(e.now),this.insert(e);}prune(e){return cn(e),this.deleteExpired(e)}readWindow(e,n){let r=this.sqlite.prepare(`
|
|
69
69
|
SELECT COUNT(*) AS count, MIN(dispatched_at) AS oldest
|
|
70
70
|
FROM doc_create_dispatches
|
|
71
71
|
WHERE account_key = ? AND dispatched_at > ?
|
|
72
72
|
`).get(e,n-6e4);if(!r||!Number.isSafeInteger(r.count)||r.count<0||r.oldest!==null&&!Number.isSafeInteger(r.oldest))throw new Error("DOC_CREATE_LEDGER_READ_INVALID");return r}insert(e){this.sqlite.prepare(`
|
|
73
73
|
INSERT INTO doc_create_dispatches (dispatch_id, request_id, account_key, source, dispatched_at)
|
|
74
74
|
VALUES (?, ?, ?, ?, ?)
|
|
75
|
-
`).run(crypto.randomUUID(),e.requestId,e.accountKey,e.source,e.now);}deleteExpired(e){return this.sqlite.prepare("DELETE FROM doc_create_dispatches WHERE dispatched_at <= ?").run(e-qa).changes}};function qt(t){if(Xn(t.accountKey),Po(t.requestId),xo(t.source),typeof t.now!="function"||typeof t.ledger?.peek!="function"||typeof t.ledger.reserve!="function"||typeof t.ledger.reserveForced!="function"||typeof t.ledger.prune!="function"||t.guard!==void 0&&typeof t.guard!="function")throw new Error("INVALID_DOC_CREATE_DISPATCH_GATE");let e=0,n=(()=>{e+=1;let r=t.guard?.();if(r!=null&&typeof r.then=="function")throw Promise.resolve(r).catch(()=>{}),new Error("APP_SYNC_DISPATCH_GUARD_MUST_BE_SYNCHRONOUS");let o=t.now();cn(o);try{let s=t.ledger.reserve({accountKey:t.accountKey,requestId:t.requestId,source:t.source,now:o});if(s.ok===!0||s.ok===!1&&Number.isSafeInteger(s.retryAt)&&s.retryAt>=0)return s;throw new Error("DOC_CREATE_LEDGER_DECISION_INVALID")}catch{throw new je(o+Ba)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function vo(t,e){if(t.oldest===null)throw new Error("DOC_CREATE_LEDGER_WINDOW_EMPTY");let n=t.oldest+6e4;if(!Number.isSafeInteger(n)||n<e)throw new Error("DOC_CREATE_LEDGER_RETRY_AT_INVALID");return n}function Do(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Xn(t.accountKey),Po(t.requestId),xo(t.source),cn(t.now);}function Xn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function Po(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function xo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function cn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var Lo=1e4,$a=12e4,ln=class{constructor(e,n,r,o,s,i){this.dependencies=e;this.scopeRegistry=n;this.sessionFence=r;this.now=o;this.createId=s;this.hasPendingRevoke=i;if(!e.continuation)throw new Error("APP_SYNC_CONTINUATION_CAPABILITY_REQUIRED");if(!e.remote.listGrantDocs||!e.remote.listDeletedRefs||!e.documents.inspectContinuation||!e.documents.applyContinuation)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");this.continuation=e.continuation,this.continuationStore=e.continuation.store;let a=e.continuation.pageSize??100;if(!Number.isSafeInteger(a)||a<1)throw new Error("APP_SYNC_CONTINUATION_PAGE_SIZE_INVALID");this.pageSize=Math.min(a,200);}dependencies;scopeRegistry;sessionFence;now;createId;hasPendingRevoke;continuation;continuationStore;pageSize;async tick(e,n,r,o,s){let i=this.createFenceContext(e,n,r,o);i.fence.assertCurrent(),!(this.continuationStore.beginDiscoveryCycle({binding:e,fence:i.fence,now:this.now()})&&!await this.traverseWithCursorRecovery(i))&&(i.fence.assertCurrent(),await this.processPendingDiscoveries(i));}listConflicts(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n||!e.session.authenticated||e.session.accountKey!==n.accountKey||n.workspaceId!==e.workspaceId||!Mo(n.rootSegments,e.resolvedRootSegments))return [];let r=this.sessionFence.currentToken(n.accountKey);return !r||this.sessionFence.activeAccountKey!==n.accountKey||this.hasPendingRevoke(n.bindingId)?[]:this.continuationStore.listConflicts(n.bindingId).map(({vaultHandle:o,...s})=>({...s,sessionEpoch:r.epoch}))}assertHumanBindingIdentity(e,n){if(ja({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Mo(e.rootSegments,n.resolvedRootSegments))throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new f("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new f("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404);return this.assertHumanBindingIdentity(n,e),n}async readConflictArchive(e){let n=this.requireHumanOperationBinding(e),r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new f("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new f("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);let s=this.archiveFenceGrant(n,o),i=this.createArchiveFenceContext(n,s,r);try{i.fence.assertCurrent();let a=await this.readVerifiedArchive(o,i);return {conflictId:o.conflictId,localVersion:o.localVersion,localFingerprint:o.localFingerprint,remoteRevision:o.remoteRevision,remoteFingerprint:o.remoteFingerprint,markdown:a}}finally{this.sessionFence.release(i.grantToken);}}async purgeAccountData(e){Wa(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new f("APP_SYNC_SESSION_STALE");let r=ae(JSON.stringify(e.resolvedRootSegments)),o=this.continuationStore.getAccountDataPurge(e.requestId);if(o&&(o.bindingId!==e.bindingId||o.accountKey!==e.session.accountKey||o.workspaceId!==e.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity))throw new f("APP_SYNC_PURGE_REQUEST_ID_REUSED",409);let s=this.dependencies.store.getBinding(e.bindingId);if(!s){if(o?.state==="complete")return {requestId:e.requestId,status:"purged",remainingArchiveCount:0};throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new f("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),p=u;try{this.continuationStore.beginAccountDataPurge({requestId:e.requestId,binding:s,humanIdentity:e.humanIdentity,fence:u.fence,now:this.now()}),s.grantId&&s.grantGeneration&&this.sessionFence.cancelGrant(s.accountKey,s.grantId,s.grantGeneration),this.sessionFence.release(u.grantToken),p=this.createArchiveFenceContext(s,a,i,c);let g=this.continuationStore.listConflicts(s.bindingId);for(let _ of g)try{p.fence.assertCurrent();let S=_.state==="purging"?_:this.continuationStore.markConflictPurging({conflictId:_.conflictId,fence:p.fence,now:this.now()});S.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:S.vaultHandle,fence:p.fence}),p.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:S.conflictId,expectedVaultHandle:S.vaultHandle,fence:p.fence,now:this.now()});}catch(S){if(!this.isFenceCurrent(p))throw S;let w=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:w}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:p.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),p!==u&&this.sessionFence.release(p.grantToken);}}async resolveConflict(e){Ka(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new f("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new f("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let o=er(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new f("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,o.grantId,o.generation),i=this.createFenceContext(n,o,r,s);try{i.fence.assertCurrent();let a=this.continuationStore.getConflict(e.conflictId);if(!a)throw new f("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(a,n),a.state==="purging")throw new f("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new f("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new f("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);this.continuationStore.beginConflictResolution({conflictId:a.conflictId,requestId:e.requestId,humanIdentity:e.humanIdentity,choice:e.choice,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,fence:i.fence,now:this.now()});let u=await this.applyHumanResolution(e,a,i);if(u.status==="stale")throw this.continuationStore.abortConflictResolution({conflictId:a.conflictId,requestId:e.requestId,state:"stale",errorCode:"APP_SYNC_CONFLICT_STALE",fence:i.fence,now:this.now()}),u.refreshed?await this.preserveConflict(tr(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new f("APP_SYNC_CONFLICT_STALE",409);let p=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(p,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Fe(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):Va(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:Zn(a),fence:i.fence,now:this.now()}));}throw a}finally{this.sessionFence.release(s);}}async dispatchReattachCreation(e,n,r,o,s){if(!o.documentId||o.operationKind!=="reattach"||o.bindingId!==e.bindingId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(this.hasPendingRevoke(e.bindingId)||!this.sessionFence.isCurrent(r))return;if(this.dependencies.createLedger)try{let u=this.dependencies.createLedger.peek(e.accountKey,this.now());if(!u.available||u.remaining<1)return}catch(u){this.dependencies.onAdapterError?.(u);return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),$a);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.createFenceContext(e,n,r,a);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,ae(o.ref))){this.dependencies.store.updateCreation(o.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}let u=await this.readRemoteDocument(o.documentId,c);if(U(u.markdown)!==o.fingerprint||u.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,u.markdown).valid){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}if(u.appGrantId===n.grantId&&u.appGrantGeneration===n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);return}let p=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let S=await this.readRemoteDocument(o.documentId,c);if(U(S.markdown)!==o.fingerprint||S.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,S.markdown).valid)return {kind:"changed"};let w=this.dependencies.createLedger?qt({ledger:this.dependencies.createLedger,accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now,guard:()=>{if(c.fence.assertCurrent(),this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING")}}):void 0,E;try{E=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:T,ref:o.ref,requestId:o.requestId,markdown:S.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...w?{dispatchGate:w}:{}});}catch(R){if(R instanceof je)return {kind:"budget_deferred",retryAt:R.retryAt};throw R}if(w&&w.calls===0){let R=new f("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(I){this.dependencies.onAdapterError?.(I);}throw this.dependencies.onAdapterError?.(R),R}return c.fence.assertCurrent(),{kind:"created",created:E}}});if(c.fence.assertCurrent(),p.status==="deferred"){let S=this.now();return this.deferClaim(i,p.retryAt,S),void 0}if(p.value.kind==="budget_deferred"){let S=this.now();return this.deferClaim(i,p.value.retryAt,S),void 0}if(p.value.kind==="changed"){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let g=p.value.created;if(g.docId!==o.documentId||g.appGrantId!==n.grantId||g.appGrantGeneration!==n.generation||g.markdownVersion!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let _=await this.readRemoteDocument(o.documentId,c);if(_.appGrantId!==n.grantId||_.appGrantGeneration!==n.generation||_.markdownVersion!==o.fingerprint||U(_.markdown)!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);}catch(u){if(!this.isFenceCurrent(c))return;if(gt(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let p=za(u);this.dependencies.store.updateCreation(o.jobId,{status:p?"waiting":"failed",nextAttemptAt:p?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),p&&this.markPendingForReconcile(e,n,o.ref,c,"APP_SYNC_REATTACH_RESPONSE_UNKNOWN");}finally{this.sessionFence.release(a);}}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}async traverseWithCursorRecovery(e){let n=0;for(;;)try{return await this.traverseGrantDocs(e),await this.traverseDeletedRefs(e),!0}catch(r){if(!Ya(r))throw r;let o=await this.readActiveGrant(e);if(this.continuationStore.resetDiscoveryCycle({binding:e.binding,fence:e.fence,now:this.now()}),!o)return false;if(n+=1,n>1)throw r}}async traverseGrantDocs(e){let n=this.dependencies.remote.listGrantDocs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.docsComplete)return;let i=s.docsCursor;if(i!==null){if(r.has(i))throw new f("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateGrantDocsPage(a,e),a.items.length>this.pageSize)throw new f("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new f("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new f("APP_SYNC_DOCS_TRAVERSAL_LIMIT");this.continuationStore.commitGrantDocsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}async traverseDeletedRefs(e){let n=this.dependencies.remote.listDeletedRefs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.deletedComplete)return;let i=s.deletedCursor;if(i!==null){if(r.has(i))throw new f("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateDeletedRefsPage(a,e),a.items.length>this.pageSize)throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new f("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new f("APP_SYNC_DELETED_REFS_TRAVERSAL_LIMIT");this.continuationStore.commitDeletedRefsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}validateGrantDocsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new f("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!J(o.docId,128)||!J(o.title,80)||!Number.isSafeInteger(o.currentRevision)||o.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(o.markdownVersion)||!Number.isSafeInteger(o.appGrantGeneration)||o.appGrantGeneration<1||o.appGrantGeneration>n.grant.generation||typeof o.needsReattach!="boolean"||!un(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new f("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new f("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!un(o.deletedAt)||r.has(o.refHash))throw new f("APP_SYNC_DELETED_REFS_PAGE_INVALID");r.add(o.refHash);}}async readActiveGrant(e){e.fence.assertCurrent();let n=await this.dependencies.remote.readGrant({accountKey:e.binding.accountKey,appId:T,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==T||n.available!==true||n.status!=="active"||!n.grant?false:n.grant.grantId===e.grant.grantId&&n.grant.generation===e.grant.generation&&n.grant.scopeVersion===e.grant.scopeVersion&&this.scopeRegistry.matchesDefinition(n.grant.scopeVersion,n.grant.scope)}async processPendingDiscoveries(e){let n=this.continuationStore.listPendingDiscoveries(e.binding.bindingId,e.grant.grantId,e.grant.generation,500);for(let r of n){if(!this.isFenceCurrent(e))return;try{this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"processing",errorCode:null},now:this.now()});let o=await this.reconcileDiscoveredDocument(r,e);if(o==="complete")this.continuationStore.completePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence});else if(o==="retry")this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",attempts:r.attempts+1},now:this.now()});else {this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:"DOC_APP_GRANT_REQUIRED"},now:this.now()});return}}catch(o){if(!this.isFenceCurrent(e))return;if(gt(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o)},now:this.now()});return}this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o),needsReconcile:true,attempts:r.attempts+1},now:this.now()});}}}async reconcileDiscoveredDocument(e,n){if(n.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(n.binding.accountKey,T,ae(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(E=>E.accountKey===n.binding.accountKey&&E.ref===e.ref);if(r.exists){if(o.some(I=>I.state==="kept_both"&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint))return "complete";let R=o.find(I=>(I.state==="open"||I.state==="resolving")&&I.preservationStatus==="ready"&&I.vaultHandle!==null&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint&&I.documentId===e.docId&&I.remoteRevision===e.listedRevision&&I.remoteFingerprint===e.listedFingerprint);if(R)return R.state==="open"&&(R.grantId!==n.grant.grantId||R.grantGeneration!==n.grant.generation||R.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:R.conflictId,grant:n.grant,needsReattach:e.needsReattach,fence:n.fence,now:this.now()}),"complete"}let s=r.baseline,i=s!==null&&r.exists&&r.localFingerprint!==s.markdownVersion,a=s!==null&&(e.listedRevision!==s.revision||e.listedFingerprint!==s.markdownVersion);if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&!i)return "complete";if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&i)return this.applyConditionalSave(e.ref,e.docId,r,e.listedRevision,e.listedFingerprint,false,n);let c=await this.readPendingDocument(e,n);if(!c)return "complete";let u=c,p=e;if(e.needsReattach){let E=await this.queueOrConfirmReattachment(e,c,n);if(!E)return "retry";u=E.document,p=E.pending;}let g=await this.inspectLocal(e.ref,n);if(g.exists&&g.localFingerprint===u.markdownVersion){let E={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:g.localVersion,expectedLocalFingerprint:g.localFingerprint,fence:n.fence},R=await this.applyEffect(E,n);if(R.status==="applied")return this.recordOutcome(n,e.ref,g.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(R.status==="stale_local")return this.reconcileAfterLocalRace(p,u,n);if(R.status==="conflict")return this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n);if(R.status==="deferred"||R.status==="failed")return "retry"}let _=g.baseline??s;if(!g.exists){let E={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!_)return this.preserveConflict(p,g,u,n);let S=g.localFingerprint!==_.markdownVersion,w=u.currentRevision!==_.revision||u.markdownVersion!==_.markdownVersion;if(S&&w)return this.preserveConflict(p,g,u,n);if(w&&!S){let E={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:g.localVersion,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}return S&&!w?this.applyConditionalSave(e.ref,u.docId,g,u.currentRevision,u.markdownVersion,p.needsReattach,n):"complete"}async inspectLocal(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.inspectContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=await r({binding:n.binding,grant:n.grant,ref:e,fence:n.fence});if(n.fence.assertCurrent(),!o||typeof o.exists!="boolean")throw new f("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!nr(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||U(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new f("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new f("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.baseline&&(!Number.isSafeInteger(o.baseline.revision)||o.baseline.revision<0||!/^sha256:[0-9a-f]{64}$/.test(o.baseline.markdownVersion)))throw new f("APP_SYNC_BASELINE_INVALID");return o}async readPendingDocument(e,n){n.fence.assertCurrent();try{let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e.docId,signal:n.fence.signal,fence:n.fence});return n.fence.assertCurrent(),this.validateRemoteDocument(r,e,n),r}catch(r){if(n.fence.assertCurrent(),Fe(r)==="DOC_NOT_FOUND"&&qo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:ae(e.ref),documentId:e.docId,fence:n.fence,now:this.now()}),null;throw r}}validateRemoteDocument(e,n,r){if(!e||e.docId!==n.docId||!Number.isSafeInteger(e.currentRevision)||e.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(e.markdownVersion)||U(e.markdown)!==e.markdownVersion||!J(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let o=e.appGrantId===r.grant.grantId&&e.appGrantGeneration===r.grant.generation,s=e.appGrantGeneration===n.appGrantGeneration&&e.appGrantGeneration<=r.grant.generation;if(!o&&!(n.needsReattach&&s))throw new f("DOC_APP_GRANT_STALE",409)}async queueOrConfirmReattachment(e,n,r){if(n.appGrantId===r.grant.grantId&&n.appGrantGeneration===r.grant.generation){this.markReattached(r.binding,r.grant,e.ref,r,n);let a=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:n,pending:a}}if(this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:e.ref,documentId:n.docId,fingerprint:n.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}).status!=="completed")return this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:e.grantId,generation:e.grantGeneration,ref:e.ref,fence:r.fence,patch:{status:"waiting",errorCode:"APP_SYNC_REATTACH_PENDING",needsReconcile:true},now:this.now()}),null;let s=await this.readRemoteDocument(n.docId,r);if(s.appGrantId!==r.grant.grantId||s.appGrantGeneration!==r.grant.generation)return null;if(U(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);this.markReattached(r.binding,r.grant,e.ref,r,s);let i=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:s,pending:i}}markReattached(e,n,r,o,s){this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)&&this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{needsReattach:false,needsReconcile:true,...s?{listedRevision:s.currentRevision,listedFingerprint:s.markdownVersion}:{},appGrantGeneration:n.generation,status:"waiting",errorCode:null},now:this.now()});}markPendingForReconcile(e,n,r,o,s){!this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)||!this.isFenceCurrent(o)||this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{status:"waiting",needsReconcile:true,errorCode:s},now:this.now()});}async applyConditionalSave(e,n,r,o,s,i,a){let c={kind:"conditional_save",binding:a.binding,grant:a.grant,ref:e,documentId:n,expectedLocalVersion:r.localVersion,expectedRemoteRevision:o,expectedRemoteFingerprint:s,markdown:r.markdown,markdownFingerprint:r.localFingerprint,needsReattach:i,fence:a.fence,beforeDispatch:async()=>{if(a.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(a.binding.accountKey,T,ae(e)))return {ok:false,reason:"deleted"};let S=await this.inspectLocal(e,a);return !S.exists||S.localVersion!==r.localVersion||S.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:S.localVersion,markdown:S.markdown,fingerprint:S.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(S){throw this.isFenceCurrent(a)&&!gt(S)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),S}if(u.status==="applied")return this.recordOutcome(a,e,r.localFingerprint,r.localFingerprint,n,"synced",null),"complete";if(u.status==="deferred"||u.status==="failed")return u.dispatch==="attempted"&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),"retry";let p=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),g=await this.readRemoteById(n,p,a);if(!g)return "complete";let _=await this.inspectLocal(e,a);if(u.status==="conflict"||_.exists&&_.localFingerprint!==g.markdownVersion)return this.preserveConflict(p??tr(a,e,n,g),_,g,a);if(_.exists&&_.localFingerprint===g.markdownVersion){let S={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:g,expectedLocalVersion:_.localVersion,expectedLocalFingerprint:_.localFingerprint,fence:a.fence};return (await this.applyEffect(S,a)).status==="applied"?(this.recordOutcome(a,e,_.localFingerprint,g.markdownVersion,n,"synced",null),"complete"):"retry"}return "retry"}async applyEffect(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.applyContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=false,s;if(e.kind==="conditional_save"){let i={...e,beforeDispatch:async()=>{o=true;let a=await e.beforeDispatch();return n.fence.assertCurrent(),a}};if(s=await r(i),s.dispatch==="attempted"&&!o)throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new f("APP_SYNC_ADAPTER_DID_NOT_DISPATCH")}else s=await r(e);return n.fence.assertCurrent(),s}async reconcileAfterLocalRace(e,n,r){let o=await this.inspectLocal(e.ref,r);if(!o.exists){let s={kind:"create_absent",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:null,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,n.markdownVersion,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}if(o.localFingerprint===n.markdownVersion){let s={kind:"attach_equal",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:o.localVersion,expectedLocalFingerprint:o.localFingerprint,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,o.localFingerprint,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}return this.preserveConflict(e,o,n,r)}async preserveConflict(e,n,r,o){if(!n.exists)return "retry";let s=o.fence.rootFingerprint,i=`c_${ae(JSON.stringify([o.binding.bindingId,o.grant.grantId,o.grant.generation,e.ref,n.localVersion,r.currentRevision,r.markdownVersion]))}`,a={conflictId:i,bindingId:o.binding.bindingId,accountKey:o.binding.accountKey,workspaceId:o.binding.workspaceId,rootFingerprint:s,grantId:o.grant.grantId,grantGeneration:o.grant.generation,scopeVersion:o.grant.scopeVersion,ref:e.ref,documentId:r.docId,localVersion:n.localVersion,localFingerprint:n.localFingerprint,baselineRevision:n.baseline?.revision??null,baselineFingerprint:n.baseline?.markdownVersion??null,remoteRevision:r.currentRevision,remoteFingerprint:r.markdownVersion,needsReattach:e.needsReattach,vaultHandle:null,preservationStatus:"pending",state:"open",supersededBy:null,resolutionRequestId:null,resolutionChoice:null,cleanupPending:false,createdAt:this.now(),updatedAt:this.now()},c=this.continuationStore.putConflict({conflict:a,fence:o.fence});if(this.recordOutcome(o,e.ref,n.localFingerprint,n.baseline?.markdownVersion??null,r.docId,"conflict","APP_SYNC_CONFLICT"),c.preservationStatus==="ready"&&c.vaultHandle)return this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),"complete";try{o.fence.assertCurrent();let u=await this.continuation.conflictVault.preserve({accountKey:o.binding.accountKey,conflictId:i,markdown:r.markdown,fingerprint:r.markdownVersion,fence:o.fence});if(o.fence.assertCurrent(),!nr(u.handle)||u.fingerprint!==r.markdownVersion||U(r.markdown)!==u.fingerprint)throw new f("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return c=this.continuationStore.putConflict({conflict:{...a,vaultHandle:u.handle,preservationStatus:"ready",updatedAt:this.now()},fence:o.fence}),c.preservationStatus==="ready"&&this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),c.preservationStatus==="ready"?"complete":"retry"}catch(u){if(!this.isFenceCurrent(o))throw u;return this.continuationStore.putConflict({conflict:{...a,preservationStatus:"failed",updatedAt:this.now()},fence:o.fence}),this.markPendingForReconcile(o.binding,o.grant,e.ref,o,"APP_SYNC_CONFLICT_ARCHIVE_FAILED"),"retry"}}recordOutcome(e,n,r,o,s,i,a){this.continuationStore.recordContinuationOutcome({binding:e.binding,grant:e.grant,ref:n,sourceFingerprint:r,syncedFingerprint:o,documentId:s,status:i,errorCode:a,fence:e.fence,now:this.now()});}async readRemoteById(e,n,r){return n?this.readPendingDocument(n,r):this.readRemoteDocument(e,r)}async readRemoteDocument(e,n){n.fence.assertCurrent();let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e,signal:n.fence.signal,fence:n.fence});if(n.fence.assertCurrent(),!r||r.docId!==e||U(r.markdown)!==r.markdownVersion)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);return r}async applyHumanResolution(e,n,r){if(r.fence.assertCurrent(),n.state==="superseded"&&e.choice==="keep_both"){let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{status:"stale"}:(await this.readVerifiedArchive(n,r),{status:"resolved"})}let o=await this.readRemoteDocument(n.documentId,r);if(!this.scopeRegistry.validateFrontMatter(n.ref,o.markdown).valid)throw new f("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let s=o.appGrantId===r.grant.grantId&&o.appGrantGeneration===r.grant.generation;if(!s&&(!n.needsReattach||o.appGrantGeneration>=r.grant.generation))throw new f("DOC_APP_GRANT_STALE",409);let i=await this.inspectLocal(n.ref,r);if(!i.exists)return {status:"stale"};let a=o.currentRevision===e.expectedRemoteRevision&&o.markdownVersion===e.expectedRemoteFingerprint,c=o.currentRevision===n.remoteRevision&&o.markdownVersion===n.remoteFingerprint;if(!a||!c)return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};if(!(i.localVersion===e.expectedLocalVersion&&i.localFingerprint===n.localFingerprint))return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};let p=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let E={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:p},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},R;try{R=await this.applyEffect(E,r);}catch(I){throw gt(I)?I:new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(R.status==="applied")return {status:"resolved"};if(R.status==="stale_local")return i=await this.inspectLocal(n.ref,r),i.exists&&i.localFingerprint===o.markdownVersion?{status:"resolved"}:{status:"stale",...i.exists?{refreshed:{local:i,remote:o}}:{}};if(R.status==="conflict"){let I=await this.readRemoteDocument(n.documentId,r),Ae=await this.inspectLocal(n.ref,r);return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}}}if(R.status==="failed"||R.status==="deferred")throw R.dispatch==="attempted"?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new f(R.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let E=this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,fingerprint:o.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}),R={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};E.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,E,R);let I=await this.readRemoteDocument(n.documentId,r);if(I.appGrantId!==r.grant.grantId||I.appGrantGeneration!==r.grant.generation||I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion){let Ae=await this.inspectLocal(n.ref,r);if(I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion)return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}};throw new f("APP_SYNC_REATTACH_PENDING")}}let _=false,S={kind:"conditional_save",binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,markdown:i.markdown,markdownFingerprint:i.localFingerprint,needsReattach:false,fence:r.fence,beforeDispatch:async()=>{_=true,r.fence.assertCurrent();let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:E.localVersion,markdown:E.markdown,fingerprint:E.localFingerprint}}},w;try{w=await this.applyEffect(S,r);}catch(E){throw gt(E)?E:_?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):E}if(w.status==="applied")return {status:"resolved"};if(w.status==="conflict"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return {status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="stale_local"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return R.exists&&R.localFingerprint===E.markdownVersion?{status:"resolved"}:{status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="failed"||w.status==="deferred")throw w.dispatch==="attempted"?new f("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new f(w.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}async cleanupResolvedConflict(e,n){let r=e;if(this.recordOutcome(n,r.ref,r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.state==="kept_both"?r.baselineFingerprint:r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.documentId,r.state==="kept_both"?"conflict":"synced",r.state==="kept_both"?"APP_SYNC_CONFLICT_KEPT_BOTH":null),r.cleanupPending&&r.vaultHandle)try{n.fence.assertCurrent(),await this.continuation.conflictVault.remove({accountKey:n.binding.accountKey,handle:r.vaultHandle,fence:n.fence}),n.fence.assertCurrent(),this.continuationStore.finishConflictArchiveCleanup({conflictId:r.conflictId,fence:n.fence,now:this.now()}),r=this.continuationStore.getConflict(r.conflictId)??r;}catch{}let{vaultHandle:o,...s}=r;return {status:r.state==="kept_both"?"kept_both":"resolved",conflict:{...s,sessionEpoch:n.session.epoch},cleanupPending:r.cleanupPending}}async readVerifiedArchive(e,n){if(e.preservationStatus!=="ready"||!e.vaultHandle)throw new f("APP_SYNC_CONFLICT_NOT_PRESERVED",409);n.fence.assertCurrent();let r=await this.continuation.conflictVault.read({accountKey:n.binding.accountKey,handle:e.vaultHandle,expectedFingerprint:e.remoteFingerprint,fence:n.fence});if(n.fence.assertCurrent(),r.fingerprint!==e.remoteFingerprint||U(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new f("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return r.markdown}async refreshConflictAfterStale(e,n){n.fence.assertCurrent();let r=await this.inspectLocal(e.ref,n),o=await this.readRemoteDocument(e.documentId,n);r.exists&&(r.localVersion===e.localVersion&&r.localFingerprint===e.localFingerprint&&o.docId===e.documentId&&o.currentRevision===e.remoteRevision&&o.markdownVersion===e.remoteFingerprint||await this.preserveConflict(tr(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?er(e):{grantId:n.grantId,appId:T,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:_e}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return er(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:T,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:_e}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new f("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=ae(JSON.stringify(e.rootSegments)),a;a=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:i,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:s.signal,assertCurrent:()=>this.assertArchiveFenceCurrent(e,n,r,s,o)});let c={binding:e,grant:n,session:r,grantToken:s,fence:a};return a.assertCurrent(),c}assertArchiveFenceCurrent(e,n,r,o,s){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||this.sessionFence.activeAccountKey!==e.accountKey||this.sessionFence.activeSessionEpoch!==r.epoch||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.generation!==n.generation)throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let i=this.dependencies.store.getBinding(e.bindingId);if(!i){let a=s.purgeRequestId?this.continuationStore.getAccountDataPurge(s.purgeRequestId):void 0;if(a?.state==="complete"&&a.bindingId===e.bindingId&&a.accountKey===e.accountKey&&a.workspaceId===e.workspaceId&&a.rootFingerprint===ae(JSON.stringify(e.rootSegments)))return;throw new f("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||ae(JSON.stringify(i.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new f("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new f("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Qn(i.status))throw new f("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new f("DOC_APP_GRANT_STALE",409)}createFenceContext(e,n,r,o){if(!e.grantId||!e.grantGeneration||!e.scopeVersion||e.grantId!==n.grantId||e.grantGeneration!==n.generation||e.scopeVersion!==n.scopeVersion||n.scopeVersion!==this.scopeRegistry.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);let s=ae(JSON.stringify(e.rootSegments)),i;i=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:s,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:o.signal,assertCurrent:()=>this.assertFenceCurrent(e,n,r,o)});let a={binding:e,grant:n,session:r,grantToken:o,fence:i};return i.assertCurrent(),a}assertFenceCurrent(e,n,r,o){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||o.grantId!==n.grantId||o.generation!==n.generation||o.accountKey!==e.accountKey)throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||ae(JSON.stringify(s.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new f("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new f("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new f(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},Ga=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","TOKEN_EXPIRED","DOC_SCOPE_REQUIRED","DOC_PILOT_NOT_ALLOWED","DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE","DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH","APP_SYNC_SESSION_STALE","APP_SYNC_ROOT_STALE","APP_SYNC_REVOKE_PENDING"]);function ae(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Mo(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function J(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function un(t){if(typeof t!="string"||t.length>40)return false;let e=Date.parse(t);return Number.isFinite(e)&&new Date(e).toISOString()===t}function nr(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Fo(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Qn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function ja(t){if(!t||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Wa(t){if(!t||t.intent!=="device_account_data_deleted"||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new f("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function Ka(t){if(!t||!t.session||!J(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.conflictId,128)||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!J(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!nr(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new f("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Fe(t){return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error&&/^[A-Z0-9_:-]{1,128}$/.test(t.message)?t.message:"APP_SYNC_OPERATION_FAILED"}function qo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function gt(t){return Ga.has(Fe(t))}function Va(t){return Fe(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Fe(t)==="APP_SYNC_REATTACH_PENDING"}function Zn(t){let e=Fe(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function za(t){if(gt(t))return false;let e=qo(t);return e===408||e===409||e===429||e!==void 0&&e>=500||new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","APP_SYNC_REATTACH_RESPONSE_UNKNOWN","APP_SYNC_SAVE_RESPONSE_UNKNOWN"]).has(Fe(t))}function Ya(t){return Fe(t)==="DOC_APP_GRANT_STALE"||Fe(t)==="DOC_APP_CURSOR_INVALID"}function er(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new f("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:T,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:_e}}function Uo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==ae(JSON.stringify(e.rootSegments))||t.scopeVersion!==Xe)throw new f("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function tr(t,e,n,r){return {bindingId:t.binding.bindingId,accountKey:t.binding.accountKey,grantId:t.grant.grantId,grantGeneration:t.grant.generation,ref:e,docId:n,listedRevision:r.currentRevision,listedFingerprint:r.markdownVersion,appGrantGeneration:r.appGrantGeneration,needsReattach:r.appGrantId!==t.grant.grantId||r.appGrantGeneration!==t.grant.generation,needsReconcile:true,status:"waiting",errorCode:null,attempts:0,updatedAt:Date.now()}}var Xa=12e4,Qa=1e4,Za=1e3,ed=15*6e4,td=4,rr=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Bt=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),or=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),pn=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),nd=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),f=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},ar=class{constructor(e){this.dependencies=e;if(e.continuation&&e.continuation.store!==e.store)throw new Error("APP_SYNC_CONTINUATION_STORE_MISMATCH");if(e.createLedger&&e.remote.capabilities?.dispatchGate!==true)throw new Error("APP_SYNC_DISPATCH_GATE_UNSUPPORTED");if(e.createLedger&&!e.store.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");this.scopeRegistry=e.scopeRegistry??new Ut,this.sessionFence=e.sessionFence??new Ft,this.now=e.now??Date.now,this.createId=e.createId??crypto.randomUUID,this.continuationRuntime=e.continuation?new ln(e,this.scopeRegistry,this.sessionFence,this.now,this.createId,n=>this.hasPendingRevoke(n)):null;}dependencies;scopeRegistry;sessionFence;now;createId;scanRuns=new Map;tickRuns=new Map;remoteReadSemaphore=new cr(td);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=_t(e.resolvedRootSegments);if(!r)throw new Error("APP_SYNC_ROOT_INVALID");if(typeof e.workspaceId!="string"||e.workspaceId.trim().length===0||e.workspaceId.length>256)throw new Error("APP_SYNC_WORKSPACE_INVALID");let o=this.sessionFence.activeAccountKey,s=this.sessionFence.activate(n);o&&o!==n&&await this.suspendBindingsForAccount(o,"account_switch");let i=this.dependencies.store.bind({bindingId:this.createId(),accountKey:n,workspaceId:e.workspaceId,appId:T,rootSegments:r,now:this.now()});return this.isCurrent(s)?(this.hasPendingRevoke(i.bindingId)?await this.holdPendingRevoke(i):this.isEligible(e.eligibility)?this.dependencies.store.updateBinding(i.bindingId,{status:"checking"},this.now()):(this.dependencies.store.updateBinding(i.bindingId,{status:"unavailable"},this.now()),this.sessionFence.suspend(n),await this.dependencies.documents.suspendBinding({binding:i,grantId:i.grantId,generation:i.grantGeneration,reason:"ineligible"})),this.dependencies.store.getBinding(i.bindingId)??i):i}scan(e,n){let r=this.dependencies.store.getBinding(e),o=r!==void 0&&(!n.session.authenticated||!n.session.accountKey||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility));o&&(this.scanEpoch+=1,this.sessionFence.suspend(r.accountKey));let s=`${e}:${n.session.accountKey??"signed-out"}:${this.scanEpoch}:${n.eligibility?.featureEnabled===true?1:0}:${n.eligibility?.ownerAllowlisted===true?1:0}`,i=o?void 0:this.scanRuns.get(s);if(i)return i;let a=this.performScan(e,n).finally(()=>{this.scanRuns.get(s)===a&&this.scanRuns.delete(s);});return o||this.scanRuns.set(s,a),a}tick(e,n){let r=this.dependencies.store.getBinding(e);r&&(!n.session.authenticated||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility))&&this.sessionFence.suspend(r.accountKey);let o=this.tickRuns.get(e),i=(o?o.catch(()=>{}):Promise.resolve()).then(()=>this.performTick(e,n)).finally(()=>{this.tickRuns.get(e)===i&&this.tickRuns.delete(e);});return this.tickRuns.set(e,i),i}async performTick(e,n){let r=await this.scan(e,n),o=this.dependencies.store.getBinding(e);if(o&&this.hasPendingRevoke(e))return await this.holdPendingRevoke(o),this.snapshot(e);if(!r.binding||!this.isTransferStatus(r.status))return r;let s=this.dependencies.store.getBinding(e);if(!s?.grantId||!s.grantGeneration||!s.scopeVersion)return this.snapshot(e);let i=await this.activateSession(s.accountKey);if(!i||!this.isCurrent(i))return this.snapshot(e);let a=this.grantFromBinding(s),c=this.sessionFence.captureGrant(i,a.grantId,a.generation);try{if(this.continuationRuntime&&await this.continuationRuntime.tick(s,a,i,c,n),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),p=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),g=this.limitCreationClaims(s.accountKey,p);if(await Promise.all([...u.filter(_=>!this.continuationRuntime&&this.shouldReconcile(_,a)).map(_=>this.reconcileExisting(s,a,c,_)),...g.map(_=>this.dispatchCreation(s,a,i,_,n))]),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}return !this.isCurrent(i)||!this.isCurrent(c)?this.snapshot(e):(this.refreshBindingStatus(e),this.snapshot(e))}finally{this.sessionFence.release(c);}}limitCreationClaims(e,n){let r=this.dependencies.createLedger;if(!r)return n;try{let o=r.peek(e,this.now());return o.available?n.slice(0,o.remaining):[]}catch(o){return this.dependencies.onAdapterError?.(o),[]}}makeDispatchGate(e){let n=this.dependencies.createLedger;if(n)return qt({ledger:n,accountKey:e.accountKey,requestId:e.requestId,source:e.source,now:this.now,guard:()=>{if(e.token.signal.aborted||!this.isCurrent(e.token)||!this.bindingHasGrant(e.bindingId,e.grant))throw new f("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new f("APP_SYNC_REVOKE_PENDING")}})}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}recordMissingDispatchGate(e){let n=new f("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger?.reserveForced({...e,now:this.now()});}catch(r){this.dependencies.onAdapterError?.(r);}return this.dependencies.onAdapterError?.(n),n}async suspendAccount(e){/^[0-9a-f]{64}$/.test(e)&&(this.scanEpoch+=1,this.sessionFence.suspend(e),await this.suspendBindingsForAccount(e,"logout"));}async invalidateGrant(e){let n=this.dependencies.store.getBinding(e.bindingId),r=e.session.accountKey;!n||!e.session.authenticated||!r||n.accountKey!==r||n.grantId!==e.grantId||n.grantGeneration!==e.generation||(this.scanEpoch+=1,this.sessionFence.suspend(r),this.sessionFence.cancelGrant(r,e.grantId,e.generation),this.dependencies.store.invalidateGrantJobs(n.bindingId,e.grantId,e.generation,this.now()),this.dependencies.store.updateBinding(n.bindingId,{status:this.hasPendingRevoke(n.bindingId)?"stopping":"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:n,grantId:e.grantId,generation:e.generation,reason:"revoked"}));}async beginControlRequest(e){let{binding:n,accountKey:r,rootFingerprint:o}=this.validateControlIdentity(e),s=e.requestId;if(typeof s!="string"||s.length<1||s.length>128||s.includes("\0"))throw new Error("APP_SYNC_REQUEST_ID_INVALID");if(e.kind!=="connect"&&e.kind!=="revoke")throw new Error("APP_SYNC_CONTROL_REQUEST_KIND_INVALID");if(e.kind==="connect"&&n.grantId&&n.grantGeneration){let p=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||p!==void 0)&&!this.dependencies.store.getControlRequest(s))throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_GRANTED")}let i=e.kind==="revoke"?e.grantId??null:null,a=e.kind==="revoke"?e.generation??null:null;if(e.kind==="revoke"&&(!i||!Number.isSafeInteger(a)||a<1||i!==n.grantId||a!==n.grantGeneration))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");if(e.kind==="connect"&&(e.grantId!=null||e.generation!=null))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let c=this.now(),u=this.dependencies.store.beginControlRequest({requestId:s,bindingId:n.bindingId,accountKey:r,appId:T,workspaceId:n.workspaceId,rootFingerprint:o,kind:e.kind,state:"pending",grantId:i,generation:a,createdAt:c,updatedAt:c,resolvedAt:null,resolution:null,resolutionId:null});return u.kind==="revoke"&&(u.state==="pending"||u.state==="unknown")&&await this.holdPendingRevoke(n),u}getControlRequest(e){let{rootFingerprint:n}=this.validateControlIdentity(e),r=this.dependencies.store.getControlRequest(e.requestId);if(r&&!od(r,e,n))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return r}getPendingControlRequest(e){let{binding:n}=this.validateControlIdentity(e);return this.dependencies.store.getPendingControlRequest(n.bindingId)}async markControlRequestUnknown(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(n.state==="unknown")return n;if(n.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED");let r=this.dependencies.store.updateControlRequest(n.requestId,{state:"unknown",grantId:n.grantId,generation:n.generation,resolution:null,resolutionId:null,resolvedAt:null,now:this.now()});if(r.kind==="revoke"){let o=this.dependencies.store.getBinding(r.bindingId);o&&await this.holdPendingRevoke(o);}return r}async resolveControlRequest(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(e.outcome!=="confirmed"&&e.outcome!=="failed")throw new Error("APP_SYNC_CONTROL_REQUEST_OUTCOME_INVALID");if(e.resolution!=="remote"&&e.resolution!=="human")throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_INVALID");if(typeof e.resolutionId!="string"||e.resolutionId.length<1||e.resolutionId.length>128||e.resolutionId.includes("\0"))throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_ID_INVALID");if(n.state==="confirmed"||n.state==="failed"){if(n.state===e.outcome&&n.resolution===e.resolution&&n.resolutionId===e.resolutionId)return n;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}let r=n.grantId,o=n.generation;if(n.kind==="connect"&&e.outcome==="confirmed"){let c=e.observedGrant;if(!c||c.appId!==T||!c.grantId||!Number.isSafeInteger(c.generation)||c.generation<1||!this.scopeRegistry.matchesDefinition(c.scopeVersion,c.scope))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_INVALID");r=c.grantId,o=c.generation;}let s=this.now(),i=this.dependencies.store.updateControlRequest(n.requestId,{state:e.outcome,grantId:r,generation:o,resolution:e.resolution,resolutionId:e.resolutionId,resolvedAt:s,now:s}),a=this.dependencies.store.getBinding(i.bindingId);return a&&n.kind==="revoke"?e.outcome==="confirmed"?(n.grantId&&n.generation&&(this.sessionFence.cancelGrant(a.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(a.bindingId,n.grantId,n.generation,s)),this.dependencies.store.updateBinding(a.bindingId,{status:"revoked"},s),await this.suspendDocumentBinding(a,"revoked")):this.dependencies.store.updateBinding(a.bindingId,{status:"checking"},s):a&&n.kind==="connect"&&e.outcome==="confirmed"&&r&&o&&this.dependencies.store.updateBinding(a.bindingId,{grantId:r,grantGeneration:o,scopeVersion:this.scopeRegistry.scopeVersion,status:"checking"},s),i}async snapshot(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e),o=Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T));return {binding:n,status:n.status,counts:o,results:r}}async performScan(e,n){let r=this.dependencies.store.getBinding(e);if(!r)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let o=this.dependencies.store.getPendingControlRequest(e);if(o?.kind==="revoke")return await this.holdPendingRevoke(r),this.snapshot(e);if(!n.session.authenticated||!n.session.accountKey)return await this.suspendAccount(r.accountKey),this.snapshot(e);if(n.session.accountKey!==r.accountKey)return this.sessionFence.suspend(r.accountKey),await this.suspendBindingsForAccount(r.accountKey,"account_switch"),this.snapshot(e);if(!this.isEligible(n.eligibility))return await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e);let s=await this.activateSession(r.accountKey);if(!s)return this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);this.dependencies.store.updateBinding(e,{status:"checking"},this.now());let i;try{i=await this.dependencies.remote.readGrant({accountKey:r.accountKey,appId:T,signal:s.signal});}catch(u){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=ft(u);return sr(u)&&!Bt.has(p)&&!rr.has(p)?await this.pauseAuthentication(r):Bt.has(p)||sd(u)?await this.pauseUnavailableBinding(r,p==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):or.has(p)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):ir(u)?this.dependencies.store.updateBinding(e,{status:"offline"},this.now()):await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)}if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(i.appId!==T||i.available!==true)return await this.pauseUnavailableBinding(r,i.available===true?"scope_mismatch":"ineligible"),this.snapshot(e);if(i.status==="none")return r.grantId&&r.grantGeneration?(await this.invalidateStoredGeneration(r,"revoked"),r=this.dependencies.store.getBinding(e)??r,this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):this.dependencies.store.updateBinding(e,{status:"consent_required"},this.now()),this.snapshot(e);if(i.status==="revoked")return r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),this.snapshot(e);if(i.status!=="active")return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);let a=i.grant;if(!a||a.appId!==T||!a.grantId||!Number.isSafeInteger(a.generation)||a.generation<1||!this.scopeRegistry.matchesDefinition(a.scopeVersion,a.scope))return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(this.dependencies.store.getConfirmedRevoke(e,a.grantId,a.generation))return this.sessionFence.suspend(r.accountKey),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),await this.suspendDocumentBinding(r,"revoked"),this.snapshot(e);o?.kind==="connect"&&this.dependencies.store.updateControlRequest(o.requestId,{state:"confirmed",grantId:a.grantId,generation:a.generation,resolution:"remote",resolutionId:"doc023-active",resolvedAt:this.now(),now:this.now()}),(r.grantId!==a.grantId||r.grantGeneration!==a.generation)&&r.grantId&&r.grantGeneration&&(this.sessionFence.cancelGrant(r.accountKey,r.grantId,r.grantGeneration),this.dependencies.store.invalidateGrantJobs(e,r.grantId,r.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:"regranted"})),this.dependencies.store.updateBinding(e,{grantId:a.grantId,grantGeneration:a.generation,scopeVersion:a.scopeVersion,status:"checking"},this.now()),r=this.dependencies.store.getBinding(e)??r;try{let u=await this.listAllowedRefs(r,s);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=new Set(u.map(g=>g.ref));for(let g of this.dependencies.store.listResults(e))!p.has(g.ref)&&g.status!=="deleted"&&this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:g.syncedFingerprint,documentId:g.documentId,status:"excluded",errorCode:"APP_FILE_MISSING_OR_OUT_OF_SCOPE"});u.sort((g,_)=>g.ref.localeCompare(_.ref));for(let[g,_]of u.entries()){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let S=crypto.createHash("sha256").update(_.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,T,S)){let ke=this.dependencies.store.getResult(e,_.ref);this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:ke?.syncedFingerprint??null,documentId:ke?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let w=this.dependencies.store.getResult(e,_.ref);if(g>=500){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let E=await this.readEligibleFile(r,_.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(E.status==="unsafe"||E.status==="missing"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:E.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(E.status==="read_error"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let R=this.scopeRegistry.validateFrontMatter(_.ref,E.markdown),I=U(E.markdown);if(!R.valid){this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(w?.status==="conflict"&&w.grantGeneration===a.generation)continue;if(w?.documentId&&w.grantGeneration===a.generation){if(w.status==="synced"&&w.syncedFingerprint===I)continue;let ke=w?.sourceFingerprint===I;this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w.syncedFingerprint,documentId:w.documentId,status:ke?w.status:"waiting",errorCode:ke?w.errorCode:null,nextAttemptAt:ke?w.nextAttemptAt:0});continue}if(w?.status==="failed"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I&&!pn.has(w.errorCode??"")||w?.status==="blocked"&&w.errorCode!=="APP_LOCAL_QUOTA"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I)continue;let Ae=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:_.ref,fingerprint:I,now:this.now()}),O=w?.sourceFingerprint===I,Ie=w?.status==="failed"&&pn.has(w.errorCode??"");this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:Ae.status==="completed"?"processing":"waiting",errorCode:O&&!Ie?w.errorCode:null,nextAttemptAt:O&&!Ie?w.nextAttemptAt:0});}return this.refreshBindingStatus(e),this.snapshot(e)}catch{return this.isCurrent(s)?(await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)):this.snapshot(e)}}async listAllowedRefs(e,n){let r=new Map,o=new Set,s=null;for(let i=0;i<Qa;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Yn,cursor:s,pageSize:100,signal:n.signal});if(this.hasPendingRevoke(e.bindingId))return [];if(!this.isCurrent(n))return [];for(let c of a.entries)c.isSymlink||!c.staysWithinRoot||this.scopeRegistry.validateRef(c.ref).valid&&r.set(c.ref,{ref:c.ref});if(a.nextCursor===null)return [...r.values()];if(o.has(a.nextCursor))throw new Error("APP_SYNC_PAGE_CURSOR_REPEATED");o.add(a.nextCursor),s=a.nextCursor;}throw new Error("APP_SYNC_PAGE_LIMIT_REACHED")}async readEligibleFile(e,n,r){if(!this.scopeRegistry.validateRef(n).valid)return {status:"unsafe"};try{let o=await this.dependencies.workspace.readFile({rootSegments:e.rootSegments,ref:n,signal:r});return o.isSymlink||!o.staysWithinRoot?{status:"unsafe"}:{status:"ok",markdown:o.markdown}}catch(o){let s=ft(o);return s==="ENOENT"||s==="APP_FILE_MISSING"?{status:"missing"}:{status:"read_error"}}}async beforeDocumentDispatch(e,n,r,o){if(!this.isCurrent(r))return {ok:false,reason:"session_stale"};if(!this.bindingHasGrant(e.bindingId,n))return {ok:false,reason:"grant_stale"};if(this.hasPendingRevoke(e.bindingId))return {ok:false,reason:"control_request_pending"};if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o)))return {ok:false,reason:"deleted"};let s=await this.readEligibleFile(e,o,r.signal);return this.isCurrent(r)?this.hasPendingRevoke(e.bindingId)?{ok:false,reason:"control_request_pending"}:this.bindingHasGrant(e.bindingId,n)?this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o))?{ok:false,reason:"deleted"}:s.status!=="ok"?{ok:false,reason:s.status}:this.scopeRegistry.validateFrontMatter(o,s.markdown).valid?{ok:true,markdown:s.markdown,fingerprint:U(s.markdown)}:{ok:false,reason:"out_of_scope"}:{ok:false,reason:"grant_stale"}:{ok:false,reason:"session_stale"}}async readRemoteDocument(e){return this.remoteReadSemaphore.run(e.signal,()=>this.dependencies.remote.readDocument(e))}async dispatchCreation(e,n,r,o,s){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(o.accountKey!==e.accountKey||o.bindingId!==e.bindingId||o.grantId!==n.grantId||o.grantGeneration!==n.generation||e.grantId!==n.grantId||e.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(!this.isCurrent(r))return;if(o.operationKind==="reattach"){this.continuationRuntime?await this.continuationRuntime.dispatchReattachCreation(e,n,r,o,s):this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),Xa);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.dependencies.store.getResult(e.bindingId,i.ref);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref))){await this.markDeleted(e,n,i,c);return}let u=await this.readEligibleFile(e,i.ref,a.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(u.status!=="ok"){this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:u.status==="read_error"?"failed":"excluded",errorCode:u.status==="unsafe"?"APP_FILE_UNSAFE":u.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:u.status==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}if(!this.scopeRegistry.validateFrontMatter(i.ref,u.markdown).valid){this.writeResult(e,n,i.ref,{sourceFingerprint:U(u.markdown),syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(U(u.markdown)!==i.fingerprint){this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"processing",errorCode:null});let _=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let O=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new f("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref)))return {kind:"deleted"};if(O.status!=="ok")return {kind:"local_file",status:O.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,O.markdown).valid)return {kind:"out_of_scope"};let Ie=U(O.markdown);if(Ie!==i.fingerprint)return {kind:"source_changed",fingerprint:Ie};let ke=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),Co;try{Co=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:T,ref:i.ref,requestId:i.requestId,markdown:O.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...ke?{dispatchGate:ke}:{}});}catch(Wn){if(Wn instanceof je)return {kind:"budget_deferred",retryAt:Wn.retryAt};throw Wn}if(ke&&ke.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:Co}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(_.status==="deferred"){let O=this.now();if(!this.deferClaim(i,_.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.retryAt});return}if(_.value.kind==="budget_deferred"){let O=this.now();if(!this.deferClaim(i,_.value.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.value.retryAt});return}if(_.value.kind!=="created"){let O=_.value;if(O.kind==="control_pending"){this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()}),this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now());return}if(O.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(O.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:O.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}let Ie=O.kind==="local_file"?O.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:Ie==="read_error"?"failed":"excluded",errorCode:O.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":Ie==="unsafe"?"APP_FILE_UNSAFE":Ie==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:Ie==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let S=_.value.result;if(S.appGrantId!==n.grantId||S.appGrantGeneration!==n.generation)throw new f("DOC_APP_GRANT_STALE",409);let w=await this.readRemoteDocument({accountKey:i.accountKey,docId:S.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(w,S,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,S.docId,{status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH",dispatch:"none"}),this.dependencies.store.updateCreation(i.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()});return}let E=U(w.markdown),R,I=i.fingerprint;if(!S.replayed&&!S.reattached&&E===i.fingerprint&&w.markdownVersion===i.fingerprint)R=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let O;if(R=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(O=await this.beforeDocumentDispatch(e,n,a,i.ref),O)}),!O&&R.dispatch!=="none")throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(R.dispatch==="attempted"&&!O)throw new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(O&&!O.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,O,i);return}O?.ok&&R.dispatch!=="none"&&(I=O.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Ae=this.recordOutcome(e,n,i.ref,I,c,S.docId,R);this.dependencies.store.updateCreation(i.jobId,{status:Ae==="conflict"?"conflict":Ae==="failed"?"failed":R.status==="failed"&&R.retryAt!==void 0?"waiting":"completed",nextAttemptAt:R.status==="failed"&&R.retryAt!==void 0?this.retryAt(i.attempts+1,R.retryAt):0,now:this.now()});}catch(u){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;await this.handleCreationError(e,n,i,c,u);}finally{this.sessionFence.release(a);}}async reconcileExisting(e,n,r,o){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!o.documentId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation||o.status==="conflict"||o.status==="excluded"||o.status==="deleted"||!this.isCurrent(r))return;let s=await this.readEligibleFile(e,o.ref,r.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;if(s.status!=="ok"){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:s.status==="read_error"?"failed":"excluded",errorCode:s.status==="unsafe"?"APP_FILE_UNSAFE":s.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"});return}if(!this.scopeRegistry.validateFrontMatter(o.ref,s.markdown).valid){this.writeResult(e,n,o.ref,{sourceFingerprint:U(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=U(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o.ref))){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});return}let u;try{u=await this.readRemoteDocument({accountKey:e.accountKey,docId:o.documentId,signal:r.signal});}catch(p){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||U(u.markdown)!==u.markdownVersion){this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH"});return}this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"processing",errorCode:null});try{let p,g=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:o.ref,document:u,localMarkdown:s.markdown,sourceFingerprint:a,signal:r.signal,beforeDispatch:async()=>(p=await this.beforeDocumentDispatch(e,n,r,o.ref),p)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!p&&g.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(g.dispatch==="attempted"&&!p){await this.handleExistingError(e,n,o,a,new f("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(p&&!p.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,p);return}let _=p?.ok&&g.dispatch!=="none"?p.fingerprint:a;this.recordOutcome(e,n,o.ref,_,o,o.documentId,g);}catch(p){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);}}}async handleCreationError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){await this.markDeleted(e,n,r,o);return}if(i==="DOC_APP_REF_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"excluded",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(i==="DOC_APP_BODY_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"failed",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"failed",nextAttemptAt:0,now:this.now()});return}if(rr.has(i)){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"blocked",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"blocked",nextAttemptAt:0,now:this.now()});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=this.retryAt(r.attempts,Ho(s,this.now())),c=ir(s);this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:c?"waiting":"failed",errorCode:i||"APP_SYNC_CREATE_FAILED",nextAttemptAt:c?a:0}),this.dependencies.store.updateCreation(r.jobId,{status:c?"waiting":"failed",nextAttemptAt:c?a:0,now:this.now()}),c&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async handleExistingError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:i,nextAttemptAt:this.now()});return}if(rr.has(i)){i==="DOC_PILOT_NOT_ALLOWED"&&await this.pauseUnavailableBinding(e,"ineligible"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"blocked",errorCode:i});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=ir(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,Ho(s,this.now())):0;this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:a?"waiting":"failed",errorCode:i||"APP_SYNC_RECONCILE_FAILED",nextAttemptAt:u,attempts:a?c:0}),a&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async markDeleted(e,n,r,o){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),this.dependencies.store.updateCreation(r.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});}recordOutcome(e,n,r,o,s,i,a){let c=a.status==="synced"&&a.syncedFingerprint===o?o:s?.syncedFingerprint??null,u=a.status==="synced"&&c!==o?"conflict":(a.status==="failed"||a.status==="waiting")&&a.retryAt!==void 0?"waiting":a.status,p=u==="waiting"&&a.retryAt!==void 0?s?.sourceFingerprint===o?s.attempts+1:1:u==="synced"||u==="conflict"?0:s?.sourceFingerprint===o?s.attempts:0;return this.writeResult(e,n,r,{sourceFingerprint:o,syncedFingerprint:c,documentId:i,status:u,errorCode:u==="conflict"&&a.status==="synced"?"DOC_SYNC_ACK_MISMATCH":a.errorCode??null,nextAttemptAt:u==="waiting"&&a.retryAt!==void 0?this.retryAt(p,a.retryAt):0,attempts:p}),u}recordBeforeDispatchFailure(e,n,r,o,s,i){if(s.reason==="session_stale"||s.reason==="grant_stale")return;if(s.reason==="deleted"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r),this.now()),this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),i&&this.dependencies.store.updateCreation(i.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}if(s.reason==="control_request_pending"){this.writeResult(e,n,r,{sourceFingerprint:o?.sourceFingerprint??null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),i&&this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}let a=s.reason==="read_error"?"failed":"excluded",c=s.reason==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":s.reason==="unsafe"?"APP_FILE_UNSAFE":s.reason==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED";this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:a,errorCode:c,nextAttemptAt:0}),i&&this.dependencies.store.updateCreation(i.jobId,{status:s.reason==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});}writeResult(e,n,r,o){let s=this.dependencies.store.getResult(e.bindingId,r),i=o.attempts??(s?.sourceFingerprint===o.sourceFingerprint?s.attempts:0);this.dependencies.store.upsertResult({bindingId:e.bindingId,accountKey:e.accountKey,ref:r,grantId:n.grantId,grantGeneration:n.generation,...o,nextAttemptAt:o.nextAttemptAt??0,attempts:i,updatedAt:this.now()});}validateControlIdentity(e){let n=this.requireAuthenticatedAccount(e.session),r=this.dependencies.store.getBinding(e.bindingId);if(!r||r.accountKey!==n)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");let o=_t(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!rd(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:Ue(JSON.stringify(o))}}hasPendingRevoke(e){let n=this.dependencies.store.getPendingControlRequest(e);return n?.kind==="revoke"&&(n.state==="pending"||n.state==="unknown")}async holdPendingRevoke(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_REVOKE_PENDING")),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),await this.suspendDocumentBinding(e,"revoke_pending");}async invalidateStoredGeneration(e,n){!e.grantId||!e.grantGeneration||(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.invalidateGrantJobs(e.bindingId,e.grantId,e.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n}));}async pauseUnavailableBinding(e,n){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_UNAVAILABLE")),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,n);}async pauseAuthentication(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"AUTH_REQUIRED",true)),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,"auth_required");}returnProcessingResultsToWaiting(e,n,r,o,s=false){for(let i of this.dependencies.store.listResults(e.bindingId)){let a=i.status==="processing",c=s&&i.status==="failed"&&pn.has(i.errorCode??"");i.grantId!==n||i.grantGeneration!==r||!a&&!c||this.dependencies.store.upsertResult({...i,status:"waiting",errorCode:o,nextAttemptAt:this.now(),updatedAt:this.now()});}}async suspendDocumentBinding(e,n){try{await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n});}catch(r){this.reportAdapterError(r);}}reportAdapterError(e){try{this.dependencies.onAdapterError?.(e);}catch{}}async activateSession(e){let n=this.sessionFence.activeAccountKey,r=this.sessionFence.activate(e);return n&&n!==e&&await this.suspendBindingsForAccount(n,"account_switch"),r}async suspendBindingsForAccount(e,n){for(let r of this.dependencies.store.listBindingsForAccount(e)){this.dependencies.store.updateBinding(r.bindingId,{status:"stopping"},this.now());try{await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:n});}catch(o){this.reportAdapterError(o);}finally{try{this.dependencies.store.updateBinding(r.bindingId,{status:this.hasPendingRevoke(r.bindingId)?"stopping":"local_only"},this.now());}catch(o){this.reportAdapterError(o);}}}}shouldReconcile(e,n){return e.documentId!==null&&e.grantId===n.grantId&&e.grantGeneration===n.generation&&(e.status==="processing"||e.status==="waiting"&&e.nextAttemptAt<=this.now())}validRemoteDocument(e,n,r){return e.docId===n.docId&&e.appGrantId===r.grantId&&e.appGrantGeneration===r.generation&&n.appGrantId===r.grantId&&n.appGrantGeneration===r.generation&&n.markdownVersion===e.markdownVersion&&U(e.markdown)===e.markdownVersion}grantFromBinding(e){if(!e.grantId||!e.grantGeneration||e.scopeVersion!==this.scopeRegistry.scopeVersion)throw new Error("APP_SYNC_BINDING_GRANT_INVALID");return {grantId:e.grantId,appId:T,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:_e}}bindingHasGrant(e,n){let r=this.dependencies.store.getBinding(e);return r?.grantId===n.grantId&&r.grantGeneration===n.generation}isTransferStatus(e){return e==="checking"||e==="syncing"||e==="synced"||e==="partial"}isEligible(e){return e?.featureEnabled===true&&e?.ownerAllowlisted===true}requireAuthenticatedAccount(e){if(!e||e.authenticated!==true||typeof e.accountKey!="string"||!/^[0-9a-f]{64}$/.test(e.accountKey))throw new Error("APP_SYNC_SESSION_REQUIRED");return e.accountKey}isCurrent(e){return this.sessionFence.isCurrent(e)}refreshBindingStatus(e){let n=this.snapshotNow(e);if(!n.binding||["offline","unavailable","revoked","stopping","local_only","consent_required"].includes(n.binding.status))return;let r=n.counts,o=r.P+r.I>0?"syncing":r.F+r.C+r.B>0?"partial":"synced";this.dependencies.store.updateBinding(e,{status:o},this.now());}snapshotNow(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T)),results:r}}listConflicts(e){return this.continuationRuntime?this.continuationRuntime.listConflicts(e):[]}readConflictArchive(e){return this.continuationRuntime?this.continuationRuntime.readConflictArchive(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}resolveConflict(e){return this.continuationRuntime?this.continuationRuntime.resolveConflict(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}purgeAccountData(e){return this.continuationRuntime?this.continuationRuntime.purgeAccountData(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}retryAt(e,n){if(n!==void 0&&Number.isFinite(n))return Math.max(this.now(),n);let r=Math.min(Math.max(e-1,0),10);return this.now()+Math.min(Za*2**r,ed)}};function dr(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Bo(t,e){let n=dr(),r=n;for(let o of t)switch(o.status){case "synced":r.S+=1;break;case "waiting":r.P+=1;break;case "processing":r.I+=1;break;case "failed":r.F+=1;break;case "conflict":r.C+=1;break;case "blocked":r.B+=1;break;}return r.N=r.S+r.P+r.I+r.F+r.C+r.B,r.D=e,n}function rd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function od(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===T}function Ue(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function ft(t){return t instanceof f||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function Ho(t,e){if(t instanceof f&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function ur(t){return t instanceof f||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function sr(t){let e=ft(t);if(Bt.has(e))return false;let n=ur(t);return pn.has(e)||n===401||n===403}function sd(t){let e=ur(t);return e!==void 0&&e>=400&&e<500}function ir(t){let e=ur(t);return e!==void 0?e===408||e===425||e===429||e>=500:nd.has(ft(t))}var cr=class{constructor(e){this.limit=e;if(!Number.isSafeInteger(e)||e<1)throw new Error("INVALID_SEMAPHORE_LIMIT")}limit;active=0;waiters=[];async run(e,n){await this.acquire(e);try{return await n()}finally{this.release();}}acquire(e){return e.aborted?Promise.reject(this.abortError()):this.active<this.limit?(this.active+=1,Promise.resolve()):new Promise((n,r)=>{let o={signal:e,resolve:()=>{e.removeEventListener("abort",o.onAbort),n();},reject:s=>{e.removeEventListener("abort",o.onAbort),r(s);},onAbort:()=>{let s=this.waiters.indexOf(o);s>=0&&this.waiters.splice(s,1),o.reject(this.abortError());}};this.waiters.push(o),e.addEventListener("abort",o.onAbort,{once:true}),e.aborted&&o.onAbort();})}release(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(e.signal.aborted){e.reject(this.abortError());continue}e.resolve();return}this.active=Math.max(0,this.active-1);}abortError(){return Object.assign(new Error("APP_SYNC_SESSION_STALE"),{code:"APP_SYNC_SESSION_STALE"})}};d();P();d();P();L();d();P();M();q();L();F();br();d();P();M();q();L();F();d();Fr();d();P();M();q();L();d();F();var Ur=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(Ur);M();q();d();q();F();F();F();F();Pt();Pt();So();an();lt();Pt();Pt();Tt();d();P();d();var wa=["success","failed","completed"];new Set(wa);vn();Pt();yo();xn();var lp=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"},{key:"usageByEpoch",field:"metadata.usageByEpoch",before:"before_usage_by_epoch",after:"after_usage_by_epoch"},{key:"usageIncomplete",field:"metadata.usageIncomplete",before:"before_usage_incomplete",after:"after_usage_incomplete"}];["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...lp.map(t=>t.field)];vn();d();P();M();q();L();F();Tt();lt();d();d();Qt();d();P();M();q();L();F();d();P();M();q();L();F();d();var Ra=["urgent","high","medium","low"],Ea=["investigating","in-progress","in-review","on-hold","done"];new Set(Ra);new Set(Ea);lt();new Set(Fs);new Set(Ms);new Set(Us);new Set(qs);new Set(Bs);d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();M();P();L();q();lt();F();d();P();d();P();M();L();L();d();P();M();L();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();lt();Tt();Br();Et.map(t=>`'${t}'`).join(", ");var Io=class extends D{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=x(n),this.sqlite=this.handle.sqlite,B(this.handle.db,n);}close(){this.handle.close();}bind(e){if(this.assertAccountKey(e.accountKey),this.assertText(e.bindingId,"bindingId",128),this.assertText(e.workspaceId,"workspaceId",256),e.appId!==T)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=_t(e.rootSegments);if(!n)throw new Error("APP_SYNC_ROOT_INVALID");let r=this.getBindingForAccountApp(e.accountKey,e.appId);if(r){if(r.workspaceId!==e.workspaceId||!Oa(r.rootSegments,n))throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");return r}try{this.sqlite.prepare(`
|
|
75
|
+
`).run(crypto.randomUUID(),e.requestId,e.accountKey,e.source,e.now);}deleteExpired(e){return this.sqlite.prepare("DELETE FROM doc_create_dispatches WHERE dispatched_at <= ?").run(e-qa).changes}};function qt(t){if(Xn(t.accountKey),Po(t.requestId),xo(t.source),typeof t.now!="function"||typeof t.ledger?.peek!="function"||typeof t.ledger.reserve!="function"||typeof t.ledger.reserveForced!="function"||typeof t.ledger.prune!="function"||t.guard!==void 0&&typeof t.guard!="function")throw new Error("INVALID_DOC_CREATE_DISPATCH_GATE");let e=0,n=(()=>{e+=1;let r=t.guard?.();if(r!=null&&typeof r.then=="function")throw Promise.resolve(r).catch(()=>{}),new Error("APP_SYNC_DISPATCH_GUARD_MUST_BE_SYNCHRONOUS");let o=t.now();cn(o);try{let s=t.ledger.reserve({accountKey:t.accountKey,requestId:t.requestId,source:t.source,now:o});if(s.ok===!0||s.ok===!1&&Number.isSafeInteger(s.retryAt)&&s.retryAt>=0)return s;throw new Error("DOC_CREATE_LEDGER_DECISION_INVALID")}catch{throw new je(o+Ba)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function vo(t,e){if(t.oldest===null)throw new Error("DOC_CREATE_LEDGER_WINDOW_EMPTY");let n=t.oldest+6e4;if(!Number.isSafeInteger(n)||n<e)throw new Error("DOC_CREATE_LEDGER_RETRY_AT_INVALID");return n}function Do(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Xn(t.accountKey),Po(t.requestId),xo(t.source),cn(t.now);}function Xn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function Po(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function xo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function cn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var Lo=1e4,$a=12e4,ln=class{constructor(e,n,r,o,s,i){this.dependencies=e;this.scopeRegistry=n;this.sessionFence=r;this.now=o;this.createId=s;this.hasPendingRevoke=i;if(!e.continuation)throw new Error("APP_SYNC_CONTINUATION_CAPABILITY_REQUIRED");if(!e.remote.listGrantDocs||!e.remote.listDeletedRefs||!e.documents.inspectContinuation||!e.documents.applyContinuation)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");this.continuation=e.continuation,this.continuationStore=e.continuation.store;let a=e.continuation.pageSize??100;if(!Number.isSafeInteger(a)||a<1)throw new Error("APP_SYNC_CONTINUATION_PAGE_SIZE_INVALID");this.pageSize=Math.min(a,200);}dependencies;scopeRegistry;sessionFence;now;createId;hasPendingRevoke;continuation;continuationStore;pageSize;async tick(e,n,r,o,s){let i=this.createFenceContext(e,n,r,o);i.fence.assertCurrent(),!(this.continuationStore.beginDiscoveryCycle({binding:e,fence:i.fence,now:this.now()})&&!await this.traverseWithCursorRecovery(i))&&(i.fence.assertCurrent(),await this.processPendingDiscoveries(i));}listConflicts(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n||!e.session.authenticated||e.session.accountKey!==n.accountKey||n.workspaceId!==e.workspaceId||!Mo(n.rootSegments,e.resolvedRootSegments))return [];let r=this.sessionFence.currentToken(n.accountKey);return !r||this.sessionFence.activeAccountKey!==n.accountKey||this.hasPendingRevoke(n.bindingId)?[]:this.continuationStore.listConflicts(n.bindingId).map(({vaultHandle:o,...s})=>({...s,sessionEpoch:r.epoch}))}assertHumanBindingIdentity(e,n){if(ja({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Mo(e.rootSegments,n.resolvedRootSegments))throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new g("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new g("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404);return this.assertHumanBindingIdentity(n,e),n}async readConflictArchive(e){let n=this.requireHumanOperationBinding(e),r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new g("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new g("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);let s=this.archiveFenceGrant(n,o),i=this.createArchiveFenceContext(n,s,r);try{i.fence.assertCurrent();let a=await this.readVerifiedArchive(o,i);return {conflictId:o.conflictId,localVersion:o.localVersion,localFingerprint:o.localFingerprint,remoteRevision:o.remoteRevision,remoteFingerprint:o.remoteFingerprint,markdown:a}}finally{this.sessionFence.release(i.grantToken);}}async purgeAccountData(e){Wa(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new g("APP_SYNC_SESSION_STALE");let r=ae(JSON.stringify(e.resolvedRootSegments)),o=this.continuationStore.getAccountDataPurge(e.requestId);if(o&&(o.bindingId!==e.bindingId||o.accountKey!==e.session.accountKey||o.workspaceId!==e.workspaceId||o.rootFingerprint!==r||o.humanIdentity!==e.humanIdentity))throw new g("APP_SYNC_PURGE_REQUEST_ID_REUSED",409);let s=this.dependencies.store.getBinding(e.bindingId);if(!s){if(o?.state==="complete")return {requestId:e.requestId,status:"purged",remainingArchiveCount:0};throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new g("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),p=u;try{this.continuationStore.beginAccountDataPurge({requestId:e.requestId,binding:s,humanIdentity:e.humanIdentity,fence:u.fence,now:this.now()}),s.grantId&&s.grantGeneration&&this.sessionFence.cancelGrant(s.accountKey,s.grantId,s.grantGeneration),this.sessionFence.release(u.grantToken),p=this.createArchiveFenceContext(s,a,i,c);let f=this.continuationStore.listConflicts(s.bindingId);for(let _ of f)try{p.fence.assertCurrent();let S=_.state==="purging"?_:this.continuationStore.markConflictPurging({conflictId:_.conflictId,fence:p.fence,now:this.now()});S.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:S.vaultHandle,fence:p.fence}),p.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:S.conflictId,expectedVaultHandle:S.vaultHandle,fence:p.fence,now:this.now()});}catch(S){if(!this.isFenceCurrent(p))throw S;let w=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:w}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:p.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),p!==u&&this.sessionFence.release(p.grantToken);}}async resolveConflict(e){Ka(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Fo(e.eligibility)||!Qn(n.status))throw new g("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new g("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let o=er(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new g("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,o.grantId,o.generation),i=this.createFenceContext(n,o,r,s);try{i.fence.assertCurrent();let a=this.continuationStore.getConflict(e.conflictId);if(!a)throw new g("APP_SYNC_CONFLICT_NOT_FOUND",404);if(Uo(a,n),a.state==="purging")throw new g("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new g("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new g("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);this.continuationStore.beginConflictResolution({conflictId:a.conflictId,requestId:e.requestId,humanIdentity:e.humanIdentity,choice:e.choice,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,fence:i.fence,now:this.now()});let u=await this.applyHumanResolution(e,a,i);if(u.status==="stale")throw this.continuationStore.abortConflictResolution({conflictId:a.conflictId,requestId:e.requestId,state:"stale",errorCode:"APP_SYNC_CONFLICT_STALE",fence:i.fence,now:this.now()}),u.refreshed?await this.preserveConflict(tr(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new g("APP_SYNC_CONFLICT_STALE",409);let p=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(p,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Fe(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):Va(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:Zn(a),fence:i.fence,now:this.now()}));}throw a}finally{this.sessionFence.release(s);}}async dispatchReattachCreation(e,n,r,o,s){if(!o.documentId||o.operationKind!=="reattach"||o.bindingId!==e.bindingId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(this.hasPendingRevoke(e.bindingId)||!this.sessionFence.isCurrent(r))return;if(this.dependencies.createLedger)try{let u=this.dependencies.createLedger.peek(e.accountKey,this.now());if(!u.available||u.remaining<1)return}catch(u){this.dependencies.onAdapterError?.(u);return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),$a);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.createFenceContext(e,n,r,a);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,ae(o.ref))){this.dependencies.store.updateCreation(o.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}let u=await this.readRemoteDocument(o.documentId,c);if(U(u.markdown)!==o.fingerprint||u.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,u.markdown).valid){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}if(u.appGrantId===n.grantId&&u.appGrantGeneration===n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);return}let p=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let S=await this.readRemoteDocument(o.documentId,c);if(U(S.markdown)!==o.fingerprint||S.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,S.markdown).valid)return {kind:"changed"};let w=this.dependencies.createLedger?qt({ledger:this.dependencies.createLedger,accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now,guard:()=>{if(c.fence.assertCurrent(),this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING")}}):void 0,E;try{E=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:T,ref:o.ref,requestId:o.requestId,markdown:S.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...w?{dispatchGate:w}:{}});}catch(R){if(R instanceof je)return {kind:"budget_deferred",retryAt:R.retryAt};throw R}if(w&&w.calls===0){let R=new g("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(I){this.dependencies.onAdapterError?.(I);}throw this.dependencies.onAdapterError?.(R),R}return c.fence.assertCurrent(),{kind:"created",created:E}}});if(c.fence.assertCurrent(),p.status==="deferred"){let S=this.now();return this.deferClaim(i,p.retryAt,S),void 0}if(p.value.kind==="budget_deferred"){let S=this.now();return this.deferClaim(i,p.value.retryAt,S),void 0}if(p.value.kind==="changed"){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let f=p.value.created;if(f.docId!==o.documentId||f.appGrantId!==n.grantId||f.appGrantGeneration!==n.generation||f.markdownVersion!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}let _=await this.readRemoteDocument(o.documentId,c);if(_.appGrantId!==n.grantId||_.appGrantGeneration!==n.generation||_.markdownVersion!==o.fingerprint||U(_.markdown)!==o.fingerprint){this.dependencies.store.updateCreation(o.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()}),this.markPendingForReconcile(e,n,o.ref,c,"DOC_SYNC_REMOTE_STATE_MISMATCH");return}this.dependencies.store.updateCreation(o.jobId,{status:"completed",nextAttemptAt:0,now:this.now()}),this.markReattached(e,n,o.ref,c);}catch(u){if(!this.isFenceCurrent(c))return;if(gt(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let p=za(u);this.dependencies.store.updateCreation(o.jobId,{status:p?"waiting":"failed",nextAttemptAt:p?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),p&&this.markPendingForReconcile(e,n,o.ref,c,"APP_SYNC_REATTACH_RESPONSE_UNKNOWN");}finally{this.sessionFence.release(a);}}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}async traverseWithCursorRecovery(e){let n=0;for(;;)try{return await this.traverseGrantDocs(e),await this.traverseDeletedRefs(e),!0}catch(r){if(!Ya(r))throw r;let o=await this.readActiveGrant(e);if(this.continuationStore.resetDiscoveryCycle({binding:e.binding,fence:e.fence,now:this.now()}),!o)return false;if(n+=1,n>1)throw r}}async traverseGrantDocs(e){let n=this.dependencies.remote.listGrantDocs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.docsComplete)return;let i=s.docsCursor;if(i!==null){if(r.has(i))throw new g("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateGrantDocsPage(a,e),a.items.length>this.pageSize)throw new g("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new g("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new g("APP_SYNC_DOCS_TRAVERSAL_LIMIT");this.continuationStore.commitGrantDocsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}async traverseDeletedRefs(e){let n=this.dependencies.remote.listDeletedRefs;if(!n)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let r=new Set,o=0;for(;;){e.fence.assertCurrent();let s=this.continuationStore.getDiscoveryCheckpoint(e.binding.bindingId);if(!s||s.deletedComplete)return;let i=s.deletedCursor;if(i!==null){if(r.has(i))throw new g("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:T,grantId:e.grant.grantId,generation:e.grant.generation,cursor:i,limit:this.pageSize,signal:e.fence.signal,fence:e.fence});if(e.fence.assertCurrent(),this.validateDeletedRefsPage(a,e),a.items.length>this.pageSize)throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new g("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Lo)throw new g("APP_SYNC_DELETED_REFS_TRAVERSAL_LIMIT");this.continuationStore.commitDeletedRefsPage({binding:e.binding,fence:e.fence,items:a.items,expectedCursor:i,nextCursor:a.nextCursor,now:this.now()});}}validateGrantDocsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new g("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!J(o.docId,128)||!J(o.title,80)||!Number.isSafeInteger(o.currentRevision)||o.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(o.markdownVersion)||!Number.isSafeInteger(o.appGrantGeneration)||o.appGrantGeneration<1||o.appGrantGeneration>n.grant.generation||typeof o.needsReattach!="boolean"||!un(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new g("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new g("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==T||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!un(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!un(o.deletedAt)||r.has(o.refHash))throw new g("APP_SYNC_DELETED_REFS_PAGE_INVALID");r.add(o.refHash);}}async readActiveGrant(e){e.fence.assertCurrent();let n=await this.dependencies.remote.readGrant({accountKey:e.binding.accountKey,appId:T,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==T||n.available!==true||n.status!=="active"||!n.grant?false:n.grant.grantId===e.grant.grantId&&n.grant.generation===e.grant.generation&&n.grant.scopeVersion===e.grant.scopeVersion&&this.scopeRegistry.matchesDefinition(n.grant.scopeVersion,n.grant.scope)}async processPendingDiscoveries(e){let n=this.continuationStore.listPendingDiscoveries(e.binding.bindingId,e.grant.grantId,e.grant.generation,500);for(let r of n){if(!this.isFenceCurrent(e))return;try{this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"processing",errorCode:null},now:this.now()});let o=await this.reconcileDiscoveredDocument(r,e);if(o==="complete")this.continuationStore.completePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence});else if(o==="retry")this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",attempts:r.attempts+1},now:this.now()});else {this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:"DOC_APP_GRANT_REQUIRED"},now:this.now()});return}}catch(o){if(!this.isFenceCurrent(e))return;if(gt(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o)},now:this.now()});return}this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:Zn(o),needsReconcile:true,attempts:r.attempts+1},now:this.now()});}}}async reconcileDiscoveredDocument(e,n){if(n.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(n.binding.accountKey,T,ae(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(E=>E.accountKey===n.binding.accountKey&&E.ref===e.ref);if(r.exists){if(o.some(I=>I.state==="kept_both"&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint))return "complete";let R=o.find(I=>(I.state==="open"||I.state==="resolving")&&I.preservationStatus==="ready"&&I.vaultHandle!==null&&I.localVersion===r.localVersion&&I.localFingerprint===r.localFingerprint&&I.documentId===e.docId&&I.remoteRevision===e.listedRevision&&I.remoteFingerprint===e.listedFingerprint);if(R)return R.state==="open"&&(R.grantId!==n.grant.grantId||R.grantGeneration!==n.grant.generation||R.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:R.conflictId,grant:n.grant,needsReattach:e.needsReattach,fence:n.fence,now:this.now()}),"complete"}let s=r.baseline,i=s!==null&&r.exists&&r.localFingerprint!==s.markdownVersion,a=s!==null&&(e.listedRevision!==s.revision||e.listedFingerprint!==s.markdownVersion);if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&!i)return "complete";if(s&&!e.needsReconcile&&!e.needsReattach&&r.exists&&!a&&i)return this.applyConditionalSave(e.ref,e.docId,r,e.listedRevision,e.listedFingerprint,false,n);let c=await this.readPendingDocument(e,n);if(!c)return "complete";let u=c,p=e;if(e.needsReattach){let E=await this.queueOrConfirmReattachment(e,c,n);if(!E)return "retry";u=E.document,p=E.pending;}let f=await this.inspectLocal(e.ref,n);if(f.exists&&f.localFingerprint===u.markdownVersion){let E={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,expectedLocalFingerprint:f.localFingerprint,fence:n.fence},R=await this.applyEffect(E,n);if(R.status==="applied")return this.recordOutcome(n,e.ref,f.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(R.status==="stale_local")return this.reconcileAfterLocalRace(p,u,n);if(R.status==="conflict")return this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n);if(R.status==="deferred"||R.status==="failed")return "retry"}let _=f.baseline??s;if(!f.exists){let E={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!_)return this.preserveConflict(p,f,u,n);let S=f.localFingerprint!==_.markdownVersion,w=u.currentRevision!==_.revision||u.markdownVersion!==_.markdownVersion;if(S&&w)return this.preserveConflict(p,f,u,n);if(w&&!S){let E={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,fence:n.fence},R=await this.applyEffect(E,n);return R.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):R.status==="stale_local"?this.reconcileAfterLocalRace(p,u,n):R.status==="conflict"?this.preserveConflict(p,await this.inspectLocal(e.ref,n),u,n):"retry"}return S&&!w?this.applyConditionalSave(e.ref,u.docId,f,u.currentRevision,u.markdownVersion,p.needsReattach,n):"complete"}async inspectLocal(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.inspectContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=await r({binding:n.binding,grant:n.grant,ref:e,fence:n.fence});if(n.fence.assertCurrent(),!o||typeof o.exists!="boolean")throw new g("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!nr(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||U(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new g("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new g("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.baseline&&(!Number.isSafeInteger(o.baseline.revision)||o.baseline.revision<0||!/^sha256:[0-9a-f]{64}$/.test(o.baseline.markdownVersion)))throw new g("APP_SYNC_BASELINE_INVALID");return o}async readPendingDocument(e,n){n.fence.assertCurrent();try{let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e.docId,signal:n.fence.signal,fence:n.fence});return n.fence.assertCurrent(),this.validateRemoteDocument(r,e,n),r}catch(r){if(n.fence.assertCurrent(),Fe(r)==="DOC_NOT_FOUND"&&qo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:ae(e.ref),documentId:e.docId,fence:n.fence,now:this.now()}),null;throw r}}validateRemoteDocument(e,n,r){if(!e||e.docId!==n.docId||!Number.isSafeInteger(e.currentRevision)||e.currentRevision<0||!/^sha256:[0-9a-f]{64}$/.test(e.markdownVersion)||U(e.markdown)!==e.markdownVersion||!J(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let o=e.appGrantId===r.grant.grantId&&e.appGrantGeneration===r.grant.generation,s=e.appGrantGeneration===n.appGrantGeneration&&e.appGrantGeneration<=r.grant.generation;if(!o&&!(n.needsReattach&&s))throw new g("DOC_APP_GRANT_STALE",409)}async queueOrConfirmReattachment(e,n,r){if(n.appGrantId===r.grant.grantId&&n.appGrantGeneration===r.grant.generation){this.markReattached(r.binding,r.grant,e.ref,r,n);let a=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:n,pending:a}}if(this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:e.ref,documentId:n.docId,fingerprint:n.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}).status!=="completed")return this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:e.grantId,generation:e.grantGeneration,ref:e.ref,fence:r.fence,patch:{status:"waiting",errorCode:"APP_SYNC_REATTACH_PENDING",needsReconcile:true},now:this.now()}),null;let s=await this.readRemoteDocument(n.docId,r);if(s.appGrantId!==r.grant.grantId||s.appGrantGeneration!==r.grant.generation)return null;if(U(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);this.markReattached(r.binding,r.grant,e.ref,r,s);let i=this.continuationStore.getPendingDiscovery(e.bindingId,e.grantId,e.grantGeneration,e.ref)??{...e,needsReattach:false,appGrantGeneration:r.grant.generation};return {document:s,pending:i}}markReattached(e,n,r,o,s){this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)&&this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{needsReattach:false,needsReconcile:true,...s?{listedRevision:s.currentRevision,listedFingerprint:s.markdownVersion}:{},appGrantGeneration:n.generation,status:"waiting",errorCode:null},now:this.now()});}markPendingForReconcile(e,n,r,o,s){!this.continuationStore.getPendingDiscovery(e.bindingId,n.grantId,n.generation,r)||!this.isFenceCurrent(o)||this.continuationStore.updatePendingDiscovery({bindingId:e.bindingId,grantId:n.grantId,generation:n.generation,ref:r,fence:o.fence,patch:{status:"waiting",needsReconcile:true,errorCode:s},now:this.now()});}async applyConditionalSave(e,n,r,o,s,i,a){let c={kind:"conditional_save",binding:a.binding,grant:a.grant,ref:e,documentId:n,expectedLocalVersion:r.localVersion,expectedRemoteRevision:o,expectedRemoteFingerprint:s,markdown:r.markdown,markdownFingerprint:r.localFingerprint,needsReattach:i,fence:a.fence,beforeDispatch:async()=>{if(a.fence.assertCurrent(),this.dependencies.store.hasDeletedRef(a.binding.accountKey,T,ae(e)))return {ok:false,reason:"deleted"};let S=await this.inspectLocal(e,a);return !S.exists||S.localVersion!==r.localVersion||S.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:S.localVersion,markdown:S.markdown,fingerprint:S.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(S){throw this.isFenceCurrent(a)&&!gt(S)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),S}if(u.status==="applied")return this.recordOutcome(a,e,r.localFingerprint,r.localFingerprint,n,"synced",null),"complete";if(u.status==="deferred"||u.status==="failed")return u.dispatch==="attempted"&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),"retry";let p=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),f=await this.readRemoteById(n,p,a);if(!f)return "complete";let _=await this.inspectLocal(e,a);if(u.status==="conflict"||_.exists&&_.localFingerprint!==f.markdownVersion)return this.preserveConflict(p??tr(a,e,n,f),_,f,a);if(_.exists&&_.localFingerprint===f.markdownVersion){let S={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:f,expectedLocalVersion:_.localVersion,expectedLocalFingerprint:_.localFingerprint,fence:a.fence};return (await this.applyEffect(S,a)).status==="applied"?(this.recordOutcome(a,e,_.localFingerprint,f.markdownVersion,n,"synced",null),"complete"):"retry"}return "retry"}async applyEffect(e,n){n.fence.assertCurrent();let r=this.dependencies.documents.applyContinuation;if(!r)throw new Error("APP_SYNC_CONTINUATION_PORT_REQUIRED");let o=false,s;if(e.kind==="conditional_save"){let i={...e,beforeDispatch:async()=>{o=true;let a=await e.beforeDispatch();return n.fence.assertCurrent(),a}};if(s=await r(i),s.dispatch==="attempted"&&!o)throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new g("APP_SYNC_ADAPTER_DID_NOT_DISPATCH")}else s=await r(e);return n.fence.assertCurrent(),s}async reconcileAfterLocalRace(e,n,r){let o=await this.inspectLocal(e.ref,r);if(!o.exists){let s={kind:"create_absent",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:null,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,n.markdownVersion,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}if(o.localFingerprint===n.markdownVersion){let s={kind:"attach_equal",binding:r.binding,grant:r.grant,ref:e.ref,document:n,expectedLocalVersion:o.localVersion,expectedLocalFingerprint:o.localFingerprint,fence:r.fence};return (await this.applyEffect(s,r)).status==="applied"?(this.recordOutcome(r,e.ref,o.localFingerprint,n.markdownVersion,n.docId,"synced",null),"complete"):"retry"}return this.preserveConflict(e,o,n,r)}async preserveConflict(e,n,r,o){if(!n.exists)return "retry";let s=o.fence.rootFingerprint,i=`c_${ae(JSON.stringify([o.binding.bindingId,o.grant.grantId,o.grant.generation,e.ref,n.localVersion,r.currentRevision,r.markdownVersion]))}`,a={conflictId:i,bindingId:o.binding.bindingId,accountKey:o.binding.accountKey,workspaceId:o.binding.workspaceId,rootFingerprint:s,grantId:o.grant.grantId,grantGeneration:o.grant.generation,scopeVersion:o.grant.scopeVersion,ref:e.ref,documentId:r.docId,localVersion:n.localVersion,localFingerprint:n.localFingerprint,baselineRevision:n.baseline?.revision??null,baselineFingerprint:n.baseline?.markdownVersion??null,remoteRevision:r.currentRevision,remoteFingerprint:r.markdownVersion,needsReattach:e.needsReattach,vaultHandle:null,preservationStatus:"pending",state:"open",supersededBy:null,resolutionRequestId:null,resolutionChoice:null,cleanupPending:false,createdAt:this.now(),updatedAt:this.now()},c=this.continuationStore.putConflict({conflict:a,fence:o.fence});if(this.recordOutcome(o,e.ref,n.localFingerprint,n.baseline?.markdownVersion??null,r.docId,"conflict","APP_SYNC_CONFLICT"),c.preservationStatus==="ready"&&c.vaultHandle)return this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),"complete";try{o.fence.assertCurrent();let u=await this.continuation.conflictVault.preserve({accountKey:o.binding.accountKey,conflictId:i,markdown:r.markdown,fingerprint:r.markdownVersion,fence:o.fence});if(o.fence.assertCurrent(),!nr(u.handle)||u.fingerprint!==r.markdownVersion||U(r.markdown)!==u.fingerprint)throw new g("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return c=this.continuationStore.putConflict({conflict:{...a,vaultHandle:u.handle,preservationStatus:"ready",updatedAt:this.now()},fence:o.fence}),c.preservationStatus==="ready"&&this.continuationStore.supersedeOpenConflicts({bindingId:o.binding.bindingId,ref:e.ref,supersededBy:i,fence:o.fence,now:this.now()}),c.preservationStatus==="ready"?"complete":"retry"}catch(u){if(!this.isFenceCurrent(o))throw u;return this.continuationStore.putConflict({conflict:{...a,preservationStatus:"failed",updatedAt:this.now()},fence:o.fence}),this.markPendingForReconcile(o.binding,o.grant,e.ref,o,"APP_SYNC_CONFLICT_ARCHIVE_FAILED"),"retry"}}recordOutcome(e,n,r,o,s,i,a){this.continuationStore.recordContinuationOutcome({binding:e.binding,grant:e.grant,ref:n,sourceFingerprint:r,syncedFingerprint:o,documentId:s,status:i,errorCode:a,fence:e.fence,now:this.now()});}async readRemoteById(e,n,r){return n?this.readPendingDocument(n,r):this.readRemoteDocument(e,r)}async readRemoteDocument(e,n){n.fence.assertCurrent();let r=await this.dependencies.remote.readDocument({accountKey:n.binding.accountKey,docId:e,signal:n.fence.signal,fence:n.fence});if(n.fence.assertCurrent(),!r||r.docId!==e||U(r.markdown)!==r.markdownVersion)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);return r}async applyHumanResolution(e,n,r){if(r.fence.assertCurrent(),n.state==="superseded"&&e.choice==="keep_both"){let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{status:"stale"}:(await this.readVerifiedArchive(n,r),{status:"resolved"})}let o=await this.readRemoteDocument(n.documentId,r);if(!this.scopeRegistry.validateFrontMatter(n.ref,o.markdown).valid)throw new g("DOC_SYNC_REMOTE_STATE_MISMATCH",409);let s=o.appGrantId===r.grant.grantId&&o.appGrantGeneration===r.grant.generation;if(!s&&(!n.needsReattach||o.appGrantGeneration>=r.grant.generation))throw new g("DOC_APP_GRANT_STALE",409);let i=await this.inspectLocal(n.ref,r);if(!i.exists)return {status:"stale"};let a=o.currentRevision===e.expectedRemoteRevision&&o.markdownVersion===e.expectedRemoteFingerprint,c=o.currentRevision===n.remoteRevision&&o.markdownVersion===n.remoteFingerprint;if(!a||!c)return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};if(!(i.localVersion===e.expectedLocalVersion&&i.localFingerprint===n.localFingerprint))return i.localFingerprint===o.markdownVersion&&e.choice!=="keep_both"?{status:"resolved"}:{status:"stale",refreshed:{local:i,remote:o}};let p=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let E={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:p},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},R;try{R=await this.applyEffect(E,r);}catch(I){throw gt(I)?I:new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(R.status==="applied")return {status:"resolved"};if(R.status==="stale_local")return i=await this.inspectLocal(n.ref,r),i.exists&&i.localFingerprint===o.markdownVersion?{status:"resolved"}:{status:"stale",...i.exists?{refreshed:{local:i,remote:o}}:{}};if(R.status==="conflict"){let I=await this.readRemoteDocument(n.documentId,r),Ae=await this.inspectLocal(n.ref,r);return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}}}if(R.status==="failed"||R.status==="deferred")throw R.dispatch==="attempted"?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new g(R.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let E=this.continuationStore.enqueueReattachJob({binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,fingerprint:o.markdownVersion,requestId:this.createId(),jobId:this.createId(),now:this.now(),fence:r.fence}),R={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};E.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,E,R);let I=await this.readRemoteDocument(n.documentId,r);if(I.appGrantId!==r.grant.grantId||I.appGrantGeneration!==r.grant.generation||I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion){let Ae=await this.inspectLocal(n.ref,r);if(I.currentRevision!==o.currentRevision||I.markdownVersion!==o.markdownVersion)return {status:"stale",...Ae.exists?{refreshed:{local:Ae,remote:I}}:{}};throw new g("APP_SYNC_REATTACH_PENDING")}}let _=false,S={kind:"conditional_save",binding:r.binding,grant:r.grant,ref:n.ref,documentId:n.documentId,expectedLocalVersion:e.expectedLocalVersion,expectedRemoteRevision:e.expectedRemoteRevision,expectedRemoteFingerprint:e.expectedRemoteFingerprint,markdown:i.markdown,markdownFingerprint:i.localFingerprint,needsReattach:false,fence:r.fence,beforeDispatch:async()=>{_=true,r.fence.assertCurrent();let E=await this.inspectLocal(n.ref,r);return !E.exists||E.localVersion!==e.expectedLocalVersion||E.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:E.localVersion,markdown:E.markdown,fingerprint:E.localFingerprint}}},w;try{w=await this.applyEffect(S,r);}catch(E){throw gt(E)?E:_?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):E}if(w.status==="applied")return {status:"resolved"};if(w.status==="conflict"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return {status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="stale_local"){let E=await this.readRemoteDocument(n.documentId,r),R=await this.inspectLocal(n.ref,r);return R.exists&&R.localFingerprint===E.markdownVersion?{status:"resolved"}:{status:"stale",...R.exists?{refreshed:{local:R,remote:E}}:{}}}if(w.status==="failed"||w.status==="deferred")throw w.dispatch==="attempted"?new g("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new g(w.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}async cleanupResolvedConflict(e,n){let r=e;if(this.recordOutcome(n,r.ref,r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.state==="kept_both"?r.baselineFingerprint:r.resolutionChoice==="use_cloud"?r.remoteFingerprint:r.localFingerprint,r.documentId,r.state==="kept_both"?"conflict":"synced",r.state==="kept_both"?"APP_SYNC_CONFLICT_KEPT_BOTH":null),r.cleanupPending&&r.vaultHandle)try{n.fence.assertCurrent(),await this.continuation.conflictVault.remove({accountKey:n.binding.accountKey,handle:r.vaultHandle,fence:n.fence}),n.fence.assertCurrent(),this.continuationStore.finishConflictArchiveCleanup({conflictId:r.conflictId,fence:n.fence,now:this.now()}),r=this.continuationStore.getConflict(r.conflictId)??r;}catch{}let{vaultHandle:o,...s}=r;return {status:r.state==="kept_both"?"kept_both":"resolved",conflict:{...s,sessionEpoch:n.session.epoch},cleanupPending:r.cleanupPending}}async readVerifiedArchive(e,n){if(e.preservationStatus!=="ready"||!e.vaultHandle)throw new g("APP_SYNC_CONFLICT_NOT_PRESERVED",409);n.fence.assertCurrent();let r=await this.continuation.conflictVault.read({accountKey:n.binding.accountKey,handle:e.vaultHandle,expectedFingerprint:e.remoteFingerprint,fence:n.fence});if(n.fence.assertCurrent(),r.fingerprint!==e.remoteFingerprint||U(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new g("APP_SYNC_CONFLICT_ARCHIVE_VERIFY_FAILED");return r.markdown}async refreshConflictAfterStale(e,n){n.fence.assertCurrent();let r=await this.inspectLocal(e.ref,n),o=await this.readRemoteDocument(e.documentId,n);r.exists&&(r.localVersion===e.localVersion&&r.localFingerprint===e.localFingerprint&&o.docId===e.documentId&&o.currentRevision===e.remoteRevision&&o.markdownVersion===e.remoteFingerprint||await this.preserveConflict(tr(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?er(e):{grantId:n.grantId,appId:T,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:_e}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return er(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:T,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:_e}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new g("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=ae(JSON.stringify(e.rootSegments)),a;a=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:i,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:s.signal,assertCurrent:()=>this.assertArchiveFenceCurrent(e,n,r,s,o)});let c={binding:e,grant:n,session:r,grantToken:s,fence:a};return a.assertCurrent(),c}assertArchiveFenceCurrent(e,n,r,o,s){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||this.sessionFence.activeAccountKey!==e.accountKey||this.sessionFence.activeSessionEpoch!==r.epoch||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.generation!==n.generation)throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let i=this.dependencies.store.getBinding(e.bindingId);if(!i){let a=s.purgeRequestId?this.continuationStore.getAccountDataPurge(s.purgeRequestId):void 0;if(a?.state==="complete"&&a.bindingId===e.bindingId&&a.accountKey===e.accountKey&&a.workspaceId===e.workspaceId&&a.rootFingerprint===ae(JSON.stringify(e.rootSegments)))return;throw new g("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||ae(JSON.stringify(i.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new g("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new g("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Qn(i.status))throw new g("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new g("DOC_APP_GRANT_STALE",409)}createFenceContext(e,n,r,o){if(!e.grantId||!e.grantGeneration||!e.scopeVersion||e.grantId!==n.grantId||e.grantGeneration!==n.generation||e.scopeVersion!==n.scopeVersion||n.scopeVersion!==this.scopeRegistry.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);let s=ae(JSON.stringify(e.rootSegments)),i;i=Object.freeze({accountKey:e.accountKey,sessionEpoch:r.epoch,bindingId:e.bindingId,workspaceId:e.workspaceId,rootFingerprint:s,grantId:n.grantId,grantGeneration:n.generation,scopeVersion:n.scopeVersion,signal:o.signal,assertCurrent:()=>this.assertFenceCurrent(e,n,r,o)});let a={binding:e,grant:n,session:r,grantToken:o,fence:i};return i.assertCurrent(),a}assertFenceCurrent(e,n,r,o){if(!this.sessionFence.isCurrent(r)||!this.sessionFence.isCurrent(o)||o.grantId!==n.grantId||o.generation!==n.generation||o.accountKey!==e.accountKey)throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||ae(JSON.stringify(s.rootSegments))!==ae(JSON.stringify(e.rootSegments)))throw new g("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new g("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new g(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},Ga=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","TOKEN_EXPIRED","DOC_SCOPE_REQUIRED","DOC_PILOT_NOT_ALLOWED","DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE","DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH","APP_SYNC_SESSION_STALE","APP_SYNC_ROOT_STALE","APP_SYNC_REVOKE_PENDING"]);function ae(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Mo(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function J(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function un(t){if(typeof t!="string"||t.length>40)return false;let e=Date.parse(t);return Number.isFinite(e)&&new Date(e).toISOString()===t}function nr(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Fo(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Qn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function ja(t){if(!t||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Wa(t){if(!t||t.intent!=="device_account_data_deleted"||!J(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new g("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function Ka(t){if(!t||!t.session||!J(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!J(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!J(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!J(t.conflictId,128)||!J(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!J(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!nr(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new g("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Fe(t){return t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error&&/^[A-Z0-9_:-]{1,128}$/.test(t.message)?t.message:"APP_SYNC_OPERATION_FAILED"}function qo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function gt(t){return Ga.has(Fe(t))}function Va(t){return Fe(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Fe(t)==="APP_SYNC_REATTACH_PENDING"}function Zn(t){let e=Fe(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function za(t){if(gt(t))return false;let e=qo(t);return e===408||e===409||e===429||e!==void 0&&e>=500||new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET","APP_SYNC_REATTACH_RESPONSE_UNKNOWN","APP_SYNC_SAVE_RESPONSE_UNKNOWN"]).has(Fe(t))}function Ya(t){return Fe(t)==="DOC_APP_GRANT_STALE"||Fe(t)==="DOC_APP_CURSOR_INVALID"}function er(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new g("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:T,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:_e}}function Uo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==ae(JSON.stringify(e.rootSegments))||t.scopeVersion!==Xe)throw new g("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function tr(t,e,n,r){return {bindingId:t.binding.bindingId,accountKey:t.binding.accountKey,grantId:t.grant.grantId,grantGeneration:t.grant.generation,ref:e,docId:n,listedRevision:r.currentRevision,listedFingerprint:r.markdownVersion,appGrantGeneration:r.appGrantGeneration,needsReattach:r.appGrantId!==t.grant.grantId||r.appGrantGeneration!==t.grant.generation,needsReconcile:true,status:"waiting",errorCode:null,attempts:0,updatedAt:Date.now()}}var Xa=12e4,Qa=1e4,Za=1e3,ed=15*6e4,td=4,rr=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Bt=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),or=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),pn=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),nd=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),g=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},ar=class{constructor(e){this.dependencies=e;if(e.continuation&&e.continuation.store!==e.store)throw new Error("APP_SYNC_CONTINUATION_STORE_MISMATCH");if(e.createLedger&&e.remote.capabilities?.dispatchGate!==true)throw new Error("APP_SYNC_DISPATCH_GATE_UNSUPPORTED");if(e.createLedger&&!e.store.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");this.scopeRegistry=e.scopeRegistry??new Ut,this.sessionFence=e.sessionFence??new Ft,this.now=e.now??Date.now,this.createId=e.createId??crypto.randomUUID,this.continuationRuntime=e.continuation?new ln(e,this.scopeRegistry,this.sessionFence,this.now,this.createId,n=>this.hasPendingRevoke(n)):null;}dependencies;scopeRegistry;sessionFence;now;createId;scanRuns=new Map;tickRuns=new Map;remoteReadSemaphore=new cr(td);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=_t(e.resolvedRootSegments);if(!r)throw new Error("APP_SYNC_ROOT_INVALID");if(typeof e.workspaceId!="string"||e.workspaceId.trim().length===0||e.workspaceId.length>256)throw new Error("APP_SYNC_WORKSPACE_INVALID");let o=this.sessionFence.activeAccountKey,s=this.sessionFence.activate(n);o&&o!==n&&await this.suspendBindingsForAccount(o,"account_switch");let i=this.dependencies.store.bind({bindingId:this.createId(),accountKey:n,workspaceId:e.workspaceId,appId:T,rootSegments:r,now:this.now()});return this.isCurrent(s)?(this.hasPendingRevoke(i.bindingId)?await this.holdPendingRevoke(i):this.isEligible(e.eligibility)?this.dependencies.store.updateBinding(i.bindingId,{status:"checking"},this.now()):(this.dependencies.store.updateBinding(i.bindingId,{status:"unavailable"},this.now()),this.sessionFence.suspend(n),await this.dependencies.documents.suspendBinding({binding:i,grantId:i.grantId,generation:i.grantGeneration,reason:"ineligible"})),this.dependencies.store.getBinding(i.bindingId)??i):i}scan(e,n){let r=this.dependencies.store.getBinding(e),o=r!==void 0&&(!n.session.authenticated||!n.session.accountKey||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility));o&&(this.scanEpoch+=1,this.sessionFence.suspend(r.accountKey));let s=`${e}:${n.session.accountKey??"signed-out"}:${this.scanEpoch}:${n.eligibility?.featureEnabled===true?1:0}:${n.eligibility?.ownerAllowlisted===true?1:0}`,i=o?void 0:this.scanRuns.get(s);if(i)return i;let a=this.performScan(e,n).finally(()=>{this.scanRuns.get(s)===a&&this.scanRuns.delete(s);});return o||this.scanRuns.set(s,a),a}tick(e,n){let r=this.dependencies.store.getBinding(e);r&&(!n.session.authenticated||n.session.accountKey!==r.accountKey||!this.isEligible(n.eligibility))&&this.sessionFence.suspend(r.accountKey);let o=this.tickRuns.get(e),i=(o?o.catch(()=>{}):Promise.resolve()).then(()=>this.performTick(e,n)).finally(()=>{this.tickRuns.get(e)===i&&this.tickRuns.delete(e);});return this.tickRuns.set(e,i),i}async performTick(e,n){let r=await this.scan(e,n),o=this.dependencies.store.getBinding(e);if(o&&this.hasPendingRevoke(e))return await this.holdPendingRevoke(o),this.snapshot(e);if(!r.binding||!this.isTransferStatus(r.status))return r;let s=this.dependencies.store.getBinding(e);if(!s?.grantId||!s.grantGeneration||!s.scopeVersion)return this.snapshot(e);let i=await this.activateSession(s.accountKey);if(!i||!this.isCurrent(i))return this.snapshot(e);let a=this.grantFromBinding(s),c=this.sessionFence.captureGrant(i,a.grantId,a.generation);try{if(this.continuationRuntime&&await this.continuationRuntime.tick(s,a,i,c,n),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),p=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),f=this.limitCreationClaims(s.accountKey,p);if(await Promise.all([...u.filter(_=>!this.continuationRuntime&&this.shouldReconcile(_,a)).map(_=>this.reconcileExisting(s,a,c,_)),...f.map(_=>this.dispatchCreation(s,a,i,_,n))]),this.hasPendingRevoke(e)){let _=this.dependencies.store.getBinding(e);return _&&await this.holdPendingRevoke(_),this.snapshot(e)}return !this.isCurrent(i)||!this.isCurrent(c)?this.snapshot(e):(this.refreshBindingStatus(e),this.snapshot(e))}finally{this.sessionFence.release(c);}}limitCreationClaims(e,n){let r=this.dependencies.createLedger;if(!r)return n;try{let o=r.peek(e,this.now());return o.available?n.slice(0,o.remaining):[]}catch(o){return this.dependencies.onAdapterError?.(o),[]}}makeDispatchGate(e){let n=this.dependencies.createLedger;if(n)return qt({ledger:n,accountKey:e.accountKey,requestId:e.requestId,source:e.source,now:this.now,guard:()=>{if(e.token.signal.aborted||!this.isCurrent(e.token)||!this.bindingHasGrant(e.bindingId,e.grant))throw new g("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new g("APP_SYNC_REVOKE_PENDING")}})}deferClaim(e,n,r){let o=this.dependencies.store;if(this.dependencies.createLedger){if(!o.deferCreation)throw new Error("APP_SYNC_DISPATCH_LEDGER_STORE_UNSUPPORTED");return o.deferCreation(e,n,r)}return o.updateCreation(e.jobId,{status:"waiting",nextAttemptAt:n,now:r}),true}recordMissingDispatchGate(e){let n=new g("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger?.reserveForced({...e,now:this.now()});}catch(r){this.dependencies.onAdapterError?.(r);}return this.dependencies.onAdapterError?.(n),n}async suspendAccount(e){/^[0-9a-f]{64}$/.test(e)&&(this.scanEpoch+=1,this.sessionFence.suspend(e),await this.suspendBindingsForAccount(e,"logout"));}async invalidateGrant(e){let n=this.dependencies.store.getBinding(e.bindingId),r=e.session.accountKey;!n||!e.session.authenticated||!r||n.accountKey!==r||n.grantId!==e.grantId||n.grantGeneration!==e.generation||(this.scanEpoch+=1,this.sessionFence.suspend(r),this.sessionFence.cancelGrant(r,e.grantId,e.generation),this.dependencies.store.invalidateGrantJobs(n.bindingId,e.grantId,e.generation,this.now()),this.dependencies.store.updateBinding(n.bindingId,{status:this.hasPendingRevoke(n.bindingId)?"stopping":"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:n,grantId:e.grantId,generation:e.generation,reason:"revoked"}));}async beginControlRequest(e){let{binding:n,accountKey:r,rootFingerprint:o}=this.validateControlIdentity(e),s=e.requestId;if(typeof s!="string"||s.length<1||s.length>128||s.includes("\0"))throw new Error("APP_SYNC_REQUEST_ID_INVALID");if(e.kind!=="connect"&&e.kind!=="revoke")throw new Error("APP_SYNC_CONTROL_REQUEST_KIND_INVALID");if(e.kind==="connect"&&n.grantId&&n.grantGeneration){let p=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||p!==void 0)&&!this.dependencies.store.getControlRequest(s))throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_GRANTED")}let i=e.kind==="revoke"?e.grantId??null:null,a=e.kind==="revoke"?e.generation??null:null;if(e.kind==="revoke"&&(!i||!Number.isSafeInteger(a)||a<1||i!==n.grantId||a!==n.grantGeneration))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");if(e.kind==="connect"&&(e.grantId!=null||e.generation!=null))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let c=this.now(),u=this.dependencies.store.beginControlRequest({requestId:s,bindingId:n.bindingId,accountKey:r,appId:T,workspaceId:n.workspaceId,rootFingerprint:o,kind:e.kind,state:"pending",grantId:i,generation:a,createdAt:c,updatedAt:c,resolvedAt:null,resolution:null,resolutionId:null});return u.kind==="revoke"&&(u.state==="pending"||u.state==="unknown")&&await this.holdPendingRevoke(n),u}getControlRequest(e){let{rootFingerprint:n}=this.validateControlIdentity(e),r=this.dependencies.store.getControlRequest(e.requestId);if(r&&!od(r,e,n))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return r}getPendingControlRequest(e){let{binding:n}=this.validateControlIdentity(e);return this.dependencies.store.getPendingControlRequest(n.bindingId)}async markControlRequestUnknown(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(n.state==="unknown")return n;if(n.state!=="pending")throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED");let r=this.dependencies.store.updateControlRequest(n.requestId,{state:"unknown",grantId:n.grantId,generation:n.generation,resolution:null,resolutionId:null,resolvedAt:null,now:this.now()});if(r.kind==="revoke"){let o=this.dependencies.store.getBinding(r.bindingId);o&&await this.holdPendingRevoke(o);}return r}async resolveControlRequest(e){let n=this.getControlRequest(e);if(!n)throw new Error("APP_SYNC_CONTROL_REQUEST_NOT_FOUND");if(e.outcome!=="confirmed"&&e.outcome!=="failed")throw new Error("APP_SYNC_CONTROL_REQUEST_OUTCOME_INVALID");if(e.resolution!=="remote"&&e.resolution!=="human")throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_INVALID");if(typeof e.resolutionId!="string"||e.resolutionId.length<1||e.resolutionId.length>128||e.resolutionId.includes("\0"))throw new Error("APP_SYNC_CONTROL_REQUEST_RESOLUTION_ID_INVALID");if(n.state==="confirmed"||n.state==="failed"){if(n.state===e.outcome&&n.resolution===e.resolution&&n.resolutionId===e.resolutionId)return n;throw new Error("APP_SYNC_CONTROL_REQUEST_ALREADY_RESOLVED")}let r=n.grantId,o=n.generation;if(n.kind==="connect"&&e.outcome==="confirmed"){let c=e.observedGrant;if(!c||c.appId!==T||!c.grantId||!Number.isSafeInteger(c.generation)||c.generation<1||!this.scopeRegistry.matchesDefinition(c.scopeVersion,c.scope))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_INVALID");r=c.grantId,o=c.generation;}let s=this.now(),i=this.dependencies.store.updateControlRequest(n.requestId,{state:e.outcome,grantId:r,generation:o,resolution:e.resolution,resolutionId:e.resolutionId,resolvedAt:s,now:s}),a=this.dependencies.store.getBinding(i.bindingId);return a&&n.kind==="revoke"?e.outcome==="confirmed"?(n.grantId&&n.generation&&(this.sessionFence.cancelGrant(a.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(a.bindingId,n.grantId,n.generation,s)),this.dependencies.store.updateBinding(a.bindingId,{status:"revoked"},s),await this.suspendDocumentBinding(a,"revoked")):this.dependencies.store.updateBinding(a.bindingId,{status:"checking"},s):a&&n.kind==="connect"&&e.outcome==="confirmed"&&r&&o&&this.dependencies.store.updateBinding(a.bindingId,{grantId:r,grantGeneration:o,scopeVersion:this.scopeRegistry.scopeVersion,status:"checking"},s),i}async snapshot(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e),o=Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T));return {binding:n,status:n.status,counts:o,results:r}}async performScan(e,n){let r=this.dependencies.store.getBinding(e);if(!r)throw new Error("APP_SYNC_BINDING_NOT_FOUND");let o=this.dependencies.store.getPendingControlRequest(e);if(o?.kind==="revoke")return await this.holdPendingRevoke(r),this.snapshot(e);if(!n.session.authenticated||!n.session.accountKey)return await this.suspendAccount(r.accountKey),this.snapshot(e);if(n.session.accountKey!==r.accountKey)return this.sessionFence.suspend(r.accountKey),await this.suspendBindingsForAccount(r.accountKey,"account_switch"),this.snapshot(e);if(!this.isEligible(n.eligibility))return await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e);let s=await this.activateSession(r.accountKey);if(!s)return this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);this.dependencies.store.updateBinding(e,{status:"checking"},this.now());let i;try{i=await this.dependencies.remote.readGrant({accountKey:r.accountKey,appId:T,signal:s.signal});}catch(u){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=ft(u);return sr(u)&&!Bt.has(p)&&!rr.has(p)?await this.pauseAuthentication(r):Bt.has(p)||sd(u)?await this.pauseUnavailableBinding(r,p==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):or.has(p)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):ir(u)?this.dependencies.store.updateBinding(e,{status:"offline"},this.now()):await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)}if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(i.appId!==T||i.available!==true)return await this.pauseUnavailableBinding(r,i.available===true?"scope_mismatch":"ineligible"),this.snapshot(e);if(i.status==="none")return r.grantId&&r.grantGeneration?(await this.invalidateStoredGeneration(r,"revoked"),r=this.dependencies.store.getBinding(e)??r,this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):this.dependencies.store.updateBinding(e,{status:"consent_required"},this.now()),this.snapshot(e);if(i.status==="revoked")return r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),this.snapshot(e);if(i.status!=="active")return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);let a=i.grant;if(!a||a.appId!==T||!a.grantId||!Number.isSafeInteger(a.generation)||a.generation<1||!this.scopeRegistry.matchesDefinition(a.scopeVersion,a.scope))return await this.pauseUnavailableBinding(r,"scope_mismatch"),this.snapshot(e);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(this.dependencies.store.getConfirmedRevoke(e,a.grantId,a.generation))return this.sessionFence.suspend(r.accountKey),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now()),await this.suspendDocumentBinding(r,"revoked"),this.snapshot(e);o?.kind==="connect"&&this.dependencies.store.updateControlRequest(o.requestId,{state:"confirmed",grantId:a.grantId,generation:a.generation,resolution:"remote",resolutionId:"doc023-active",resolvedAt:this.now(),now:this.now()}),(r.grantId!==a.grantId||r.grantGeneration!==a.generation)&&r.grantId&&r.grantGeneration&&(this.sessionFence.cancelGrant(r.accountKey,r.grantId,r.grantGeneration),this.dependencies.store.invalidateGrantJobs(e,r.grantId,r.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:"regranted"})),this.dependencies.store.updateBinding(e,{grantId:a.grantId,grantGeneration:a.generation,scopeVersion:a.scopeVersion,status:"checking"},this.now()),r=this.dependencies.store.getBinding(e)??r;try{let u=await this.listAllowedRefs(r,s);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let p=new Set(u.map(f=>f.ref));for(let f of this.dependencies.store.listResults(e))!p.has(f.ref)&&f.status!=="deleted"&&this.writeResult(r,a,f.ref,{sourceFingerprint:null,syncedFingerprint:f.syncedFingerprint,documentId:f.documentId,status:"excluded",errorCode:"APP_FILE_MISSING_OR_OUT_OF_SCOPE"});u.sort((f,_)=>f.ref.localeCompare(_.ref));for(let[f,_]of u.entries()){if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);let S=crypto.createHash("sha256").update(_.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,T,S)){let ke=this.dependencies.store.getResult(e,_.ref);this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:ke?.syncedFingerprint??null,documentId:ke?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let w=this.dependencies.store.getResult(e,_.ref);if(f>=500){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let E=await this.readEligibleFile(r,_.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(E.status==="unsafe"||E.status==="missing"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:E.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(E.status==="read_error"){this.writeResult(r,a,_.ref,{sourceFingerprint:null,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let R=this.scopeRegistry.validateFrontMatter(_.ref,E.markdown),I=U(E.markdown);if(!R.valid){this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(w?.status==="conflict"&&w.grantGeneration===a.generation)continue;if(w?.documentId&&w.grantGeneration===a.generation){if(w.status==="synced"&&w.syncedFingerprint===I)continue;let ke=w?.sourceFingerprint===I;this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w.syncedFingerprint,documentId:w.documentId,status:ke?w.status:"waiting",errorCode:ke?w.errorCode:null,nextAttemptAt:ke?w.nextAttemptAt:0});continue}if(w?.status==="failed"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I&&!pn.has(w.errorCode??"")||w?.status==="blocked"&&w.errorCode!=="APP_LOCAL_QUOTA"&&w.grantGeneration===a.generation&&w.sourceFingerprint===I)continue;let Ae=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:_.ref,fingerprint:I,now:this.now()}),O=w?.sourceFingerprint===I,Ie=w?.status==="failed"&&pn.has(w.errorCode??"");this.writeResult(r,a,_.ref,{sourceFingerprint:I,syncedFingerprint:w?.syncedFingerprint??null,documentId:w?.documentId??null,status:Ae.status==="completed"?"processing":"waiting",errorCode:O&&!Ie?w.errorCode:null,nextAttemptAt:O&&!Ie?w.nextAttemptAt:0});}return this.refreshBindingStatus(e),this.snapshot(e)}catch{return this.isCurrent(s)?(await this.pauseUnavailableBinding(r,"ineligible"),this.snapshot(e)):this.snapshot(e)}}async listAllowedRefs(e,n){let r=new Map,o=new Set,s=null;for(let i=0;i<Qa;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Yn,cursor:s,pageSize:100,signal:n.signal});if(this.hasPendingRevoke(e.bindingId))return [];if(!this.isCurrent(n))return [];for(let c of a.entries)c.isSymlink||!c.staysWithinRoot||this.scopeRegistry.validateRef(c.ref).valid&&r.set(c.ref,{ref:c.ref});if(a.nextCursor===null)return [...r.values()];if(o.has(a.nextCursor))throw new Error("APP_SYNC_PAGE_CURSOR_REPEATED");o.add(a.nextCursor),s=a.nextCursor;}throw new Error("APP_SYNC_PAGE_LIMIT_REACHED")}async readEligibleFile(e,n,r){if(!this.scopeRegistry.validateRef(n).valid)return {status:"unsafe"};try{let o=await this.dependencies.workspace.readFile({rootSegments:e.rootSegments,ref:n,signal:r});return o.isSymlink||!o.staysWithinRoot?{status:"unsafe"}:{status:"ok",markdown:o.markdown}}catch(o){let s=ft(o);return s==="ENOENT"||s==="APP_FILE_MISSING"?{status:"missing"}:{status:"read_error"}}}async beforeDocumentDispatch(e,n,r,o){if(!this.isCurrent(r))return {ok:false,reason:"session_stale"};if(!this.bindingHasGrant(e.bindingId,n))return {ok:false,reason:"grant_stale"};if(this.hasPendingRevoke(e.bindingId))return {ok:false,reason:"control_request_pending"};if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o)))return {ok:false,reason:"deleted"};let s=await this.readEligibleFile(e,o,r.signal);return this.isCurrent(r)?this.hasPendingRevoke(e.bindingId)?{ok:false,reason:"control_request_pending"}:this.bindingHasGrant(e.bindingId,n)?this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o))?{ok:false,reason:"deleted"}:s.status!=="ok"?{ok:false,reason:s.status}:this.scopeRegistry.validateFrontMatter(o,s.markdown).valid?{ok:true,markdown:s.markdown,fingerprint:U(s.markdown)}:{ok:false,reason:"out_of_scope"}:{ok:false,reason:"grant_stale"}:{ok:false,reason:"session_stale"}}async readRemoteDocument(e){return this.remoteReadSemaphore.run(e.signal,()=>this.dependencies.remote.readDocument(e))}async dispatchCreation(e,n,r,o,s){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(o.accountKey!==e.accountKey||o.bindingId!==e.bindingId||o.grantId!==n.grantId||o.grantGeneration!==n.generation||e.grantId!==n.grantId||e.grantGeneration!==n.generation){this.dependencies.store.updateCreation(o.jobId,{status:"invalidated",nextAttemptAt:0,now:this.now()});return}if(!this.isCurrent(r))return;if(o.operationKind==="reattach"){this.continuationRuntime?await this.continuationRuntime.dispatchReattachCreation(e,n,r,o,s):this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let i=this.dependencies.store.claimCreation(o.jobId,this.now(),Xa);if(!i)return;let a=this.sessionFence.captureGrant(r,n.grantId,n.generation),c=this.dependencies.store.getResult(e.bindingId,i.ref);try{if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref))){await this.markDeleted(e,n,i,c);return}let u=await this.readEligibleFile(e,i.ref,a.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(u.status!=="ok"){this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:u.status==="read_error"?"failed":"excluded",errorCode:u.status==="unsafe"?"APP_FILE_UNSAFE":u.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:u.status==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}if(!this.scopeRegistry.validateFrontMatter(i.ref,u.markdown).valid){this.writeResult(e,n,i.ref,{sourceFingerprint:U(u.markdown),syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(U(u.markdown)!==i.fingerprint){this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"processing",errorCode:null});let _=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let O=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new g("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(i.ref)))return {kind:"deleted"};if(O.status!=="ok")return {kind:"local_file",status:O.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,O.markdown).valid)return {kind:"out_of_scope"};let Ie=U(O.markdown);if(Ie!==i.fingerprint)return {kind:"source_changed",fingerprint:Ie};let ke=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),Co;try{Co=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:T,ref:i.ref,requestId:i.requestId,markdown:O.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...ke?{dispatchGate:ke}:{}});}catch(Wn){if(Wn instanceof je)return {kind:"budget_deferred",retryAt:Wn.retryAt};throw Wn}if(ke&&ke.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:Co}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(_.status==="deferred"){let O=this.now();if(!this.deferClaim(i,_.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.retryAt});return}if(_.value.kind==="budget_deferred"){let O=this.now();if(!this.deferClaim(i,_.value.retryAt,O))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:_.value.retryAt});return}if(_.value.kind!=="created"){let O=_.value;if(O.kind==="control_pending"){this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()}),this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now());return}if(O.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(O.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:O.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null}),this.dependencies.store.updateCreation(i.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}let Ie=O.kind==="local_file"?O.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:Ie==="read_error"?"failed":"excluded",errorCode:O.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":Ie==="unsafe"?"APP_FILE_UNSAFE":Ie==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:Ie==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let S=_.value.result;if(S.appGrantId!==n.grantId||S.appGrantGeneration!==n.generation)throw new g("DOC_APP_GRANT_STALE",409);let w=await this.readRemoteDocument({accountKey:i.accountKey,docId:S.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(w,S,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,S.docId,{status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH",dispatch:"none"}),this.dependencies.store.updateCreation(i.jobId,{status:"conflict",nextAttemptAt:0,now:this.now()});return}let E=U(w.markdown),R,I=i.fingerprint;if(!S.replayed&&!S.reattached&&E===i.fingerprint&&w.markdownVersion===i.fingerprint)R=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let O;if(R=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:w,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(O=await this.beforeDocumentDispatch(e,n,a,i.ref),O)}),!O&&R.dispatch!=="none")throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(R.dispatch==="attempted"&&!O)throw new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(O&&!O.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,O,i);return}O?.ok&&R.dispatch!=="none"&&(I=O.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Ae=this.recordOutcome(e,n,i.ref,I,c,S.docId,R);this.dependencies.store.updateCreation(i.jobId,{status:Ae==="conflict"?"conflict":Ae==="failed"?"failed":R.status==="failed"&&R.retryAt!==void 0?"waiting":"completed",nextAttemptAt:R.status==="failed"&&R.retryAt!==void 0?this.retryAt(i.attempts+1,R.retryAt):0,now:this.now()});}catch(u){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;await this.handleCreationError(e,n,i,c,u);}finally{this.sessionFence.release(a);}}async reconcileExisting(e,n,r,o){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!o.documentId||o.accountKey!==e.accountKey||o.grantId!==n.grantId||o.grantGeneration!==n.generation||o.status==="conflict"||o.status==="excluded"||o.status==="deleted"||!this.isCurrent(r))return;let s=await this.readEligibleFile(e,o.ref,r.signal);if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;if(s.status!=="ok"){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:s.status==="read_error"?"failed":"excluded",errorCode:s.status==="unsafe"?"APP_FILE_UNSAFE":s.status==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"});return}if(!this.scopeRegistry.validateFrontMatter(o.ref,s.markdown).valid){this.writeResult(e,n,o.ref,{sourceFingerprint:U(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=U(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,T,Ue(o.ref))){this.writeResult(e,n,o.ref,{sourceFingerprint:null,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});return}let u;try{u=await this.readRemoteDocument({accountKey:e.accountKey,docId:o.documentId,signal:r.signal});}catch(p){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||U(u.markdown)!==u.markdownVersion){this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"conflict",errorCode:"DOC_SYNC_REMOTE_STATE_MISMATCH"});return}this.writeResult(e,n,o.ref,{sourceFingerprint:a,syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"processing",errorCode:null});try{let p,f=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:o.ref,document:u,localMarkdown:s.markdown,sourceFingerprint:a,signal:r.signal,beforeDispatch:async()=>(p=await this.beforeDocumentDispatch(e,n,r,o.ref),p)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!p&&f.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(f.dispatch==="attempted"&&!p){await this.handleExistingError(e,n,o,a,new g("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(p&&!p.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,p);return}let _=p?.ok&&f.dispatch!=="none"?p.fingerprint:a;this.recordOutcome(e,n,o.ref,_,o,o.documentId,f);}catch(p){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,p);}}}async handleCreationError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){await this.markDeleted(e,n,r,o);return}if(i==="DOC_APP_REF_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"excluded",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"completed",nextAttemptAt:0,now:this.now()});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(i==="DOC_APP_BODY_OUT_OF_SCOPE"){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"failed",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"failed",nextAttemptAt:0,now:this.now()});return}if(rr.has(i)){this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"blocked",errorCode:i}),this.dependencies.store.updateCreation(r.jobId,{status:"blocked",nextAttemptAt:0,now:this.now()});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=this.retryAt(r.attempts,Ho(s,this.now())),c=ir(s);this.writeResult(e,n,r.ref,{sourceFingerprint:r.fingerprint,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:c?"waiting":"failed",errorCode:i||"APP_SYNC_CREATE_FAILED",nextAttemptAt:c?a:0}),this.dependencies.store.updateCreation(r.jobId,{status:c?"waiting":"failed",nextAttemptAt:c?a:0,now:this.now()}),c&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async handleExistingError(e,n,r,o,s){let i=ft(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(or.has(i)){this.sessionFence.cancelGrant(e.accountKey,n.grantId,n.generation),this.dependencies.store.invalidateGrantJobs(e.bindingId,n.grantId,n.generation,this.now()),this.dependencies.store.updateBinding(e.bindingId,{status:"revoked"},this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:n.grantId,generation:n.generation,reason:"revoked"});return}if(Bt.has(i)){await this.pauseUnavailableBinding(e,i==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:i,nextAttemptAt:this.now()});return}if(rr.has(i)){i==="DOC_PILOT_NOT_ALLOWED"&&await this.pauseUnavailableBinding(e,"ineligible"),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"blocked",errorCode:i});return}if(sr(s)){await this.pauseAuthentication(e),this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"waiting",errorCode:"AUTH_REQUIRED",nextAttemptAt:this.now()});return}let a=ir(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,Ho(s,this.now())):0;this.writeResult(e,n,r.ref,{sourceFingerprint:o,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:a?"waiting":"failed",errorCode:i||"APP_SYNC_RECONCILE_FAILED",nextAttemptAt:u,attempts:a?c:0}),a&&this.dependencies.store.updateBinding(e.bindingId,{status:"offline"},this.now());}async markDeleted(e,n,r,o){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),this.dependencies.store.updateCreation(r.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});}recordOutcome(e,n,r,o,s,i,a){let c=a.status==="synced"&&a.syncedFingerprint===o?o:s?.syncedFingerprint??null,u=a.status==="synced"&&c!==o?"conflict":(a.status==="failed"||a.status==="waiting")&&a.retryAt!==void 0?"waiting":a.status,p=u==="waiting"&&a.retryAt!==void 0?s?.sourceFingerprint===o?s.attempts+1:1:u==="synced"||u==="conflict"?0:s?.sourceFingerprint===o?s.attempts:0;return this.writeResult(e,n,r,{sourceFingerprint:o,syncedFingerprint:c,documentId:i,status:u,errorCode:u==="conflict"&&a.status==="synced"?"DOC_SYNC_ACK_MISMATCH":a.errorCode??null,nextAttemptAt:u==="waiting"&&a.retryAt!==void 0?this.retryAt(p,a.retryAt):0,attempts:p}),u}recordBeforeDispatchFailure(e,n,r,o,s,i){if(s.reason==="session_stale"||s.reason==="grant_stale")return;if(s.reason==="deleted"){this.dependencies.store.suppressDeletedRef(e.accountKey,T,Ue(r),this.now()),this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"}),i&&this.dependencies.store.updateCreation(i.jobId,{status:"deleted",nextAttemptAt:0,now:this.now()});return}if(s.reason==="control_request_pending"){this.writeResult(e,n,r,{sourceFingerprint:o?.sourceFingerprint??null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:"waiting",errorCode:"APP_SYNC_REVOKE_PENDING",nextAttemptAt:this.now()}),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),i&&this.dependencies.store.updateCreation(i.jobId,{status:"waiting",nextAttemptAt:this.now(),now:this.now()});return}let a=s.reason==="read_error"?"failed":"excluded",c=s.reason==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":s.reason==="unsafe"?"APP_FILE_UNSAFE":s.reason==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED";this.writeResult(e,n,r,{sourceFingerprint:null,syncedFingerprint:o?.syncedFingerprint??null,documentId:o?.documentId??null,status:a,errorCode:c,nextAttemptAt:0}),i&&this.dependencies.store.updateCreation(i.jobId,{status:s.reason==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});}writeResult(e,n,r,o){let s=this.dependencies.store.getResult(e.bindingId,r),i=o.attempts??(s?.sourceFingerprint===o.sourceFingerprint?s.attempts:0);this.dependencies.store.upsertResult({bindingId:e.bindingId,accountKey:e.accountKey,ref:r,grantId:n.grantId,grantGeneration:n.generation,...o,nextAttemptAt:o.nextAttemptAt??0,attempts:i,updatedAt:this.now()});}validateControlIdentity(e){let n=this.requireAuthenticatedAccount(e.session),r=this.dependencies.store.getBinding(e.bindingId);if(!r||r.accountKey!==n)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");let o=_t(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!rd(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:Ue(JSON.stringify(o))}}hasPendingRevoke(e){let n=this.dependencies.store.getPendingControlRequest(e);return n?.kind==="revoke"&&(n.state==="pending"||n.state==="unknown")}async holdPendingRevoke(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_REVOKE_PENDING")),this.dependencies.store.updateBinding(e.bindingId,{status:"stopping"},this.now()),await this.suspendDocumentBinding(e,"revoke_pending");}async invalidateStoredGeneration(e,n){!e.grantId||!e.grantGeneration||(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.invalidateGrantJobs(e.bindingId,e.grantId,e.grantGeneration,this.now()),await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n}));}async pauseUnavailableBinding(e,n){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"APP_SYNC_UNAVAILABLE")),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,n);}async pauseAuthentication(e){this.scanEpoch+=1,this.sessionFence.suspend(e.accountKey),e.grantId&&e.grantGeneration&&(this.sessionFence.cancelGrant(e.accountKey,e.grantId,e.grantGeneration),this.dependencies.store.releaseProcessingCreations(e.bindingId,e.grantId,e.grantGeneration,this.now()),this.returnProcessingResultsToWaiting(e,e.grantId,e.grantGeneration,"AUTH_REQUIRED",true)),this.dependencies.store.updateBinding(e.bindingId,{status:"unavailable"},this.now()),await this.suspendDocumentBinding(e,"auth_required");}returnProcessingResultsToWaiting(e,n,r,o,s=false){for(let i of this.dependencies.store.listResults(e.bindingId)){let a=i.status==="processing",c=s&&i.status==="failed"&&pn.has(i.errorCode??"");i.grantId!==n||i.grantGeneration!==r||!a&&!c||this.dependencies.store.upsertResult({...i,status:"waiting",errorCode:o,nextAttemptAt:this.now(),updatedAt:this.now()});}}async suspendDocumentBinding(e,n){try{await this.dependencies.documents.suspendBinding({binding:e,grantId:e.grantId,generation:e.grantGeneration,reason:n});}catch(r){this.reportAdapterError(r);}}reportAdapterError(e){try{this.dependencies.onAdapterError?.(e);}catch{}}async activateSession(e){let n=this.sessionFence.activeAccountKey,r=this.sessionFence.activate(e);return n&&n!==e&&await this.suspendBindingsForAccount(n,"account_switch"),r}async suspendBindingsForAccount(e,n){for(let r of this.dependencies.store.listBindingsForAccount(e)){this.dependencies.store.updateBinding(r.bindingId,{status:"stopping"},this.now());try{await this.dependencies.documents.suspendBinding({binding:r,grantId:r.grantId,generation:r.grantGeneration,reason:n});}catch(o){this.reportAdapterError(o);}finally{try{this.dependencies.store.updateBinding(r.bindingId,{status:this.hasPendingRevoke(r.bindingId)?"stopping":"local_only"},this.now());}catch(o){this.reportAdapterError(o);}}}}shouldReconcile(e,n){return e.documentId!==null&&e.grantId===n.grantId&&e.grantGeneration===n.generation&&(e.status==="processing"||e.status==="waiting"&&e.nextAttemptAt<=this.now())}validRemoteDocument(e,n,r){return e.docId===n.docId&&e.appGrantId===r.grantId&&e.appGrantGeneration===r.generation&&n.appGrantId===r.grantId&&n.appGrantGeneration===r.generation&&n.markdownVersion===e.markdownVersion&&U(e.markdown)===e.markdownVersion}grantFromBinding(e){if(!e.grantId||!e.grantGeneration||e.scopeVersion!==this.scopeRegistry.scopeVersion)throw new Error("APP_SYNC_BINDING_GRANT_INVALID");return {grantId:e.grantId,appId:T,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:_e}}bindingHasGrant(e,n){let r=this.dependencies.store.getBinding(e);return r?.grantId===n.grantId&&r.grantGeneration===n.generation}isTransferStatus(e){return e==="checking"||e==="syncing"||e==="synced"||e==="partial"}isEligible(e){return e?.featureEnabled===true&&e?.ownerAllowlisted===true}requireAuthenticatedAccount(e){if(!e||e.authenticated!==true||typeof e.accountKey!="string"||!/^[0-9a-f]{64}$/.test(e.accountKey))throw new Error("APP_SYNC_SESSION_REQUIRED");return e.accountKey}isCurrent(e){return this.sessionFence.isCurrent(e)}refreshBindingStatus(e){let n=this.snapshotNow(e);if(!n.binding||["offline","unavailable","revoked","stopping","local_only","consent_required"].includes(n.binding.status))return;let r=n.counts,o=r.P+r.I>0?"syncing":r.F+r.C+r.B>0?"partial":"synced";this.dependencies.store.updateBinding(e,{status:o},this.now());}snapshotNow(e){let n=this.dependencies.store.getBinding(e)??null;if(!n)return {binding:null,status:"local_only",counts:dr(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Bo(r,this.dependencies.store.countDeletedRefs(n.accountKey,T)),results:r}}listConflicts(e){return this.continuationRuntime?this.continuationRuntime.listConflicts(e):[]}readConflictArchive(e){return this.continuationRuntime?this.continuationRuntime.readConflictArchive(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}resolveConflict(e){return this.continuationRuntime?this.continuationRuntime.resolveConflict(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}purgeAccountData(e){return this.continuationRuntime?this.continuationRuntime.purgeAccountData(e):Promise.reject(new Error("APP_SYNC_CONTINUATION_DISABLED"))}retryAt(e,n){if(n!==void 0&&Number.isFinite(n))return Math.max(this.now(),n);let r=Math.min(Math.max(e-1,0),10);return this.now()+Math.min(Za*2**r,ed)}};function dr(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Bo(t,e){let n=dr(),r=n;for(let o of t)switch(o.status){case "synced":r.S+=1;break;case "waiting":r.P+=1;break;case "processing":r.I+=1;break;case "failed":r.F+=1;break;case "conflict":r.C+=1;break;case "blocked":r.B+=1;break;}return r.N=r.S+r.P+r.I+r.F+r.C+r.B,r.D=e,n}function rd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function od(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===T}function Ue(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function ft(t){return t instanceof g||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function Ho(t,e){if(t instanceof g&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function ur(t){return t instanceof g||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function sr(t){let e=ft(t);if(Bt.has(e))return false;let n=ur(t);return pn.has(e)||n===401||n===403}function sd(t){let e=ur(t);return e!==void 0&&e>=400&&e<500}function ir(t){let e=ur(t);return e!==void 0?e===408||e===425||e===429||e>=500:nd.has(ft(t))}var cr=class{constructor(e){this.limit=e;if(!Number.isSafeInteger(e)||e<1)throw new Error("INVALID_SEMAPHORE_LIMIT")}limit;active=0;waiters=[];async run(e,n){await this.acquire(e);try{return await n()}finally{this.release();}}acquire(e){return e.aborted?Promise.reject(this.abortError()):this.active<this.limit?(this.active+=1,Promise.resolve()):new Promise((n,r)=>{let o={signal:e,resolve:()=>{e.removeEventListener("abort",o.onAbort),n();},reject:s=>{e.removeEventListener("abort",o.onAbort),r(s);},onAbort:()=>{let s=this.waiters.indexOf(o);s>=0&&this.waiters.splice(s,1),o.reject(this.abortError());}};this.waiters.push(o),e.addEventListener("abort",o.onAbort,{once:true}),e.aborted&&o.onAbort();})}release(){for(;this.waiters.length>0;){let e=this.waiters.shift();if(e.signal.aborted){e.reject(this.abortError());continue}e.resolve();return}this.active=Math.max(0,this.active-1);}abortError(){return Object.assign(new Error("APP_SYNC_SESSION_STALE"),{code:"APP_SYNC_SESSION_STALE"})}};d();P();d();P();L();d();P();M();q();L();F();br();d();P();M();q();L();F();d();Fr();d();P();M();q();L();d();F();var Ur=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(Ur);M();q();d();q();F();F();F();F();Pt();Pt();So();an();lt();Pt();Pt();Tt();d();P();d();var wa=["success","failed","completed"];new Set(wa);vn();Pt();yo();xn();var pp=[{key:"usageBackfill",field:"metadata.usageBackfill",before:"before_usage_backfill",after:"after_usage_backfill"},{key:"usageAccounting",field:"metadata.usageAccounting",before:"before_usage_accounting",after:"after_usage_accounting"},{key:"usageAccountingReason",field:"metadata.usageAccountingReason",before:"before_usage_accounting_reason",after:"after_usage_accounting_reason"},{key:"usageByEpoch",field:"metadata.usageByEpoch",before:"before_usage_by_epoch",after:"after_usage_by_epoch"},{key:"usageIncomplete",field:"metadata.usageIncomplete",before:"before_usage_incomplete",after:"after_usage_incomplete"}];["run_epoch","completed_at","input_tokens","output_tokens","cached_input_tokens","cost_usd","model",...pp.map(t=>t.field)];vn();d();P();M();q();L();F();Tt();lt();d();d();Qt();d();P();M();q();L();F();d();P();M();q();L();F();d();var Ra=["urgent","high","medium","low"],Ea=["investigating","in-progress","in-review","on-hold","done"];new Set(Ra);new Set(Ea);lt();new Set(Fs);new Set(Ms);new Set(Us);new Set(qs);new Set(Bs);d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();M();P();L();q();lt();F();d();P();d();P();M();L();L();d();P();M();L();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();L();F();d();P();M();q();lt();Tt();Br();Et.map(t=>`'${t}'`).join(", ");var Io=class extends D{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=x(n),this.sqlite=this.handle.sqlite,B(this.handle.db,n);}close(){this.handle.close();}bind(e){if(this.assertAccountKey(e.accountKey),this.assertText(e.bindingId,"bindingId",128),this.assertText(e.workspaceId,"workspaceId",256),e.appId!==T)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=_t(e.rootSegments);if(!n)throw new Error("APP_SYNC_ROOT_INVALID");let r=this.getBindingForAccountApp(e.accountKey,e.appId);if(r){if(r.workspaceId!==e.workspaceId||!Oa(r.rootSegments,n))throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");return r}try{this.sqlite.prepare(`
|
|
76
76
|
INSERT INTO app_sync_bindings (
|
|
77
77
|
binding_id, account_key, workspace_id, app_id, root_segments,
|
|
78
78
|
grant_id, grant_generation, scope_version, status, created_at, updated_at
|
|
79
79
|
) VALUES (?, ?, ?, ?, ?, NULL, NULL, NULL, 'local_only', ?, ?)
|
|
80
|
-
`).run(e.bindingId,e.accountKey,e.workspaceId,e.appId,JSON.stringify(n),e.now,e.now);}catch(s){let i=this.getBindingForAccountApp(e.accountKey,e.appId);if(i){if(i.workspaceId===e.workspaceId&&Oa(i.rootSegments,n))return i;throw new Error("APP_SYNC_ROOT_ALREADY_BOUND")}throw
|
|
80
|
+
`).run(e.bindingId,e.accountKey,e.workspaceId,e.appId,JSON.stringify(n),e.now,e.now);}catch(s){let i=this.getBindingForAccountApp(e.accountKey,e.appId);if(i){if(i.workspaceId===e.workspaceId&&Oa(i.rootSegments,n))return i;throw new Error("APP_SYNC_ROOT_ALREADY_BOUND")}throw Op(s)?new Error("APP_SYNC_BINDING_ID_CONFLICT"):s}let o=this.getBinding(e.bindingId);if(!o)throw new Error("APP_SYNC_BINDING_WRITE_FAILED");return o}getBinding(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE binding_id = ?").get(e);return n?Ro(n):void 0}getBindingForAccountApp(e,n){let r=this.sqlite.prepare("SELECT * FROM app_sync_bindings WHERE account_key = ? AND app_id = ?").get(e,n);return r?Ro(r):void 0}beginControlRequest(e){let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.appId!==e.appId||n.workspaceId!==e.workspaceId||ye(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_CONTROL_REQUEST_BINDING_MISMATCH");if(this.assertAccountKey(e.accountKey),this.assertText(e.requestId,"requestId",128),this.assertText(e.workspaceId,"workspaceId",256),e.state!=="pending"||e.resolvedAt!==null||e.resolution!==null||e.resolutionId!==null)throw new Error("APP_SYNC_CONTROL_REQUEST_INITIAL_STATE_INVALID");if(!/^[0-9a-f]{64}$/.test(e.rootFingerprint))throw new Error("APP_SYNC_ROOT_FINGERPRINT_INVALID");if(e.kind==="revoke"&&(e.grantId!==n.grantId||e.generation!==n.grantGeneration||!e.grantId||!e.generation))throw new Error("APP_SYNC_CONTROL_REQUEST_GRANT_MISMATCH");let r=this.getControlRequest(e.requestId);if(r){if(!Na(r,e))throw new Error("APP_SYNC_CONTROL_REQUEST_ID_REUSED");return r}try{this.sqlite.prepare(`
|
|
81
81
|
INSERT INTO app_sync_control_requests (
|
|
82
82
|
request_id, binding_id, account_key, app_id, workspace_id, root_fingerprint,
|
|
83
83
|
kind, state, grant_id, generation, created_at, updated_at, resolved_at, resolution, resolution_id
|
|
@@ -247,7 +247,7 @@ ${r.join(`
|
|
|
247
247
|
`).get(e,n,r,o);return s?To(s):void 0}updatePendingDiscovery(e){this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.sqlite.prepare(`
|
|
248
248
|
SELECT * FROM app_sync_pending_discoveries
|
|
249
249
|
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ?
|
|
250
|
-
`).get(e.bindingId,e.grantId,e.generation,e.ref);if(!r)return;let o={...To(r),...e.patch};
|
|
250
|
+
`).get(e.bindingId,e.grantId,e.generation,e.ref);if(!r)return;let o={...To(r),...e.patch};Ap(o),this.sqlite.prepare(`
|
|
251
251
|
UPDATE app_sync_pending_discoveries
|
|
252
252
|
SET doc_id = ?, listed_revision = ?, listed_fingerprint = ?, app_grant_generation = ?,
|
|
253
253
|
needs_reattach = ?, needs_reconcile = ?, status = ?, error_code = ?, attempts = ?, updated_at = ?
|
|
@@ -298,7 +298,7 @@ ${r.join(`
|
|
|
298
298
|
WHERE binding_id = ? AND grant_id = ? AND grant_generation = ? AND ref = ? AND fingerprint = ?
|
|
299
299
|
AND operation_kind = 'reattach' AND document_id = ?
|
|
300
300
|
ORDER BY created_at DESC, job_id DESC LIMIT 1
|
|
301
|
-
`).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId)),!r)throw new Error("APP_SYNC_REATTACH_JOB_WRITE_FAILED");return this.assertContinuationFence(e.fence),jn(r)})()}putConflict(e){return
|
|
301
|
+
`).get(e.binding.bindingId,e.grant.grantId,e.grant.generation,e.ref,e.fingerprint,e.documentId)),!r)throw new Error("APP_SYNC_REATTACH_JOB_WRITE_FAILED");return this.assertContinuationFence(e.fence),jn(r)})()}putConflict(e){return Ip(e.conflict),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),Cp(e.conflict,e.fence);let r=this.getConflict(e.conflict.conflictId);if(r&&!Np(r,e.conflict))throw new Error("APP_SYNC_CONFLICT_IDENTITY_MISMATCH");if(r?.state==="resolved"||r?.state==="kept_both")return r;let o=r?.preservationStatus==="ready"?"ready":e.conflict.preservationStatus,s=r?.vaultHandle??e.conflict.vaultHandle,i={...e.conflict,preservationStatus:o,vaultHandle:s};this.sqlite.prepare(`
|
|
302
302
|
INSERT INTO app_sync_conflicts (
|
|
303
303
|
conflict_id, binding_id, account_key, workspace_id, root_fingerprint, grant_id, grant_generation,
|
|
304
304
|
scope_version, ref, doc_id, local_version, local_fingerprint, baseline_revision, baseline_fingerprint,
|
|
@@ -325,7 +325,7 @@ ${r.join(`
|
|
|
325
325
|
AND preservation_status = 'ready' AND vault_handle IS NOT NULL
|
|
326
326
|
`).run(e.supersededBy,e.now,e.bindingId,e.ref,e.supersededBy),this.assertContinuationFence(e.fence);})();}getConflict(e){let n=this.sqlite.prepare("SELECT * FROM app_sync_conflicts WHERE conflict_id = ?").get(e);return n?ba(n):void 0}listConflicts(e){return this.sqlite.prepare(`
|
|
327
327
|
SELECT * FROM app_sync_conflicts WHERE binding_id = ? ORDER BY created_at, conflict_id
|
|
328
|
-
`).all(e).map(ba)}beginConflictResolution(e){
|
|
328
|
+
`).all(e).map(ba)}beginConflictResolution(e){bp(e),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence);let r=this.getConflict(e.conflictId);if(!r||r.bindingId!==e.fence.bindingId||r.accountKey!==e.fence.accountKey)throw new Error("APP_SYNC_CONFLICT_NOT_FOUND");if(r.preservationStatus!=="ready"||!r.vaultHandle)throw new Error("APP_SYNC_CONFLICT_NOT_PRESERVED");if(r.localVersion!==e.expectedLocalVersion||r.remoteRevision!==e.expectedRemoteRevision||r.remoteFingerprint!==e.expectedRemoteFingerprint)throw new Error("APP_SYNC_CONFLICT_STALE");if(r.state==="superseded"&&e.choice!=="keep_both")throw new Error("APP_SYNC_CONFLICT_SUPERSEDED");let o=this.sqlite.prepare("SELECT * FROM app_sync_conflict_resolutions WHERE request_id = ?").get(e.requestId);if(o){if(!(o.conflict_id===e.conflictId&&o.account_key===e.fence.accountKey&&o.human_identity===e.humanIdentity&&o.choice===e.choice&&o.expected_local_version===e.expectedLocalVersion&&o.expected_remote_revision===e.expectedRemoteRevision&&o.expected_remote_fingerprint===e.expectedRemoteFingerprint))throw new Error("APP_SYNC_REQUEST_ID_REUSED");if(o.state==="stale"||o.state==="failed")throw new Error("APP_SYNC_CONFLICT_RESOLUTION_ALREADY_ENDED");if(r.state==="resolved"||r.state==="kept_both"||r.state==="resolving"&&r.resolutionRequestId===e.requestId)return;throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS")}if(r.state!=="open"&&!(r.state==="superseded"&&e.choice==="keep_both"))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_IN_PROGRESS");this.sqlite.prepare(`
|
|
329
329
|
INSERT INTO app_sync_conflict_resolutions (
|
|
330
330
|
request_id, conflict_id, account_key, human_identity, choice, expected_local_version,
|
|
331
331
|
expected_remote_revision, expected_remote_fingerprint, state, error_code, created_at, updated_at
|
|
@@ -387,4 +387,4 @@ ${r.join(`
|
|
|
387
387
|
`).get(n.bindingId))throw new Error("APP_SYNC_ACCOUNT_DATA_PURGE_PENDING");e.assertCurrent();}assertPurgeFence(e){e.assertCurrent();let n=this.getBinding(e.bindingId);if(!n||n.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||ye(JSON.stringify(n.rootSegments))!==e.rootFingerprint)throw new Error("APP_SYNC_ROOT_STALE");if(n.grantId&&(n.grantId!==e.grantId||n.grantGeneration!==e.grantGeneration))throw new Error("DOC_APP_GRANT_STALE");if(n.status==="stopping")throw new Error("APP_SYNC_REVOKE_PENDING");if(this.sqlite.prepare(`
|
|
388
388
|
SELECT 1 AS found FROM app_sync_control_requests
|
|
389
389
|
WHERE binding_id = ? AND kind = 'revoke' AND state IN ('pending', 'unknown') LIMIT 1
|
|
390
|
-
`).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");e.assertCurrent();}assertAccountKey(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("APP_SYNC_ACCOUNT_KEY_INVALID")}assertText(e,n,r){if(typeof e!="string"||e.length===0||e.length>r||e.includes("\0"))throw new Error(`APP_SYNC_${n.toUpperCase()}_INVALID`)}};function Ro(t){let e;try{e=JSON.parse(t.root_segments);}catch{throw new Error("APP_SYNC_ROOT_STORAGE_INVALID")}if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error("APP_SYNC_ROOT_STORAGE_INVALID");return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,appId:T,rootSegments:e,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function jn(t){return {jobId:t.job_id,bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,requestId:t.request_id,fingerprint:t.fingerprint,operationKind:t.operation_kind==="reattach"?"reattach":"create",documentId:t.document_id,status:t.status,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,createdAt:t.created_at,updatedAt:t.updated_at}}function Eo(t){return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,lastCycleStartedAt:t.last_cycle_started_at,cycleStartedAt:t.cycle_started_at,docsCursor:t.docs_cursor,docsComplete:t.docs_complete===1,deletedCursor:t.deleted_cursor,deletedComplete:t.deleted_complete===1,updatedAt:t.updated_at}}function To(t){return {bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,docId:t.doc_id,listedRevision:t.listed_revision,listedFingerprint:t.listed_fingerprint,appGrantGeneration:t.app_grant_generation,needsReattach:t.needs_reattach===1,needsReconcile:t.needs_reconcile===1,status:t.status,errorCode:t.error_code,attempts:t.attempts,updatedAt:t.updated_at}}function ba(t){return {conflictId:t.conflict_id,bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,ref:t.ref,documentId:t.doc_id,localVersion:t.local_version,localFingerprint:t.local_fingerprint,baselineRevision:t.baseline_revision,baselineFingerprint:t.baseline_fingerprint,remoteRevision:t.remote_revision,remoteFingerprint:t.remote_fingerprint,needsReattach:t.needs_reattach===1,vaultHandle:t.vault_handle,preservationStatus:t.preservation_status,state:t.state,supersededBy:t.superseded_by,resolutionRequestId:t.resolution_request_id,resolutionChoice:t.resolution_choice,cleanupPending:t.cleanup_pending===1,createdAt:t.created_at,updatedAt:t.updated_at}}function
|
|
390
|
+
`).get(n.bindingId))throw new Error("APP_SYNC_REVOKE_PENDING");e.assertCurrent();}assertAccountKey(e){if(!/^[0-9a-f]{64}$/.test(e))throw new Error("APP_SYNC_ACCOUNT_KEY_INVALID")}assertText(e,n,r){if(typeof e!="string"||e.length===0||e.length>r||e.includes("\0"))throw new Error(`APP_SYNC_${n.toUpperCase()}_INVALID`)}};function Ro(t){let e;try{e=JSON.parse(t.root_segments);}catch{throw new Error("APP_SYNC_ROOT_STORAGE_INVALID")}if(!Array.isArray(e)||e.some(n=>typeof n!="string"))throw new Error("APP_SYNC_ROOT_STORAGE_INVALID");return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,appId:T,rootSegments:e,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function jn(t){return {jobId:t.job_id,bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,requestId:t.request_id,fingerprint:t.fingerprint,operationKind:t.operation_kind==="reattach"?"reattach":"create",documentId:t.document_id,status:t.status,attempts:t.attempts,nextAttemptAt:t.next_attempt_at,createdAt:t.created_at,updatedAt:t.updated_at}}function Eo(t){return {bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,lastCycleStartedAt:t.last_cycle_started_at,cycleStartedAt:t.cycle_started_at,docsCursor:t.docs_cursor,docsComplete:t.docs_complete===1,deletedCursor:t.deleted_cursor,deletedComplete:t.deleted_complete===1,updatedAt:t.updated_at}}function To(t){return {bindingId:t.binding_id,accountKey:t.account_key,grantId:t.grant_id,grantGeneration:t.grant_generation,ref:t.ref,docId:t.doc_id,listedRevision:t.listed_revision,listedFingerprint:t.listed_fingerprint,appGrantGeneration:t.app_grant_generation,needsReattach:t.needs_reattach===1,needsReconcile:t.needs_reconcile===1,status:t.status,errorCode:t.error_code,attempts:t.attempts,updatedAt:t.updated_at}}function ba(t){return {conflictId:t.conflict_id,bindingId:t.binding_id,accountKey:t.account_key,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,grantId:t.grant_id,grantGeneration:t.grant_generation,scopeVersion:t.scope_version,ref:t.ref,documentId:t.doc_id,localVersion:t.local_version,localFingerprint:t.local_fingerprint,baselineRevision:t.baseline_revision,baselineFingerprint:t.baseline_fingerprint,remoteRevision:t.remote_revision,remoteFingerprint:t.remote_fingerprint,needsReattach:t.needs_reattach===1,vaultHandle:t.vault_handle,preservationStatus:t.preservation_status,state:t.state,supersededBy:t.superseded_by,resolutionRequestId:t.resolution_request_id,resolutionChoice:t.resolution_choice,cleanupPending:t.cleanup_pending===1,createdAt:t.created_at,updatedAt:t.updated_at}}function Ap(t){if(!/^[0-9a-f]{64}$/.test(t.accountKey)||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.docId!="string"||t.docId.length<1||t.docId.length>128||!Number.isSafeInteger(t.listedRevision)||t.listedRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.listedFingerprint)||!Number.isSafeInteger(t.grantGeneration)||t.grantGeneration<1||!Number.isSafeInteger(t.appGrantGeneration)||t.appGrantGeneration<1||!Number.isSafeInteger(t.attempts)||t.attempts<0||!["waiting","processing","failed","invalidated"].includes(t.status))throw new Error("APP_SYNC_PENDING_DISCOVERY_INVALID");if(t.errorCode!==null&&!/^[A-Z0-9_:-]{1,128}$/.test(t.errorCode))throw new Error("APP_SYNC_PENDING_DISCOVERY_METADATA_INVALID")}function Ip(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t.conflictId)||!/^[0-9a-f]{64}$/.test(t.accountKey)||!/^[0-9a-f]{64}$/.test(t.rootFingerprint)||typeof t.workspaceId!="string"||t.workspaceId.length<1||t.workspaceId.length>256||typeof t.ref!="string"||t.ref.length<1||t.ref.length>256||typeof t.documentId!="string"||t.documentId.length<1||t.documentId.length>128||!bo(t.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(t.localFingerprint)||!Number.isSafeInteger(t.remoteRevision)||t.remoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.remoteFingerprint)||!["pending","ready","failed"].includes(t.preservationStatus)||!["open","resolving","superseded","resolved","kept_both","purging"].includes(t.state)||t.supersededBy!==null&&!/^[A-Za-z0-9_-]{1,128}$/.test(t.supersededBy)||t.state==="superseded"&&t.supersededBy===null||!Number.isSafeInteger(t.createdAt)||!Number.isSafeInteger(t.updatedAt)||t.updatedAt<t.createdAt)throw new Error("APP_SYNC_CONFLICT_METADATA_INVALID");if(t.baselineRevision===null!=(t.baselineFingerprint===null))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.baselineRevision!==null&&(!Number.isSafeInteger(t.baselineRevision)||t.baselineRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.baselineFingerprint??"")))throw new Error("APP_SYNC_CONFLICT_BASELINE_INVALID");if(t.vaultHandle!==null&&!bo(t.vaultHandle))throw new Error("APP_SYNC_CONFLICT_HANDLE_INVALID");if(!(t.state==="open"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending||t.preservationStatus!=="ready"&&t.vaultHandle===null&&!t.cleanupPending:t.state==="resolving"||t.state==="superseded"?t.preservationStatus==="ready"&&t.vaultHandle!==null&&!t.cleanupPending:t.state==="purging"?!t.cleanupPending:t.state==="kept_both"?t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&t.resolutionChoice==="keep_both"&&t.vaultHandle!==null&&!t.cleanupPending:t.preservationStatus==="ready"&&t.resolutionRequestId!==null&&(t.cleanupPending?t.vaultHandle!==null:t.vaultHandle===null)))throw new Error("APP_SYNC_CONFLICT_PRESERVATION_INVALID");if(t.resolutionRequestId===null!=(t.resolutionChoice===null))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INVALID")}function bp(t){if(typeof t.requestId!="string"||t.requestId.length<1||t.requestId.length>128||t.requestId.includes("\0")||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!bo(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new Error("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID")}function Cp(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==e.rootFingerprint||t.grantId!==e.grantId||t.grantGeneration!==e.grantGeneration||t.scopeVersion!==e.scopeVersion)throw new Error("APP_SYNC_CONFLICT_BINDING_MISMATCH")}function Np(t,e){return t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.grantId===e.grantId&&t.grantGeneration===e.grantGeneration&&t.ref===e.ref&&t.documentId===e.documentId&&t.localVersion===e.localVersion&&t.localFingerprint===e.localFingerprint&&t.remoteRevision===e.remoteRevision&&t.remoteFingerprint===e.remoteFingerprint}function bo(t){return typeof t=="string"&&t.length>=1&&t.length<=256&&!t.includes("/")&&!t.includes("\\")&&!t.includes("\0")&&!t.startsWith("~")&&!/^[A-Za-z]:/.test(t)}function Ca(t){return {bindingId:t.binding_id,accountKey:t.account_key,ref:t.ref,grantId:t.grant_id,grantGeneration:t.grant_generation,sourceFingerprint:t.source_fingerprint,syncedFingerprint:t.synced_fingerprint,documentId:t.document_id,status:t.status,errorCode:t.error_code,nextAttemptAt:t.next_attempt_at,attempts:t.attempts,updatedAt:t.updated_at}}function Ao(t){return {requestId:t.request_id,bindingId:t.binding_id,accountKey:t.account_key,appId:T,workspaceId:t.workspace_id,rootFingerprint:t.root_fingerprint,kind:t.kind,state:t.state,grantId:t.grant_id,generation:t.generation,createdAt:t.created_at,updatedAt:t.updated_at,resolvedAt:t.resolved_at,resolution:t.resolution,resolutionId:t.resolution_id}}function Na(t,e){return t.requestId===e.requestId&&t.bindingId===e.bindingId&&t.accountKey===e.accountKey&&t.appId===e.appId&&t.workspaceId===e.workspaceId&&t.rootFingerprint===e.rootFingerprint&&t.kind===e.kind&&(t.kind==="connect"||t.grantId===e.grantId&&t.generation===e.generation)}function ye(t){return crypto.createHash("sha256").update(t,"utf8").digest("hex")}function Oa(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function Op(t){return t instanceof Error&&t.code==="SQLITE_CONSTRAINT_UNIQUE"}exports.APP_SYNC_APP_ID=T;exports.APP_SYNC_CONTINUATION_MAX_PAGE_SIZE=zn;exports.APP_SYNC_CONTINUATION_MIN_INTERVAL_MS=Lt;exports.APP_SYNC_FRONT_MATTER_MAX_BYTES=Vn;exports.APP_SYNC_LOCAL_RECORD_LIMIT=pt;exports.APP_SYNC_PAGE_SIZE=Kn;exports.APP_SYNC_SCOPE_DEFINITION=_e;exports.APP_SYNC_SCOPE_SELECTORS=Yn;exports.APP_SYNC_SCOPE_VERSION=Xe;exports.AppSyncBudgetDeferredError=je;exports.AppSyncCoordinator=ar;exports.AppSyncRemoteError=g;exports.AppSyncScopeRegistry=Ut;exports.AppSyncSessionFence=Ft;exports.DOC001_CREATE_LIMIT_PER_WINDOW=Mt;exports.DOC001_CREATE_WINDOW_MS=dn;exports.SqliteAppSyncStore=Io;exports.SqliteDocCreateLedger=Jn;exports.createDispatchGate=qt;exports.fingerprintMarkdown=U;exports.normalizeResolvedRootSegments=_t;
|