@crewx/sdk 0.9.0-rc.227 → 0.9.0-rc.228
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 +18 -18
- 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 +18 -18
- package/dist/esm/index.js +260 -260
- 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 +4 -4
- package/dist/index.js +256 -256
- package/dist/plugins/index.js +44 -44
- 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/types/index.d.ts +40 -0
- package/package.json +1 -1
|
@@ -19,7 +19,7 @@ import re,{join,resolve,dirname}from'path';import {fileURLToPath}from'url';impor
|
|
|
19
19
|
)
|
|
20
20
|
${u}`);return {hash:a,markedPointers:_?.count??0}}function hn(t){let{migrate:e}=Lt("drizzle-orm/better-sqlite3/migrator"),{sql:n}=Lt("drizzle-orm"),r=[re.join(l,"../migrations"),re.join(l,"migrations"),re.join(l,"../../../../drizzle/migrations"),re.join(process.cwd(),"drizzle/migrations")],o=r.find(f=>existsSync(re.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),yd(t,i),s?.cnt&&(Td(t,o),Ed(t,o,n),Sd(t,o,n));let a=Cd(t,o,n,!!s?.cnt),c=Nd(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let _=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(_>0){let f=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${f} (${_} migration${_>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.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(g=>g.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function H(t,e){zo.has(e)||(hn(t),zo.add(e));}var zo,md,kd,Ad,Id,bd,Yo,B=S(()=>{d();zo=new Set,md={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"};kd={"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"}};Ad="0027_task_stop_scope_cleanup",Id="0033_thread_creator_boundary_guard",bd="trg_threads_creator_late_fill_guard",Yo="thread_creator_unverified";});var we,mn=S(()=>{d();we=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var z,x_,L_,yt=S(()=>{d();z=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),pid_started_at:text("pid_started_at"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),security_key:text("security_key"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0),rating:text("rating",{enum:["up","down"]}),rated_at:text("rated_at"),workflow_run_id:text("workflow_run_id"),schedule_id:text("schedule_id")},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),rating_check:check("tasks_rating_ck",sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(sql`${t.rating} IS NOT NULL`)})),{security_key:x_,...L_}=getTableColumns(z);});var ns=S(()=>{d();yt();sqliteTable("task_provider_inputs",{task_id:text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),run_epoch:integer("run_epoch").notNull(),input:text("input").notNull(),key_wrap_skipped:integer("key_wrap_skipped").notNull().default(0),recorded_at:text("recorded_at").notNull()},t=>({pk:primaryKey({columns:[t.task_id,t.run_epoch]})}));});var os=S(()=>{d();yt();sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var $d,Gd,j,kt=S(()=>{d();mn();$d="json_extract(metadata, '$.threadTitle.state')",Gd="json_extract(metadata, '$.threadTitle.priority')",j=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>we.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw($d)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Gd))}));});var as=S(()=>{d();sqliteTable("thread_creator_unverified",{thread_id:text("thread_id").notNull(),created_by_task_id:text("created_by_task_id").notNull()},t=>({pk:primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var fr,cs=S(()=>{d();yt();fr=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>z.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>fr.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var ls=S(()=>{d();yt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>z.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var gs=S(()=>{d();kt();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>j.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var hs,ms=S(()=>{d();kt();hs=sqliteTable("thread_branches",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),parent_thread_id:text("parent_thread_id").notNull().references(()=>j.id),child_thread_id:text("child_thread_id").notNull().unique().references(()=>j.id,{onDelete:"cascade"}),branch_point_task_id:text("branch_point_task_id").notNull(),branch_answer_no:integer("branch_answer_no").notNull(),first_task_id:text("first_task_id").notNull(),parent_title:text("parent_title").notNull(),actor_id:text("actor_id").notNull(),request_id:text("request_id").notNull(),payload_hash:text("payload_hash").notNull(),snapshot_version:integer("snapshot_version").notNull(),carry_json:text("carry_json").notNull(),carried_turns:integer("carried_turns").notNull(),carried_chars:integer("carried_chars").notNull(),carried_truncated:integer("carried_truncated").notNull().default(0),status:text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:text("created_at").notNull(),undone_at:text("undone_at")},t=>({idx_thread_branches_parent_point:index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:check("thread_branches_status_ck",sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:check("thread_branches_carried_truncated_ck",sql`${t.carried_truncated} IN (0, 1)`)})),sqliteTable("thread_branch_sources",{branch_id:text("branch_id").primaryKey().references(()=>hs.id,{onDelete:"cascade"}),source_json:text("source_json").notNull(),bytes:integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:check("thread_branch_sources_bytes_ck",sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var ks=S(()=>{d();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var Ss=S(()=>{d();sqliteTable("request_log_daily",{day:text("day").notNull(),scope:text("scope").notNull(),ok:integer("ok").notNull(),client:integer("client").notNull(),server:integer("server").notNull(),p50_ms:integer("p50_ms"),p95_ms:integer("p95_ms"),computed_at:text("computed_at").notNull()},t=>({pk:primaryKey({columns:[t.day,t.scope]})}));});var Es=S(()=>{d();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Ts=S(()=>{d();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Is=S(()=>{d();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var Cs=S(()=>{d();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Ns=S(()=>{d();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),opened_by_json:text("opened_by_json"),agent_open_request_json:text("agent_open_request_json"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:check("ui_instances_opened_by_json_ck",sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var vs=S(()=>{d();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),definition_id:text("definition_id"),definition_version:integer("definition_version"),definition_hash:text("definition_hash"),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",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),yd(t,i),s?.cnt&&(Td(t,o),Ed(t,o,n),Sd(t,o,n));let a=Cd(t,o,n,!!s?.cnt),c=Nd(t,o,n,!!s?.cnt);e(t,{migrationsFolder:o});let _=(t.get(n`SELECT count(*) as cnt FROM __drizzle_migrations`)?.cnt??0)-i;if(_>0){let f=s?.cnt?"Database migrated":"Database initialized";console.error(`[crewx] ${f} (${_} migration${_>1?"s":""} applied).`);}a&&t.all(n`SELECT hash FROM __drizzle_migrations`).some(g=>g.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(g=>g.hash===c.hash)&&console.error(`[crewx] Thread creator pointer migration (${c.markedPointers} pointer(s) marked unverified).`);}function H(t,e){zo.has(e)||(hn(t),zo.add(e));}var zo,md,kd,Ad,Id,bd,Yo,B=S(()=>{d();zo=new Set,md={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"};kd={"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"}};Ad="0027_task_stop_scope_cleanup",Id="0033_thread_creator_boundary_guard",bd="trg_threads_creator_late_fill_guard",Yo="thread_creator_unverified";});var we,mn=S(()=>{d();we=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),starred:integer("starred").notNull().default(0)});});var z,L_,M_,yt=S(()=>{d();z=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),actor_kind:text("actor_kind",{enum:["human","agent","system","unknown"]}),actor_id:text("actor_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),pid_started_at:text("pid_started_at"),heartbeat_at:text("heartbeat_at"),stop_requested_at:text("stop_requested_at"),stop_requested_epoch:integer("stop_requested_epoch"),rendered_prompt:text("rendered_prompt"),security_key:text("security_key"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),log_storage:text("log_storage",{enum:["blob","events"]}).notNull().default("blob"),last_log_seq:integer("last_log_seq").notNull().default(0),log_revision:integer("log_revision").notNull().default(0),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),cwd:text("cwd"),project_id:text("project_id"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0),run_epoch:integer("run_epoch").default(0),rating:text("rating",{enum:["up","down"]}),rated_at:text("rated_at"),workflow_run_id:text("workflow_run_id"),schedule_id:text("schedule_id")},t=>({log_storage_check:check("tasks_log_storage_ck",sql`${t.log_storage} IN ('blob', 'events')`),rating_check:check("tasks_rating_ck",sql`${t.rating} IN ('up', 'down')`),idx_tasks_agent_id:index("idx_tasks_agent_id").on(t.agent_id),idx_tasks_status:index("idx_tasks_status").on(t.status),idx_tasks_started_at:index("idx_tasks_started_at").on(t.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(t.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(t.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(t.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(t.pid),idx_tasks_status_heartbeat:index("idx_tasks_status_heartbeat").on(t.status,t.heartbeat_at),idx_tasks_thread_id:index("idx_tasks_thread_id").on(t.thread_id),idx_tasks_thread_creator:index("idx_tasks_thread_creator").on(t.id,t.thread_id,t.actor_kind,t.actor_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(t.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(t.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(t.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(t.workspace_id,t.started_at),idx_tasks_ws_rated:index("idx_tasks_ws_rated").on(t.workspace_id,t.rating,t.rated_at).where(sql`${t.rating} IS NOT NULL`)})),{security_key:L_,...M_}=getTableColumns(z);});var ns=S(()=>{d();yt();sqliteTable("task_provider_inputs",{task_id:text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),run_epoch:integer("run_epoch").notNull(),input:text("input").notNull(),key_wrap_skipped:integer("key_wrap_skipped").notNull().default(0),recorded_at:text("recorded_at").notNull()},t=>({pk:primaryKey({columns:[t.task_id,t.run_epoch]})}));});var os=S(()=>{d();yt();sqliteTable("task_log_events",{id:integer("id").primaryKey(),task_id:text("task_id").notNull().references(()=>z.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),timestamp:text("timestamp").notNull(),level:text("level").notNull(),message:text("message").notNull()},t=>({taskSeqUnique:uniqueIndex("task_log_events_task_seq_uq").on(t.task_id,t.seq),timestampIdIndex:index("task_log_events_timestamp_id_idx").on(t.timestamp,t.id)}));});var $d,Gd,j,kt=S(()=>{d();mn();$d="json_extract(metadata, '$.threadTitle.state')",Gd="json_extract(metadata, '$.threadTitle.priority')",j=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>we.id,{onDelete:"set null"}),created_by_kind:text("created_by_kind",{enum:["human","agent","system","unknown"]}),created_by_id:text("created_by_id"),created_by_task_id:text("created_by_task_id"),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0),pinned:integer("pinned").notNull().default(0),starred:integer("starred").notNull().default(0)},t=>({idx_threads_updated_at:index("idx_threads_updated_at").on(t.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(t.workspace_id),idx_threads_ws_updated:index("idx_threads_ws_updated").on(t.workspace_id,t.updated_at),idx_threads_workspace_created_by_kind_updated_at:index("idx_threads_workspace_created_by_kind_updated_at").on(t.workspace_id,t.created_by_kind,t.updated_at),idx_threads_title:index("idx_threads_title").on(t.title),idx_threads_workspace_thread_state:index("idx_threads_workspace_thread_state").on(t.workspace_id,sql.raw($d)),idx_threads_workspace_thread_priority:index("idx_threads_workspace_thread_priority").on(t.workspace_id,sql.raw(Gd))}));});var as=S(()=>{d();sqliteTable("thread_creator_unverified",{thread_id:text("thread_id").notNull(),created_by_task_id:text("created_by_task_id").notNull()},t=>({pk:primaryKey({columns:[t.thread_id,t.created_by_task_id]})}));});var fr,cs=S(()=>{d();yt();fr=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>z.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>fr.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},t=>({idx_spans_task_id:index("idx_spans_task_id").on(t.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(t.parent_span_id)}));});var ls=S(()=>{d();yt();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>z.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},t=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(t.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(t.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(t.timestamp)}));});var gs=S(()=>{d();kt();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>j.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},t=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(t.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(t.thread_id,t.seq),uniq_thread_boxes_thread_seq:unique().on(t.thread_id,t.seq)}));});var hs,ms=S(()=>{d();kt();hs=sqliteTable("thread_branches",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),parent_thread_id:text("parent_thread_id").notNull().references(()=>j.id),child_thread_id:text("child_thread_id").notNull().unique().references(()=>j.id,{onDelete:"cascade"}),branch_point_task_id:text("branch_point_task_id").notNull(),branch_answer_no:integer("branch_answer_no").notNull(),first_task_id:text("first_task_id").notNull(),parent_title:text("parent_title").notNull(),actor_id:text("actor_id").notNull(),request_id:text("request_id").notNull(),payload_hash:text("payload_hash").notNull(),snapshot_version:integer("snapshot_version").notNull(),carry_json:text("carry_json").notNull(),carried_turns:integer("carried_turns").notNull(),carried_chars:integer("carried_chars").notNull(),carried_truncated:integer("carried_truncated").notNull().default(0),status:text("status",{enum:["active","undone"]}).notNull().default("active"),created_at:text("created_at").notNull(),undone_at:text("undone_at")},t=>({idx_thread_branches_parent_point:index("idx_thread_branches_parent_point").on(t.parent_thread_id,t.branch_point_task_id),uniq_thread_branches_request:unique("uniq_thread_branches_workspace_actor_request").on(t.workspace_id,t.actor_id,t.request_id),thread_branches_status_ck:check("thread_branches_status_ck",sql`${t.status} IN ('active', 'undone')`),thread_branches_carried_truncated_ck:check("thread_branches_carried_truncated_ck",sql`${t.carried_truncated} IN (0, 1)`)})),sqliteTable("thread_branch_sources",{branch_id:text("branch_id").primaryKey().references(()=>hs.id,{onDelete:"cascade"}),source_json:text("source_json").notNull(),bytes:integer("bytes").notNull()},t=>({thread_branch_sources_bytes_ck:check("thread_branch_sources_bytes_ck",sql`${t.bytes} >= 0 AND ${t.bytes} <= 524288`)}));});var ks=S(()=>{d();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},t=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(t.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(t.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(t.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(t.partition_key)}));});var Ss=S(()=>{d();sqliteTable("request_log_daily",{day:text("day").notNull(),scope:text("scope").notNull(),ok:integer("ok").notNull(),client:integer("client").notNull(),server:integer("server").notNull(),p50_ms:integer("p50_ms"),p95_ms:integer("p95_ms"),computed_at:text("computed_at").notNull()},t=>({pk:primaryKey({columns:[t.day,t.scope]})}));});var Es=S(()=>{d();sqliteTable("usage_limit_snapshots",{id:text("id").primaryKey(),provider:text("provider").notNull(),account_ref:text("account_ref").notNull().default("default"),limit_window:text("limit_window").notNull(),bucket_start:text("bucket_start").notNull(),captured_at:text("captured_at").notNull(),used_percent:integer("used_percent").notNull(),remaining_percent:integer("remaining_percent").notNull(),resets_at:text("resets_at"),source:text("source").notNull(),metadata:text("metadata")},t=>({uniq_usage_limit_snapshots_bucket:uniqueIndex("uniq_usage_limit_snapshots_bucket").on(t.provider,t.account_ref,t.limit_window,t.bucket_start),idx_usage_limit_snapshots_window_bucket:index("idx_usage_limit_snapshots_window_bucket").on(t.limit_window,t.bucket_start),idx_usage_limit_snapshots_provider_window_bucket:index("idx_usage_limit_snapshots_provider_window_bucket").on(t.provider,t.limit_window,t.bucket_start)}));});var Ts=S(()=>{d();sqliteTable("usage_reports",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),month:text("month").notNull(),generated_at:text("generated_at").notNull(),source_range:text("source_range").notNull(),tier:text("tier").notNull(),total_tokens:integer("total_tokens").notNull(),total_cost_usd:real("total_cost_usd").notNull(),payload:text("payload").notNull(),payload_hash:text("payload_hash"),signature:text("signature"),signed_at:text("signed_at"),issuer:text("issuer")},t=>({uniq_usage_reports_ws_month:uniqueIndex("uniq_usage_reports_ws_month").on(t.workspace_id,t.month)}));});var Is=S(()=>{d();sqliteTable("notifications",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id"),task_id:text("task_id"),thread_id:text("thread_id"),source:text("source").notNull().default("agent"),level:text("level").notNull().default("info"),title:text("title").notNull(),body:text("body"),target_user_id:text("target_user_id"),created_at:text("created_at").notNull(),metadata:text("metadata")},t=>({idx_notifications_ws_created:index("idx_notifications_ws_created").on(t.workspace_id,sql`${t.created_at} DESC`)})),sqliteTable("notification_reads",{notification_id:text("notification_id").notNull(),user_id:text("user_id").notNull(),read_at:text("read_at").notNull()},t=>({pk:primaryKey({columns:[t.notification_id,t.user_id]})}));});var Cs=S(()=>{d();sqliteTable("agent_suggestions",{id:text("id").primaryKey(),workspace_id:text("workspace_id").notNull(),agent_id:text("agent_id").notNull(),task_id:text("task_id"),type:text("type").notNull(),status:text("status").notNull().default("pending"),payload:text("payload").notNull(),applied_commit_sha:text("applied_commit_sha"),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()},t=>({idx_agent_suggestions_ws_agent:index("idx_agent_suggestions_ws_agent").on(t.workspace_id,t.agent_id),idx_agent_suggestions_ws_created:index("idx_agent_suggestions_ws_created").on(t.workspace_id,t.created_at)}));});var Ns=S(()=>{d();sqliteTable("ui_instances",{id:text("id").primaryKey().notNull(),definition_id:text("definition_id").notNull(),definition_version:integer("definition_version").notNull(),definition_hash:text("definition_hash").notNull(),workspace_id:text("workspace_id").notNull(),thread_id:text("thread_id").notNull(),app_id:text("app_id"),anchor_task_id:text("anchor_task_id"),domain_ref_json:text("domain_ref_json").notNull(),state_json:text("state_json").notNull(),revision:integer("revision").notNull().default(0),status:text("status").notNull().default("active"),granted_capabilities_json:text("granted_capabilities_json").notNull().default("[]"),opened_by_json:text("opened_by_json"),agent_open_request_json:text("agent_open_request_json"),created_at:integer("created_at").notNull(),updated_at:integer("updated_at").notNull()},t=>({idCheck:check("ui_instances_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128 AND ${t.id} GLOB 'uic_*'`),definitionIdCheck:check("ui_instances_definition_id_ck",sql`length(${t.definition_id}) BETWEEN 1 AND 128`),definitionVersionCheck:check("ui_instances_definition_version_ck",sql`${t.definition_version} >= 1`),definitionHashCheck:check("ui_instances_definition_hash_ck",sql`length(${t.definition_hash}) = 64 AND ${t.definition_hash} NOT GLOB '*[^0-9a-f]*'`),workspaceIdCheck:check("ui_instances_workspace_id_ck",sql`length(${t.workspace_id}) BETWEEN 1 AND 256`),threadIdCheck:check("ui_instances_thread_id_ck",sql`length(${t.thread_id}) BETWEEN 1 AND 256`),appIdCheck:check("ui_instances_app_id_ck",sql`${t.app_id} IS NULL OR length(${t.app_id}) BETWEEN 1 AND 128`),domainRefJsonCheck:check("ui_instances_domain_ref_json_ck",sql`json_valid(${t.domain_ref_json}) AND json_type(${t.domain_ref_json}) = 'object'`),stateJsonCheck:check("ui_instances_state_json_ck",sql`json_valid(${t.state_json}) AND json_type(${t.state_json}) = 'object'`),revisionCheck:check("ui_instances_revision_ck",sql`${t.revision} >= 0`),statusCheck:check("ui_instances_status_ck",sql`${t.status} IN ('active', 'completed', 'expired', 'revoked', 'unsupported')`),grantedCapabilitiesJsonCheck:check("ui_instances_granted_capabilities_json_ck",sql`json_valid(${t.granted_capabilities_json}) AND json_type(${t.granted_capabilities_json}) = 'array'`),openedByJsonCheck:check("ui_instances_opened_by_json_ck",sql`${t.opened_by_json} IS NULL OR (json_valid(${t.opened_by_json}) AND json_type(${t.opened_by_json}) = 'object')`),createdAtCheck:check("ui_instances_created_at_ck",sql`${t.created_at} >= 0`),updatedAtCheck:check("ui_instances_updated_at_ck",sql`${t.updated_at} >= ${t.created_at}`),workspaceThreadIdx:index("ui_instances_workspace_thread_idx").on(t.workspace_id,t.thread_id),workspaceThreadAppUnique:uniqueIndex("ui_instances_workspace_thread_app_uq").on(t.workspace_id,t.thread_id,t.app_id).where(sql`${t.status} = 'active'`)}));});var vs=S(()=>{d();sqliteTable("ui_action_receipts",{id:text("id").primaryKey().notNull(),instance_id:text("instance_id").notNull(),definition_id:text("definition_id"),definition_version:integer("definition_version"),definition_hash:text("definition_hash"),request_id:text("request_id").notNull(),action_id:text("action_id").notNull(),actor_json:text("actor_json").notNull(),source:text("source").notNull(),expected_revision:integer("expected_revision").notNull(),before_revision:integer("before_revision").notNull(),after_revision:integer("after_revision"),status:text("status").notNull(),outcome:text("outcome"),input_json:text("input_json").notNull(),result_json:text("result_json"),error_code:text("error_code"),requested_at:integer("requested_at").notNull(),settled_at:integer("settled_at")},t=>({idCheck:check("ui_action_receipts_id_ck",sql`length(${t.id}) BETWEEN 5 AND 128`),instanceIdCheck:check("ui_action_receipts_instance_id_ck",sql`length(${t.instance_id}) BETWEEN 1 AND 128`),requestIdCheck:check("ui_action_receipts_request_id_ck",sql`length(${t.request_id}) BETWEEN 1 AND 128`),actionIdCheck:check("ui_action_receipts_action_id_ck",sql`length(${t.action_id}) BETWEEN 1 AND 128`),actorJsonCheck:check("ui_action_receipts_actor_json_ck",sql`json_valid(${t.actor_json}) AND json_type(${t.actor_json}) = 'object'`),sourceCheck:check("ui_action_receipts_source_ck",sql`${t.source} IN ('ui_host', 'cli', 'system', 'mcp')`),expectedRevisionCheck:check("ui_action_receipts_expected_revision_ck",sql`${t.expected_revision} >= 0`),beforeRevisionCheck:check("ui_action_receipts_before_revision_ck",sql`${t.before_revision} >= 0`),afterRevisionCheck:check("ui_action_receipts_after_revision_ck",sql`${t.after_revision} IS NULL OR ${t.after_revision} >= 0`),statusCheck:check("ui_action_receipts_status_ck",sql`${t.status} IN ('requested', 'settled')`),outcomeCheck:check("ui_action_receipts_outcome_ck",sql`${t.outcome} IS NULL OR ${t.outcome} IN ('succeeded', 'rejected', 'failed', 'conflicted', 'expired')`),inputJsonCheck:check("ui_action_receipts_input_json_ck",sql`json_valid(${t.input_json}) AND json_type(${t.input_json}) = 'object'`),resultJsonCheck:check("ui_action_receipts_result_json_ck",sql`${t.result_json} IS NULL OR (json_valid(${t.result_json}) AND json_type(${t.result_json}) = 'object')`),requestedAtCheck:check("ui_action_receipts_requested_at_ck",sql`${t.requested_at} >= 0`),settledAtCheck:check("ui_action_receipts_settled_at_ck",sql`${t.settled_at} IS NULL OR ${t.settled_at} >= ${t.requested_at}`),statusTransitionCheck:check("ui_action_receipts_status_transition_ck",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,20 +50,20 @@ ${r.join(`
|
|
|
50
50
|
`).filter(r=>r.trim());return n.length===0?false:n.every(r=>Ru(r,e))}function ue(t){return typeof t=="object"&&t!==null}function gi(t,e){if(e==="assistant"||e==="user"){let n=t.message;return ue(n)&&Array.isArray(n.content)}return e==="system"?typeof t.subtype=="string"||typeof t.session_id=="string":e==="result"?typeof t.result=="string"||ue(t.usage)||typeof t.total_cost_usd=="number"||typeof t.is_error=="boolean":e==="rate_limit_event"?ue(t.rate_limit_info):e==="tool_progress"?t.heartbeat===true&&typeof t.tool_use_id=="string":false}function Eu(t,e){return typeof t.session_id=="string"||typeof t.uuid=="string"?true:gi(t,e)}function Tu(t,e){if(e==="error")return typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||ue(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 ue(n)&&typeof n.type=="string"}return false}function Au(t,e){if(e==="step_start"||e==="step_finish")return typeof t.stepID=="string"||typeof t.sessionID=="string"||ue(t.part);if(e==="text"||e==="tool_use")return ue(t.part);if(e==="error"){let n=t.error;return ue(n)&&typeof n.type=="string"&&typeof n.message=="string"}return e==="result"?typeof t.result=="string":false}function Iu(t,e){return !!(typeof t.stepID=="string"||typeof t.sessionID=="string"||ue(t.part)||e==="result"&&typeof t.result=="string")}function bu(t,e){return e.startsWith("assistant.")||e.startsWith("tool.execution")||e==="user.message"?ue(t.data):e==="result"?typeof t.result=="string":false}function Cu(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 Nu(t,e){return e==="available_commands"?ue(t.tools)||ue(t.commands):e==="usage"?ue(t.usage):e==="end"?typeof t.sessionId=="string"||typeof t.stopReason=="string"||ue(t.usage):e==="tool_call_update"?typeof t.toolCallId=="string"||typeof t.status=="string":false}var fi,Ou,Zt=S(()=>{d();Vr();Ln();fi={claude:gi,codex:Tu,opencode:Au,copilot:bu,gemini:Cu},Ou={...fi,claude:Eu,opencode:Iu,grok:Nu,antigravity:t=>_i(JSON.stringify(t))};});function xe(t){return /crewx\s+(q|query|x|execute)\s/.test(t)}function Le(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 Nt=S(()=>{d();});function Pu(t){let e=xu(t),n=e.map((s,i)=>({line:s,index:i})).filter(({line:s})=>Mu(s.value)),r=Lu(e);return {result:n.length===1&&n[0].index===r?Fu(n[0].line.value):null,resultPreview:Bu(e,n),hasReservedLine:n.length>0}}function Me(t,e){let n=Pu(t);return {resultPreview:n.resultPreview,isError:e||n.result?.isError===true,...n.hasReservedLine?{delegationResult:n.result}:{}}}function xu(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 Lu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Mu(t){return t.trimStart().startsWith(vu)}function Fu(t){let e=t.trim();if(!e.startsWith(hi)||!e.endsWith("]]"))return null;let n=e.slice(hi.length,-2);if(!n)return null;try{return Uu(JSON.parse(n))}catch{return null}}function Uu(t){return qu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function qu(t){if(!Hu(t)||Object.keys(t).some(r=>!Du.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?mi(t.taskId)&&mi(t.agentId):t.isError===true}function Bu(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 mi(t){return typeof t=="string"&&t.trim().length>0}function Hu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hi,vu,Du,Ot=S(()=>{d();hi="[[crewx:delegation-result ",vu="[[crewx:delegation-result",Du=new Set(["schema","taskId","agentId","isError"]);});function Fe(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 vt=S(()=>{d();});var yi,Mn,Yr,Fn=S(()=>{d();yi=["none","minimal","low","medium","high","xhigh","max","ultra"],Mn={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"]},Yr={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(Yr).map(([t,e])=>[t,e.models]));});function Jr(t){return Gu[t]??t}function Wu(t){return ju.get(t)??t}function Xr(t){if(!t)return {};let e=Vu.get(t);return e?{...e}:{model:t}}function Qr(t,e){return t==="antigravity"||t==="cli/antigravity"?Xr(e):e===void 0?{}:{model:Wu(e)}}var $u,Gu,ju,Ku,Vu,en=S(()=>{d();$u=[{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]"}],Gu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};ju=new Map($u.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Ku=[{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"}],Vu=new Map(Ku.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Yu(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ye(t){return tn(t).models}function tn(t){let e=zu[t],n=Yr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Yu()}function nn(t,e){let n=tn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Qr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Zr(t){return tn(t).modelOverrides}function ki(){return Ye("claude")}function Si(){return Ye("codex")}function wi(){return Ye("copilot")}function Ri(){return Ye("antigravity")}var zu,Je=S(()=>{d();Fn();vn();en();zu={};});function Ei(t){return Xu[t]??t}var Xu,Ti=S(()=>{d();Je();en();Xu={auto:"default"};});function eo(t,e){return (Mn[t]??[]).includes(e)}function ut(t){if(!t)return {};let e=t.match(/^(.+?)\[([^\]]+)\]$/);if(e){let n=e[2].toLowerCase();return Qu.has(n)?{model:e[1],effort:n}:{model:t}}return {model:t}}function Ai(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 Ii(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 bi(t){return !t||!eo("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Ci(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Ei(t);return e.has(n)?["--permission-mode",n]:[]}function Ni(t){return t?eo("claude",t)?["--effort",t]:[]:[]}function Oi(t){if(!t)return [];switch(Jr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function vi(t){return t?eo("antigravity",t)?["--effort",t]:[]:[]}var Qu,rn=S(()=>{d();Ti();en();Fn();Qu=new Set(yi);});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 el(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 tl(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 Di(t){let e=new Map,n;for(let s of t.split(`
|
|
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 Lu(t){for(let e=t.length-1;e>=0;e--)if(t[e].value.trim())return e;return -1}function Mu(t){return t.trimStart().startsWith(vu)}function Fu(t){let e=t.trim();if(!e.startsWith(hi)||!e.endsWith("]]"))return null;let n=e.slice(hi.length,-2);if(!n)return null;try{return Uu(JSON.parse(n))}catch{return null}}function Uu(t){return qu(t)?Object.prototype.hasOwnProperty.call(t,"taskId")?{schema:1,taskId:t.taskId,agentId:t.agentId,isError:t.isError}:{schema:1,isError:true}:null}function qu(t){if(!Hu(t)||Object.keys(t).some(r=>!Du.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?mi(t.taskId)&&mi(t.agentId):t.isError===true}function Bu(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 mi(t){return typeof t=="string"&&t.trim().length>0}function Hu(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var hi,vu,Du,Ot=S(()=>{d();hi="[[crewx:delegation-result ",vu="[[crewx:delegation-result",Du=new Set(["schema","taskId","agentId","isError"]);});function Fe(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 vt=S(()=>{d();});var yi,Mn,Yr,Fn=S(()=>{d();yi=["none","minimal","low","medium","high","xhigh","max","ultra"],Mn={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"]},Yr={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(Yr).map(([t,e])=>[t,e.models]));});function Jr(t){return Gu[t]??t}function Wu(t){return ju.get(t)??t}function Xr(t){if(!t)return {};let e=Vu.get(t);return e?{...e}:{model:t}}function Qr(t,e){return t==="antigravity"||t==="cli/antigravity"?Xr(e):e===void 0?{}:{model:Wu(e)}}var $u,Gu,ju,Ku,Vu,en=S(()=>{d();$u=[{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]"}],Gu={"accept-edits":"acceptEdits",yolo:"bypassPermissions","agent-full-access":"bypassPermissions"};ju=new Map($u.map(({baseModelId:t,catalogModelId:e})=>[t,e]));Ku=[{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"}],Vu=new Map(Ku.map(({legacyId:t,model:e,effort:n})=>[t,n===void 0?{model:e}:{model:e,effort:n}]));});function Yu(){return {models:[],modes:[],effort:[],modelOverrides:{},providerOptions:[]}}function Ye(t){return tn(t).models}function tn(t){let e=zu[t],n=Yr[t];return e?e.suggestedModels!==void 0||n?.suggestedModels===void 0?e:{...e,suggestedModels:n.suggestedModels}:n??Yu()}function nn(t,e){let n=tn(t);if(e){if(Object.prototype.hasOwnProperty.call(n.modelOverrides,e))return n.modelOverrides[e]?.effort??n.effort;let r=Qr(t,e);return r.model===void 0?n.effort:n.modelOverrides[r.model]?.effort??n.effort}return n.effort}function Zr(t){return tn(t).modelOverrides}function ki(){return Ye("claude")}function Si(){return Ye("codex")}function wi(){return Ye("copilot")}function Ri(){return Ye("antigravity")}var zu,Je=S(()=>{d();Fn();vn();en();zu={};});function Ei(t){return Qu[t]??t}var Qu,Ti=S(()=>{d();Je();en();Qu={auto:"default"};});function eo(t,e){return (Mn[t]??[]).includes(e)}function ut(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 Ai(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 Ii(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 bi(t){return !t||!eo("codex",t)?[]:["-c",`model_reasoning_effort=${t}`]}function Ci(t){if(!t)return [];let e=new Set(["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"]),n=Ei(t);return e.has(n)?["--permission-mode",n]:[]}function Ni(t){return t?eo("claude",t)?["--effort",t]:[]:[]}function Oi(t){if(!t)return [];switch(Jr(t)){case "default":return [];case "plan":return ["--mode","plan"];case "acceptEdits":return ["--mode","accept-edits"];case "bypassPermissions":return ["--dangerously-skip-permissions"];default:return []}}function vi(t){return t?eo("antigravity",t)?["--effort",t]:[]:[]}var Zu,rn=S(()=>{d();Ti();en();Fn();Zu=new Set(yi);});function el(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 tl(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 nl(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 Di(t){let e=new Map,n;for(let s of t.split(`
|
|
54
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 _=Number(u.input_tokens??0),f=Number(u.cache_read_input_tokens??0);e.set(c,{inputTokens:_+f,cachedInputTokens:f});let g=a?.model;typeof g=="string"&&g&&(n=g);}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 on(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=
|
|
55
|
+
`))if(r.trim())try{let o=JSON.parse(r),s=nl(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=el(o)??tl(o);i&&(e=i);}catch{}return n||(e??void 0)}var sn=S(()=>{d();});function Ge(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 lt=S(()=>{d();});var Un,Pi=S(()=>{d();Un=Object.freeze({CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"});});function Li(t){return t==="all"?[...xi,...rl]:xi}function Mi(t){return Li(t).map(e=>`Bash(${e} *)`)}function Fi(t){return Li(t).map(e=>`command(${e})`)}var xi,rl,to=S(()=>{d();xi=["crewx memory","crewx search","crewx doc","crewx notify"],rl=["crewx q","crewx query","crewx x","crewx execute","crewx cron","crewx wbs","crewx wi","crewx workflow","crewx app","crewx skill"];});function Ui(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 qi(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 Dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ji(t){let e=Dt(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=Dt(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 Dt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function ji(t){let e=Dt(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=cl(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(ul(n))return `Claude rate limit: ${n}`}}function il(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=Dt(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 al(t){let e=Dt(t);if(e?.type!=="rate_limit_event")return;let n=Dt(Dt(e.rate_limit_info)?.unifiedWindows);if(!n)return;let r=Bi(n.five_hour),o=Bi(n.seven_day);if(!(!r&&!o))return {...r?{five_hour:r}:{},...o?{seven_day:o}:{}}}function Bi(t){let e=Dt(t);if(!(typeof e?.utilization!="number"||typeof e.resetsAt!="number"))return {utilization:e.utilization,resetsAt:e.resetsAt}}function Hi(t){if(t?.is_error===true)return Pn(t.result)}function dl(t){let e=ji(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 cl(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,...Me(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=Di(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=Ge(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 Xe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Xe(t.error)}function Ji(t){let e=Xe(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:Xe(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=Fe(s);return o==="Bash"&&xe(i)?Le(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",...Me(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&&!(Xe(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 Sl(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=Fe(o);return r==="Bash"&&xe(s)?Le(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var _l,gl,so=S(()=>{d();ze();Zt();sn();Nt();vt();Vr();Ot();rn();Je();lt();_l=new Set(["turn.started","turn.completed","item.updated"]),gl="cli/codex";({command:"codex",meta:{displayName:"Codex",models:Si(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ut(e.model),s=e.effort??o,i=e.resumeSessionId?Ii(e.mode):Ai(e.mode),a=bi(s),c=r?["-m",r]:[],u=hl(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=ml(t);if(e)throw new W(e,gl);let n=Vi(t);if(n)return n;let r=t.trim();return ct(r,"codex")?"":r},extractPartialText(t){return Vi(t)},parseResultMeta(t){let e=on(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=fl(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(!Xe(c))continue;let u=c.type;if(!u)continue;let _=Ge(c,r);if(Yi(c)){let g=Ji(c);o.push({timestamp:_,type:"error",content:g,errorMessage:g});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Kr(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let f=c.item;if(f){if(u==="item.started"){o.push(...yl(_,f,zi(f,u,n,i)));continue}if(u==="item.completed"){let g=kl(_,f,zi(f,u,n,i));g&&o.push(g);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?_l.has(r):!1}catch{return false}}});});var Qi=S(()=>{d();});var Zi=S(()=>{d();});function Rl(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 El(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),ea),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:ea,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(Rl(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function Tl(){return process.platform!=="win32"?Promise.resolve(null):(qn||(qn=El(),qn.then(t=>{},()=>{})),qn)}function Al(){process.platform==="win32"&&Tl();}var ea,qn,na=S(()=>{d();ea=1e3;Al();});var io=S(()=>{d();});var ra=S(()=>{d();});var ao=S(()=>{d();ze();io();ra();});var oa=S(()=>{d();co();Zi();na();io();ao();Je();});var uo=S(()=>{d();ze();Qi();sn();vt();lt();oa();ao();});var sa=S(()=>{d();});function Pt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ll(t,e){return t&&ia.has(t)||Pt(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"&&ia.has(o)})}function Ml(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 Fl(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(!Pl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ul(t,e){if(!(t?Dl.has(t)||Ye(lo).some(s=>s.id===t):false)||!t)return e;let r=nn(lo,t),o=Zr(lo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function je(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function go(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 fo(t){return t.step.step_index}function G(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Pn(e)?.slice(0,500).trim()||void 0}function ql(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&xl.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 Bl(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 ca(t){let e=ye(t)?t:void 0,n=e&&ye(e.error)?e.error:void 0,r=e?G(e.code)??G(e.error_code)??G(n?.code)??G(n?.error_code):void 0,o=typeof t=="string"?G(t):e?G(e.message)??G(e.error)??G(e.reason)??G(n?.message)??G(n?.error)??G(n?.reason):void 0,s=ql(r,o),i=e?je(e.retry_after_ms)??je(e.retryAfterMs)??je(n?.retry_after_ms)??je(n?.retryAfterMs):void 0;return {code:s,kind:Bl(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Hn(t){let e=ca(t);return new W(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function ho(t){return new W(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function Hl(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=_o))throw new W(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${_o} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function po(){return new W("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 $n(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Gn(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 $l(t){let e=Gn(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||$n(e.event)?.status!=="SUCCESS"||Bn(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=go(o),i=fo(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"||!ye(o.usage)||je(o.usage.input_tokens)===void 0||je(o.usage.output_tokens)===void 0)return false;return true}function Gl(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function jl(t,e){return ye(t)&&ye(e)?{...e,...t}:ye(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&ye(e)?{...e,message:t}:t??e}function Wl(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=ye(i)?i:void 0,c=typeof i=="string"?G(i):G(a?.display_name)??G(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 W("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Bn(t){let e=Gn(t);if(!e)return;if(e.event.kind==="agy_error")return Hn(e.event.error);let n=$n(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Wl(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return ho("Antigravity returned a result with an unsupported status.");let r=n.error,o=jl(r==null||r===""?n:r,Gl(t,e.index));return Hn(o)}function ua(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function Kl(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function Vl(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function la(t){let e=ua(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function zl(t){let e=ye(t)?t:void 0,n=e&&ye(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(G(e?.type)??G(e?.code)??G(e?.error_type)??G(n?.type)??G(n?.code)??G(n?.error_type)??G(r)??"TOOL_ERROR").slice(0,60),s=ca(t).message.slice(0,250);return la({type:o,message:s})??"Antigravity reported a tool error."}function aa(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function da(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var lo,Dl,Pl,ia,_o,xl,mo=S(()=>{d();ze();sa();jr();en();Je();rn();Ln();to();lo="antigravity",Dl=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),Pl=new Set(["--conversation","--resume","--continue"]),ia=new Set(["bypassPermissions","agent-full-access","yolo"]),_o=18e4,xl=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:_o,meta:{displayName:"Antigravity",models:Ri(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Qt(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){Hl(t);let{model:r,effort:o}=ut(e.model),s=Xr(r),i=s.model,a=e.effort??o??s.effort,c=Ul(i,a),u=e.additionalArgs??[],_=Fl(Ml(u,new Set(["--input-format","--output-format"]))),f=i&&!Pt(u,"--model")?["--model",i]:[],g=Pt(u,"--effort")?[]:vi(c),w=Pt(u,"--mode")||Pt(u,"--dangerously-skip-permissions")?[]:Oi(e.mode),R=Ll(e.mode,u)||Pt(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Fi(e.builtinAllow)}})],T=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...f,...g,...w,...T,...R,..._],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
66
|
-
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Ct(t),n=Gn(e)?.event,r=Bn(e);if(r)throw r;let o=n?$n(n):void 0;if(o){if(o.status!=="SUCCESS")throw ho("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw ho("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw po();return o.response}if(e.length>0)throw po();let s=t.trim();if(!s)throw po();return s},extractPartialText(t){let e=Ct(t),n=Gn(e)?.event;if(!n||n.kind==="agy_error")return;let r=$n(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Ct(n??""),o=Bn(r);return o||(t!==0&&e.trim()?Hn(e):null)},parseResultMeta(t){let e=Ct(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"||!ye(c.step.usage))continue;let u=go(c),_=fo(c);if(!u||!Number.isSafeInteger(_))continue;let f=JSON.stringify([u,_]);if(i.has(f))continue;let g=c.step.usage,w=je(g.input_tokens),R=je(g.output_tokens);if(w===void 0||R===void 0)continue;i.add(f);let T=je(g.cache_read_tokens)??0;n+=w+T,r+=R,o+=T,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete
|
|
60
|
+
`):""}function ul(t){let e=t.toLowerCase();return e.includes("out of extra usage")||e.includes("rate limit")||e.includes("quota")}function Gi(t){return t.replace(/\s+/g," ").trim()}function ll(t,e){let n=t?.description;if(typeof n!="string")return;let r=Gi(n);if(!r||r===Gi(e))return;if(r.length<=$i)return r;let o=r.slice(0,$i-1);return /[\uD800-\uDBFF]$/.test(o)&&(o=o.slice(0,-1)),`${o}\u2026`}function pl(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=Fe(s);if(r==="Bash"&&xe(i))return Le(t,i,o);let a=ll(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,...Me(i,r)}}return null}var ol,sl,no,$i,ro=S(()=>{d();Gr();ze();jr();Zt();Nt();Ot();vt();rn();Je();sn();lt();Pi();to();ol=new Set(["tool_progress"]),sl="cli/claude";no={command:"claude",meta:{displayName:"Claude",models:ki(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ut(e.model),s=e.effort??o,i=Ci(e.mode),a=Ni(s),c=r?["--model",r]:[],u=e.mode==="bypassPermissions"?[]:["--allowedTools",...Mi(e.builtinAllow)],_=e.resumeSessionId?["--resume",e.resumeSessionId]:[];if(e.additionalArgs!==void 0){let g=[...e.additionalArgs];return g.indexOf("-p")!==-1?{args:["--output-format","stream-json","--verbose",..._,...i,...a,...c,...u,...g],stdinMessage:t,env:Un}:{args:["--output-format","stream-json","--verbose",..._,...i,...a,...c,...u,...g],stdinMessage:t,env:Un}}return {args:["-p","--output-format","stream-json","--verbose",..._,...i,...a,...c,...u],stdinMessage:t,env:Un}},extractText(t){let e=qi(t);if(e?.is_error===true){let o=no.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 W(Hi(e)??`Claude ended without an answer (subtype=${s}, terminal_reason=${i})`,sl,{code:"EMPTY_OUTPUT",kind:"permanent"})}let n=Ui(t);if(n)return n;let r=t.trim();return ct(r,"claude")?"":r},extractPartialText(t){return Ui(t)},extractFailure(t){try{let e=JSON.parse(t),n=ji(e);if(n)return new Xt(n)}catch{}return null},interpretExit(t,e,n){let r=il(n??"");if(r)return new W(`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=Hi(qi(n??""));return o?new W(o,"cli/claude"):null},observeRateLimit(t){try{let e=JSON.parse(t);return al(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=Di(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=Ge(n,e??new Date().toISOString()),s=dl(n);if(s)return [{timestamp:o,type:"error",content:s,errorMessage:s}];let i=n.output_file,a=n.summary;if(r==="system"&&n.subtype==="task_notification"&&n.status==="completed"&&typeof i=="string"&&i.trim().length>0&&typeof a=="string"&&a.trim().length>0)return [{timestamp:o,type:"text",content:a}];if(r!=="assistant"&&r!=="user")return [];let u=n.message?.content;if(!Array.isArray(u))return [];let _=[];for(let f of u){let g=pl(o,f);g&&_.push(g);}return _},suppressOutputLine(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return false;try{let r=JSON.parse(e).type;return r?ol.has(r):!1}catch{return false}}};$i=200;});function Wi(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 _l,oo=S(()=>{d();Zt();sn();Nt();vt();Ot();Je();Fn();lt();_l=new Set(["interactive","plan","autopilot"]);({command:"copilot",meta:{displayName:"Copilot",models:wi()},buildArgs(t,e,n){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),e.mode&&_l.has(e.mode)&&r.push("--mode",e.mode),e.effort&&(Mn.copilot??[]).includes(e.effort)&&r.push("--effort",e.effort),{args:r,stdinMessage:t}},extractText(t){let e=Wi(t);if(e)return e;let n=t.trim();return ct(n,"copilot")?"":n},extractPartialText(t){return Wi(t)},parseResultMeta(t){let e=on(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=Ge(n,e??new Date().toISOString()),i=o.toolCallId;if(r==="tool.execution_start"){let a=String(o.toolName||""),c=o.arguments,u=Fe(c);return (a==="bash"||a==="Bash")&&xe(u)?[Le(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},...Me(String(a.message||""),true)}];let c=o.result,u=String(c?.content||"");return [{timestamp:s,type:"tool_result",...i&&{toolUseId:i},...Me(u,false)}]}if(r==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}});});function hl(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 ml(t){return t[0]==="exec"?t.slice(1):t}function Vi(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 Xe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Yi(t){return t.type==="turn.failed"?true:t.type!=="error"?false:typeof t.message=="string"||typeof t.errorMessage=="string"||typeof t.error=="string"||Xe(t.error)}function Ji(t){let e=Xe(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 yl(t){for(let e of t.split(/\r?\n/)){if(!e.trim())continue;let n;try{n=JSON.parse(e);}catch{continue}if(Xe(n)&&Yi(n))return Ji(n)}}function zi(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 kl(t,e,n){let r=e.type;if(r==="command_execution"){let o=String(e.command||"");return xe(o)?[Le(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:Fe(e.arguments),...n?{toolUseId:n}:{}}]:[]}function Sl(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=wl(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",...Me(o,s),...n?{toolUseId:n}:{}}}if(r==="mcp_tool_call"){let o=Xe(e.result)?e.result:void 0,i=(Array.isArray(o?.content)?o.content:[]).filter(c=>Xe(c)&&c.type==="text"&&typeof c.text=="string").map(c=>c.text).join(`
|
|
65
|
+
`),a=typeof e.error=="string"?e.error:Xe(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=Fe(s);return o==="Bash"&&xe(i)?Le(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",...Me(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&&!(Xe(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 wl(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=Fe(o);return r==="Bash"&&xe(s)?Le(t,s):{timestamp:t,type:"tool_use",toolName:r,toolInput:s}}return null}var gl,fl,so=S(()=>{d();ze();Zt();sn();Nt();vt();Vr();Ot();rn();Je();lt();gl=new Set(["turn.started","turn.completed","item.updated"]),fl="cli/codex";({command:"codex",meta:{displayName:"Codex",models:Si(),capabilities:{resume:true}},buildArgs(t,e,n){let{model:r,effort:o}=ut(e.model),s=e.effort??o,i=e.resumeSessionId?Ii(e.mode):Ai(e.mode),a=bi(s),c=r?["-m",r]:[],u=ml(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=yl(t);if(e)throw new W(e,fl);let n=Vi(t);if(n)return n;let r=t.trim();return ct(r,"codex")?"":r},extractPartialText(t){return Vi(t)},parseResultMeta(t){let e=on(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=hl(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(!Xe(c))continue;let u=c.type;if(!u)continue;let _=Ge(c,r);if(Yi(c)){let g=Ji(c);o.push({timestamp:_,type:"error",content:g,errorMessage:g});continue}if(!u.startsWith("item.")&&!u.startsWith("turn.")&&!u.startsWith("thread.")||Kr(c))continue;u==="thread.started"&&n&&n.state.delete("codex.pending");let f=c.item;if(f){if(u==="item.started"){o.push(...kl(_,f,zi(f,u,n,i)));continue}if(u==="item.completed"){let g=Sl(_,f,zi(f,u,n,i));g&&o.push(g);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?gl.has(r):!1}catch{return false}}});});var Qi=S(()=>{d();});var Zi=S(()=>{d();});function El(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 Tl(){return new Promise(t=>{let e=false,n,r=o=>{e||(e=true,n&&clearTimeout(n),t(o));};n=setTimeout(()=>r(null),ea),n.unref();try{execFile("chcp.com",[],{encoding:"ascii",timeout:ea,windowsHide:!0},(s,i)=>{if(s){r(null);return}r(El(String(i)));}).once("error",()=>r(null));}catch{r(null);}})}function Al(){return process.platform!=="win32"?Promise.resolve(null):(qn||(qn=Tl(),qn.then(t=>{},()=>{})),qn)}function Il(){process.platform==="win32"&&Al();}var ea,qn,na=S(()=>{d();ea=1e3;Il();});var io=S(()=>{d();});var ra=S(()=>{d();});var ao=S(()=>{d();ze();io();ra();});var oa=S(()=>{d();co();Zi();na();io();ao();Je();});var uo=S(()=>{d();ze();Qi();sn();vt();lt();oa();ao();});var sa=S(()=>{d();});function Pt(t,e){return t.some(n=>n===e||n.startsWith(`${e}=`))}function Ml(t,e){return t&&ia.has(t)||Pt(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"&&ia.has(o)})}function Fl(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 Ul(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(!xl.has(s)){e.push(r);continue}r===s&&n+1<t.length&&!t[n+1].startsWith("-")&&(n+=1);}return e}function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ql(t,e){if(!(t?Pl.has(t)||Ye(lo).some(s=>s.id===t):false)||!t)return e;let r=nn(lo,t),o=Zr(lo)[t]?.defaultEffort;if(r.length!==0)return e?r.includes(e)?e:o&&r.includes(o)?o:void 0:o}function je(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:void 0}function go(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 fo(t){return t.step.step_index}function G(t){if(typeof t!="string")return;let e=t.split(/\r?\n/,1)[0]?.trim();return e&&Pn(e)?.slice(0,500).trim()||void 0}function Bl(t,e){let n=(t??"").trim().toUpperCase().replace(/[^A-Z0-9]+/g,"_");if(n!=="UNKNOWN"&&Ll.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 Hl(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 ca(t){let e=ye(t)?t:void 0,n=e&&ye(e.error)?e.error:void 0,r=e?G(e.code)??G(e.error_code)??G(n?.code)??G(n?.error_code):void 0,o=typeof t=="string"?G(t):e?G(e.message)??G(e.error)??G(e.reason)??G(n?.message)??G(n?.error)??G(n?.reason):void 0,s=Bl(r,o),i=e?je(e.retry_after_ms)??je(e.retryAfterMs)??je(n?.retry_after_ms)??je(n?.retryAfterMs):void 0;return {code:s,kind:Hl(s),message:o??"Antigravity reported a terminal error.",...i===void 0?{}:{retryAfterMs:i}}}function Hn(t){let e=ca(t);return new W(e.message,"cli/antigravity",{code:e.code,kind:e.kind,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}})}function ho(t){return new W(t,"cli/antigravity",{code:"INVALID_PROVIDER_FORMAT",kind:"config"})}function $l(t){let e=new TextEncoder().encode(t).byteLength;if(!(e<=_o))throw new W(`Input is too large: final provider initial input is ${e} UTF-8 bytes; budget is ${_o} bytes.`,"cli/antigravity",{code:"UNKNOWN",kind:"config"})}function po(){return new W("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 $n(t){if(t.kind==="result"||t.kind==="legacy_result")return t.result}function Gn(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 Gl(t){let e=Gn(t);if(!e||e.event.kind==="agy_error"||e.index!==t.length-1||$n(e.event)?.status!=="SUCCESS"||Bn(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=go(o),i=fo(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"||!ye(o.usage)||je(o.usage.input_tokens)===void 0||je(o.usage.output_tokens)===void 0)return false;return true}function jl(t,e){for(let n=e-1;n>=0;n-=1){let r=t[n];if(r?.kind==="agy_error")return r.error}}function Wl(t,e){return ye(t)&&ye(e)?{...e,...t}:ye(t)&&typeof e=="string"?{...t,message:e}:typeof t=="string"&&ye(e)?{...e,message:t}:t??e}function Kl(t){let e=Array.isArray(t.denied_actions)?t.denied_actions:[],n=[];for(let i of e){let a=ye(i)?i:void 0,c=typeof i=="string"?G(i):G(a?.display_name)??G(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 W("Could not run because of permissions.","cli/antigravity",{code:"UNKNOWN",kind:"permanent",providerReason:s})}function Bn(t){let e=Gn(t);if(!e)return;if(e.event.kind==="agy_error")return Hn(e.event.error);let n=$n(e.event);if(!n)return;if(Array.isArray(n.denied_actions)&&n.denied_actions.length>0)return Kl(n);if(n.status==="SUCCESS")return;if(n.status!=="ERROR")return ho("Antigravity returned a result with an unsupported status.");let r=n.error,o=Wl(r==null||r===""?n:r,jl(t,e.index));return Hn(o)}function ua(t){if(typeof t=="string")return t;if(t!=null)try{return JSON.stringify(t)}catch{return}}function Vl(t){return `agy:${String(t.conversation_id)}:${String(t.step_index)}`}function zl(t,e){let n=typeof e?.name=="string"?e.name:t.tool_name;return typeof n=="string"&&n.trim()?n:void 0}function la(t){let e=ua(t);if(e)return e.length<=2e3?e:`${e.slice(0,1999)}\u2026`}function Yl(t){let e=ye(t)?t:void 0,n=e&&ye(e.error)?e.error:void 0,r=typeof t=="string"?t.trim().match(/^([A-Z][A-Z0-9_]*)(?:[:\s]|$)/)?.[1]:void 0,o=(G(e?.type)??G(e?.code)??G(e?.error_type)??G(n?.type)??G(n?.code)??G(n?.error_type)??G(r)??"TOOL_ERROR").slice(0,60),s=ca(t).message.slice(0,250);return la({type:o,message:s})??"Antigravity reported a tool error."}function aa(t,e){return t?t.state.has(e)?true:(t.state.set(e,true),false):false}function da(t,e){return {timestamp:t,type:"error",content:e.message,errorMessage:e.message,isError:true}}var lo,Pl,xl,ia,_o,Ll,mo=S(()=>{d();ze();sa();jr();en();Je();rn();Ln();to();lo="antigravity",Pl=new Set(["claude-sonnet-4-6","claude-opus-4-6-thinking","gpt-oss-120b"]),xl=new Set(["--conversation","--resume","--continue"]),ia=new Set(["bypassPermissions","agent-full-access","yolo"]),_o=18e4,Ll=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:_o,meta:{displayName:"Antigravity",models:Ri(),defaultIdleMs:6e5,capabilities:{resume:true,usageCompleteness:true}},extractSessionId(t){let e=Qt(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){$l(t);let{model:r,effort:o}=ut(e.model),s=Xr(r),i=s.model,a=e.effort??o??s.effort,c=ql(i,a),u=e.additionalArgs??[],_=Ul(Fl(u,new Set(["--input-format","--output-format"]))),f=i&&!Pt(u,"--model")?["--model",i]:[],g=Pt(u,"--effort")?[]:vi(c),w=Pt(u,"--mode")||Pt(u,"--dangerously-skip-permissions")?[]:Oi(e.mode),R=Ml(e.mode,u)||Pt(u,"--settings")?[]:["--settings",JSON.stringify({permissions:{allow:Fi(e.builtinAllow)}})],T=typeof e.resumeSessionId=="string"&&e.resumeSessionId.trim().length>0?["--conversation",e.resumeSessionId]:[];return {args:["--input-format","stream-json","--output-format","stream-json",...f,...g,...w,...T,...R,..._],stdinMessage:`${JSON.stringify({event:"user",message:{content:t}})}
|
|
66
|
+
`,env:{AGY_CLI_DISABLE_AUTO_UPDATE:"true"}}},extractText(t){let e=Ct(t),n=Gn(e)?.event,r=Bn(e);if(r)throw r;let o=n?$n(n):void 0;if(o){if(o.status!=="SUCCESS")throw ho("Antigravity returned a result with an unsupported status.");if(typeof o.response!="string")throw ho("Antigravity returned a successful result without a response string.");if(!o.response.trim())throw po();return o.response}if(e.length>0)throw po();let s=t.trim();if(!s)throw po();return s},extractPartialText(t){let e=Ct(t),n=Gn(e)?.event;if(!n||n.kind==="agy_error")return;let r=$n(n);return r&&typeof r.response=="string"&&r.response.trim()?r.response:void 0},interpretExit(t,e,n){let r=Ct(n??""),o=Bn(r);return o||(t!==0&&e.trim()?Hn(e):null)},parseResultMeta(t){let e=Ct(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"||!ye(c.step.usage))continue;let u=go(c),_=fo(c);if(!u||!Number.isSafeInteger(_))continue;let f=JSON.stringify([u,_]);if(i.has(f))continue;let g=c.step.usage,w=je(g.input_tokens),R=je(g.output_tokens);if(w===void 0||R===void 0)continue;i.add(f);let T=je(g.cache_read_tokens)??0;n+=w+T,r+=R,o+=T,s+=1;}return {usage:s===0?null:{inputTokens:n,outputTokens:r,cachedInputTokens:o,costUsd:0,complete:Gl(e)},model:null}},parseEvent(t,e,n){let r=Qt(t);if(!r)return [];let o=e??new Date().toISOString();if(r.kind==="agy_error")return [da(o,Hn(r.error))];if(r.kind==="legacy_result"||r.kind==="result"){let w=Bn([r]);return w?[da(o,w)]:[]}if(r.kind!=="step_update")return [];let{step:s}=r,i=go(r)??"unknown",a=fo(r),c=`${i}:${a}`;if((s.state==="DONE"||s.state==="ERROR")&&aa(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=ye(s.tool_info)?s.tool_info:void 0,_=zl(s,u);if(!_)return [];let f=Vl(s);if(s.state==="ACTIVE"){if(aa(n,`antigravity:active:${c}`))return [];let w=ua(u?.parameters);return [{timestamp:o,type:"tool_use",toolName:_,toolUseId:f,...w===void 0?{}:{toolInput:w}}]}let g=s.state==="ERROR"?Yl(u?.error):la(u?.output);return [{timestamp:o,type:"tool_result",toolName:_,toolUseId:f,...g===void 0?{}:{resultPreview:g},...s.state==="ERROR"?{isError:true}:{}}]}});});var _a=S(()=>{d();Nt();vt();Ot();lt();});var yo=S(()=>{d();ze();Gr();Je();Ot();rn();lt();});var co=S(()=>{d();ro();oo();so();uo();mo();_a();yo();ro();oo();so();uo();mo();yo();Nt();});var ga=S(()=>{d();di();co();});var ko=S(()=>{d();ga();vn();});var an,pt=S(()=>{d();an=["success","completed","done","failed","error","stopped","runner_lost"];});var dn=S(()=>{d();});var wo=S(()=>{d();$r();dn();});var up,xt=S(()=>{d();x();F();B();M();U();At();vn();Hr();$r();Dn();Ur();ko();pt();dn();wo();dn();At();up="0.8.9-rc.13",parseInt(up.split("rc.")[1]),new Set(an);});d();d();d();var A="workout-log",Qe="workout-log.records.v1",_t=500,Vn=100,zn=4096,Mt=6e4,Yn=200,Ft=20,cn=6e4;d();var Ut=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 Fa=Qe,ge=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"])}),Jn=Object.freeze({exactFiles:Object.freeze(["exercises.md"]),directFolders:Object.freeze(["routines","workouts"]),suffix:".md",maxDepth:1}),Ua=/^[A-Za-z0-9_-]{1,40}$/,Oo=["root","include","idPattern","exclude"];function vo(t,e){return Array.isArray(t)&&t.length===e.length&&t.every((n,r)=>n===e[r])}function qa(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ba(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||!Ua.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 Ha(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 $a(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
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 _=u[1];if(r.has(_))return null;let f=Ha(u[2]);if(f===null)return null;r.set(_,f);}if(s<0)break;o=s+1;}return null}var qt=class{scopeVersion=Qe;definition=ge;matchesDefinition(e,n){return e!==Fa||!qa(n)||Object.keys(n).length!==Oo.length||!Oo.every(r=>Object.hasOwn(n,r))?false:n.root===ge.root&&n.idPattern===ge.idPattern&&vo(n.include,ge.include)&&vo(n.exclude,ge.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=Ba(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=$a(n);return o?o.get("crewx_app")!==A?{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 q(t){return `sha256:${createHash("sha256").update(t,"utf8").digest("hex")}`}function gt(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 ja=10*6e4,Wa=5e3,We=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"},Xn=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){Qn(e),un(n),this.deleteExpired(n);let r=this.readWindow(e,n);return r.count<20?{available:true,remaining:20-r.count}:{available:false,retryAt:Do(r,n)}}reserve(e){return Po(e),this.sqlite.transaction(r=>{this.deleteExpired(r.now);let o=this.readWindow(r.accountKey,r.now);return o.count>=20?{ok:false,retryAt:Do(o,r.now)}:(this.insert(r),{ok:true})}).immediate(e)}reserveForced(e){Po(e),this.deleteExpired(e.now),this.insert(e);}prune(e){return un(e),this.deleteExpired(e)}readWindow(e,n){let r=this.sqlite.prepare(`
|
|
69
69
|
SELECT COUNT(*) AS count, MIN(dispatched_at) AS oldest
|
|
@@ -72,12 +72,12 @@ ${r.join(`
|
|
|
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(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-ja).changes}};function Bt(t){if(Qn(t.accountKey),xo(t.requestId),Lo(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();un(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 We(o+Wa)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function Do(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 Po(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Qn(t.accountKey),xo(t.requestId),Lo(t.source),un(t.now);}function Qn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function xo(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function Lo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function un(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var Mo=1e4,Va=12e4,pn=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||!Fo(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(Ya({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Fo(e.rootSegments,n.resolvedRootSegments))throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new h("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new h("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new h("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(!Uo(e.eligibility)||!Zn(n.status))throw new h("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new h("APP_SYNC_CONFLICT_NOT_FOUND",404);if(qo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new h("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){Ja(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new h("APP_SYNC_SESSION_STALE");let r=de(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 h("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 h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new h("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),_=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),_=this.createArchiveFenceContext(s,a,i,c);let f=this.continuationStore.listConflicts(s.bindingId);for(let g of f)try{_.fence.assertCurrent();let w=g.state==="purging"?g:this.continuationStore.markConflictPurging({conflictId:g.conflictId,fence:_.fence,now:this.now()});w.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:w.vaultHandle,fence:_.fence}),_.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:w.conflictId,expectedVaultHandle:w.vaultHandle,fence:_.fence,now:this.now()});}catch(w){if(!this.isFenceCurrent(_))throw w;let R=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:R}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:_.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),_!==u&&this.sessionFence.release(_.grantToken);}}async resolveConflict(e){Xa(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Uo(e.eligibility)||!Zn(n.status))throw new h("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new h("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new h("APP_SYNC_REVOKE_PENDING");let o=tr(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new h("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 h("APP_SYNC_CONFLICT_NOT_FOUND",404);if(qo(a,n),a.state==="purging")throw new h("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new h("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new h("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new h("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(nr(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new h("APP_SYNC_CONFLICT_STALE",409);let _=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(_,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Ue(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):Qa(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:er(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(),Va);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,A,de(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(q(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 _=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let w=await this.readRemoteDocument(o.documentId,c);if(q(w.markdown)!==o.fingerprint||w.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,w.markdown).valid)return {kind:"changed"};let R=this.dependencies.createLedger?Bt({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 h("APP_SYNC_REVOKE_PENDING")}}):void 0,T;try{T=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:A,ref:o.ref,requestId:o.requestId,markdown:w.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...R?{dispatchGate:R}:{}});}catch(E){if(E instanceof We)return {kind:"budget_deferred",retryAt:E.retryAt};throw E}if(R&&R.calls===0){let E=new h("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(b){this.dependencies.onAdapterError?.(b);}throw this.dependencies.onAdapterError?.(E),E}return c.fence.assertCurrent(),{kind:"created",created:T}}});if(c.fence.assertCurrent(),_.status==="deferred"){let w=this.now();return this.deferClaim(i,_.retryAt,w),void 0}if(_.value.kind==="budget_deferred"){let w=this.now();return this.deferClaim(i,_.value.retryAt,w),void 0}if(_.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=_.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 g=await this.readRemoteDocument(o.documentId,c);if(g.appGrantId!==n.grantId||g.appGrantGeneration!==n.generation||g.markdownVersion!==o.fingerprint||q(g.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(ft(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let _=Za(u);this.dependencies.store.updateCreation(o.jobId,{status:_?"waiting":"failed",nextAttemptAt:_?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),_&&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(!ed(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 h("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:A,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 h("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new h("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Mo)throw new h("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 h("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:A,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 h("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new h("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Mo)throw new h("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!==A||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!ln(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new h("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!X(o.docId,128)||!X(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"||!ln(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new h("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new h("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==A||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!ln(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new h("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!ln(o.deletedAt)||r.has(o.refHash))throw new h("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:A,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==A||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(ft(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:er(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:er(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,A,de(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(T=>T.accountKey===n.binding.accountKey&&T.ref===e.ref);if(r.exists){if(o.some(b=>b.state==="kept_both"&&b.localVersion===r.localVersion&&b.localFingerprint===r.localFingerprint))return "complete";let E=o.find(b=>(b.state==="open"||b.state==="resolving")&&b.preservationStatus==="ready"&&b.vaultHandle!==null&&b.localVersion===r.localVersion&&b.localFingerprint===r.localFingerprint&&b.documentId===e.docId&&b.remoteRevision===e.listedRevision&&b.remoteFingerprint===e.listedFingerprint);if(E)return E.state==="open"&&(E.grantId!==n.grant.grantId||E.grantGeneration!==n.grant.generation||E.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:E.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,_=e;if(e.needsReattach){let T=await this.queueOrConfirmReattachment(e,c,n);if(!T)return "retry";u=T.document,_=T.pending;}let f=await this.inspectLocal(e.ref,n);if(f.exists&&f.localFingerprint===u.markdownVersion){let T={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,expectedLocalFingerprint:f.localFingerprint,fence:n.fence},E=await this.applyEffect(T,n);if(E.status==="applied")return this.recordOutcome(n,e.ref,f.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(E.status==="stale_local")return this.reconcileAfterLocalRace(_,u,n);if(E.status==="conflict")return this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n);if(E.status==="deferred"||E.status==="failed")return "retry"}let g=f.baseline??s;if(!f.exists){let T={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},E=await this.applyEffect(T,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(_,u,n):E.status==="conflict"?this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!g)return this.preserveConflict(_,f,u,n);let w=f.localFingerprint!==g.markdownVersion,R=u.currentRevision!==g.revision||u.markdownVersion!==g.markdownVersion;if(w&&R)return this.preserveConflict(_,f,u,n);if(R&&!w){let T={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,fence:n.fence},E=await this.applyEffect(T,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(_,u,n):E.status==="conflict"?this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n):"retry"}return w&&!R?this.applyConditionalSave(e.ref,u.docId,f,u.currentRevision,u.markdownVersion,_.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 h("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!rr(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||q(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new h("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new h("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 h("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(),Ue(r)==="DOC_NOT_FOUND"&&Bo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:de(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)||q(e.markdown)!==e.markdownVersion||!X(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new h("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 h("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(q(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new h("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,A,de(e)))return {ok:false,reason:"deleted"};let w=await this.inspectLocal(e,a);return !w.exists||w.localVersion!==r.localVersion||w.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:w.localVersion,markdown:w.markdown,fingerprint:w.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(w){throw this.isFenceCurrent(a)&&!ft(w)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),w}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 _=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),f=await this.readRemoteById(n,_,a);if(!f)return "complete";let g=await this.inspectLocal(e,a);if(u.status==="conflict"||g.exists&&g.localFingerprint!==f.markdownVersion)return this.preserveConflict(_??nr(a,e,n,f),g,f,a);if(g.exists&&g.localFingerprint===f.markdownVersion){let w={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:f,expectedLocalVersion:g.localVersion,expectedLocalFingerprint:g.localFingerprint,fence:a.fence};return (await this.applyEffect(w,a)).status==="applied"?(this.recordOutcome(a,e,g.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 h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new h("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_${de(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(),!rr(u.handle)||u.fingerprint!==r.markdownVersion||q(r.markdown)!==u.fingerprint)throw new h("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||q(r.markdown)!==r.markdownVersion)throw new h("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 T=await this.inspectLocal(n.ref,r);return !T.exists||T.localVersion!==e.expectedLocalVersion||T.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 h("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 h("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 _=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let T={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:_},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},E;try{E=await this.applyEffect(T,r);}catch(b){throw ft(b)?b:new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(E.status==="applied")return {status:"resolved"};if(E.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(E.status==="conflict"){let b=await this.readRemoteDocument(n.documentId,r),Ie=await this.inspectLocal(n.ref,r);return {status:"stale",...Ie.exists?{refreshed:{local:Ie,remote:b}}:{}}}if(E.status==="failed"||E.status==="deferred")throw E.dispatch==="attempted"?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new h(E.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let T=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}),E={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};T.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,T,E);let b=await this.readRemoteDocument(n.documentId,r);if(b.appGrantId!==r.grant.grantId||b.appGrantGeneration!==r.grant.generation||b.currentRevision!==o.currentRevision||b.markdownVersion!==o.markdownVersion){let Ie=await this.inspectLocal(n.ref,r);if(b.currentRevision!==o.currentRevision||b.markdownVersion!==o.markdownVersion)return {status:"stale",...Ie.exists?{refreshed:{local:Ie,remote:b}}:{}};throw new h("APP_SYNC_REATTACH_PENDING")}}let g=false,w={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()=>{g=true,r.fence.assertCurrent();let T=await this.inspectLocal(n.ref,r);return !T.exists||T.localVersion!==e.expectedLocalVersion||T.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:T.localVersion,markdown:T.markdown,fingerprint:T.localFingerprint}}},R;try{R=await this.applyEffect(w,r);}catch(T){throw ft(T)?T:g?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):T}if(R.status==="applied")return {status:"resolved"};if(R.status==="conflict"){let T=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return {status:"stale",...E.exists?{refreshed:{local:E,remote:T}}:{}}}if(R.status==="stale_local"){let T=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return E.exists&&E.localFingerprint===T.markdownVersion?{status:"resolved"}:{status:"stale",...E.exists?{refreshed:{local:E,remote:T}}:{}}}if(R.status==="failed"||R.status==="deferred")throw R.dispatch==="attempted"?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new h(R.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 h("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||q(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new h("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(nr(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?tr(e):{grantId:n.grantId,appId:A,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:ge}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return tr(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:A,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:ge}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new h("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=de(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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("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===de(JSON.stringify(e.rootSegments)))return;throw new h("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||de(JSON.stringify(i.rootSegments))!==de(JSON.stringify(e.rootSegments)))throw new h("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new h("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new h("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Zn(i.status))throw new h("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new h("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 h("DOC_APP_GRANT_STALE",409);let s=de(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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||de(JSON.stringify(s.rootSegments))!==de(JSON.stringify(e.rootSegments)))throw new h("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new h("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new h(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},za=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 de(t){return createHash("sha256").update(t,"utf8").digest("hex")}function Fo(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function X(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function ln(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 rr(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 Uo(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Zn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function Ya(t){if(!t||!X(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Ja(t){if(!t||t.intent!=="device_account_data_deleted"||!X(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!X(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new h("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function Xa(t){if(!t||!t.session||!X(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!X(t.conflictId,128)||!X(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!X(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!rr(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new h("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Ue(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 Bo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function ft(t){return za.has(Ue(t))}function Qa(t){return Ue(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Ue(t)==="APP_SYNC_REATTACH_PENDING"}function er(t){let e=Ue(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function Za(t){if(ft(t))return false;let e=Bo(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(Ue(t))}function ed(t){return Ue(t)==="DOC_APP_GRANT_STALE"||Ue(t)==="DOC_APP_CURSOR_INVALID"}function tr(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new h("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:A,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:ge}}function qo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==de(JSON.stringify(e.rootSegments))||t.scopeVersion!==Qe)throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function nr(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 nd=12e4,rd=1e4,od=1e3,sd=15*6e4,id=4,or=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Ht=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),sr=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),_n=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),ad=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),h=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},dr=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 qt,this.sessionFence=e.sessionFence??new Ut,this.now=e.now??Date.now,this.createId=e.createId??randomUUID,this.continuationRuntime=e.continuation?new pn(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 ur(id);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=gt(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:A,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 g=this.dependencies.store.getBinding(e);return g&&await this.holdPendingRevoke(g),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),_=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),f=this.limitCreationClaims(s.accountKey,_);if(await Promise.all([...u.filter(g=>!this.continuationRuntime&&this.shouldReconcile(g,a)).map(g=>this.reconcileExisting(s,a,c,g)),...f.map(g=>this.dispatchCreation(s,a,i,g,n))]),this.hasPendingRevoke(e)){let g=this.dependencies.store.getBinding(e);return g&&await this.holdPendingRevoke(g),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 Bt({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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("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 h("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 _=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||_!==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:A,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&&!cd(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!==A||!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:cr(),results:[]};let r=this.dependencies.store.listResults(e),o=Ho(r,this.dependencies.store.countDeletedRefs(n.accountKey,A));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:A,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 _=ht(u);return ir(u)&&!Ht.has(_)&&!or.has(_)?await this.pauseAuthentication(r):Ht.has(_)||ud(u)?await this.pauseUnavailableBinding(r,_==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):sr.has(_)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):ar(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!==A||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!==A||!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 _=new Set(u.map(f=>f.ref));for(let f of this.dependencies.store.listResults(e))!_.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,g)=>f.ref.localeCompare(g.ref));for(let[f,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 w=createHash("sha256").update(g.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,A,w)){let Se=this.dependencies.store.getResult(e,g.ref);this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:Se?.syncedFingerprint??null,documentId:Se?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let R=this.dependencies.store.getResult(e,g.ref);if(f>=500){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let T=await this.readEligibleFile(r,g.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(T.status==="unsafe"||T.status==="missing"){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"excluded",errorCode:T.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(T.status==="read_error"){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let E=this.scopeRegistry.validateFrontMatter(g.ref,T.markdown),b=q(T.markdown);if(!E.valid){this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(R?.status==="conflict"&&R.grantGeneration===a.generation)continue;if(R?.documentId&&R.grantGeneration===a.generation){if(R.status==="synced"&&R.syncedFingerprint===b)continue;let Se=R?.sourceFingerprint===b;this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R.syncedFingerprint,documentId:R.documentId,status:Se?R.status:"waiting",errorCode:Se?R.errorCode:null,nextAttemptAt:Se?R.nextAttemptAt:0});continue}if(R?.status==="failed"&&R.grantGeneration===a.generation&&R.sourceFingerprint===b&&!_n.has(R.errorCode??"")||R?.status==="blocked"&&R.errorCode!=="APP_LOCAL_QUOTA"&&R.grantGeneration===a.generation&&R.sourceFingerprint===b)continue;let Ie=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:g.ref,fingerprint:b,now:this.now()}),v=R?.sourceFingerprint===b,be=R?.status==="failed"&&_n.has(R.errorCode??"");this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:Ie.status==="completed"?"processing":"waiting",errorCode:v&&!be?R.errorCode:null,nextAttemptAt:v&&!be?R.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<rd;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Jn,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=ht(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,A,qe(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,A,qe(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:q(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(),nd);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,A,qe(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:q(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(q(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 g=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let v=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new h("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,A,qe(i.ref)))return {kind:"deleted"};if(v.status!=="ok")return {kind:"local_file",status:v.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,v.markdown).valid)return {kind:"out_of_scope"};let be=q(v.markdown);if(be!==i.fingerprint)return {kind:"source_changed",fingerprint:be};let Se=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),No;try{No=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:A,ref:i.ref,requestId:i.requestId,markdown:v.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...Se?{dispatchGate:Se}:{}});}catch(Kn){if(Kn instanceof We)return {kind:"budget_deferred",retryAt:Kn.retryAt};throw Kn}if(Se&&Se.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:No}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(g.status==="deferred"){let v=this.now();if(!this.deferClaim(i,g.retryAt,v))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:g.retryAt});return}if(g.value.kind==="budget_deferred"){let v=this.now();if(!this.deferClaim(i,g.value.retryAt,v))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:g.value.retryAt});return}if(g.value.kind!=="created"){let v=g.value;if(v.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(v.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(v.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:v.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 be=v.kind==="local_file"?v.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:be==="read_error"?"failed":"excluded",errorCode:v.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":be==="unsafe"?"APP_FILE_UNSAFE":be==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:be==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let w=g.value.result;if(w.appGrantId!==n.grantId||w.appGrantGeneration!==n.generation)throw new h("DOC_APP_GRANT_STALE",409);let R=await this.readRemoteDocument({accountKey:i.accountKey,docId:w.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(R,w,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,w.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 T=q(R.markdown),E,b=i.fingerprint;if(!w.replayed&&!w.reattached&&T===i.fingerprint&&R.markdownVersion===i.fingerprint)E=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:R,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let v;if(E=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:R,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(v=await this.beforeDocumentDispatch(e,n,a,i.ref),v)}),!v&&E.dispatch!=="none")throw new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(E.dispatch==="attempted"&&!v)throw new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(v&&!v.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,v,i);return}v?.ok&&E.dispatch!=="none"&&(b=v.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Ie=this.recordOutcome(e,n,i.ref,b,c,w.docId,E);this.dependencies.store.updateCreation(i.jobId,{status:Ie==="conflict"?"conflict":Ie==="failed"?"failed":E.status==="failed"&&E.retryAt!==void 0?"waiting":"completed",nextAttemptAt:E.status==="failed"&&E.retryAt!==void 0?this.retryAt(i.attempts+1,E.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:q(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=q(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,A,qe(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(_){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,_);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||q(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 _,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()=>(_=await this.beforeDocumentDispatch(e,n,r,o.ref),_)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!_&&f.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(f.dispatch==="attempted"&&!_){await this.handleExistingError(e,n,o,a,new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(_&&!_.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,_);return}let g=_?.ok&&f.dispatch!=="none"?_.fingerprint:a;this.recordOutcome(e,n,o.ref,g,o,o.documentId,f);}catch(_){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,_);}}}async handleCreationError(e,n,r,o,s){let i=ht(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(Ht.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(sr.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(or.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(ir(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,$o(s,this.now())),c=ar(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=ht(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,A,qe(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(sr.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(Ht.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(or.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(ir(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=ar(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,$o(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,A,qe(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,_=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(_,a.retryAt):0,attempts:_}),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,A,qe(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=gt(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!dd(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:qe(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"&&_n.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&&q(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:A,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:ge}}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:cr(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Ho(r,this.dependencies.store.countDeletedRefs(n.accountKey,A)),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(od*2**r,sd)}};function cr(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Ho(t,e){let n=cr(),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 dd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function cd(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===A}function qe(t){return createHash("sha256").update(t,"utf8").digest("hex")}function ht(t){return t instanceof h||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function $o(t,e){if(t instanceof h&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function lr(t){return t instanceof h||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function ir(t){let e=ht(t);if(Ht.has(e))return false;let n=lr(t);return _n.has(e)||n===401||n===403}function ud(t){let e=lr(t);return e!==void 0&&e>=400&&e<500}function ar(t){let e=lr(t);return e!==void 0?e===408||e===425||e===429||e>=500:ad.has(ht(t))}var ur=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();x();d();x();M();d();x();F();B();M();U();Cr();d();x();F();B();M();U();d();Ur();d();x();F();B();M();d();U();var qr=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(qr);F();B();d();B();U();U();U();U();xt();xt();wo();dn();pt();xt();xt();At();d();x();d();var Ra=["success","failed","completed"];new Set(Ra);Dn();xt();ko();Ln();var hp=[{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",...hp.map(t=>t.field)];Dn();d();x();F();B();M();U();At();pt();d();d();Zt();d();x();F();B();M();U();d();x();F();B();M();U();d();var Ea=["urgent","high","medium","low"],Ta=["investigating","in-progress","in-review","on-hold","done"];new Set(Ea);new Set(Ta);pt();new Set(Us);new Set(Fs);new Set(qs);new Set(Bs);new Set(Hs);d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();F();x();M();B();pt();U();d();x();d();x();F();M();M();d();x();F();M();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();pt();At();Hr();Tt.map(t=>`'${t}'`).join(", ");var bo=class extends P{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=L(n),this.sqlite=this.handle.sqlite,H(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!==A)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=gt(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||!va(r.rootSegments,n))throw new Error("APP_SYNC_ROOT_ALREADY_BOUND");return r}try{this.sqlite.prepare(`
|
|
75
|
+
`).run(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-ja).changes}};function Bt(t){if(Qn(t.accountKey),xo(t.requestId),Lo(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();un(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 We(o+Wa)}});return Object.defineProperty(n,"calls",{enumerable:true,get:()=>e}),n}function Do(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 Po(t){if(!t||typeof t!="object")throw new Error("INVALID_DOC_CREATE_DISPATCH_INPUT");Qn(t.accountKey),xo(t.requestId),Lo(t.source),un(t.now);}function Qn(t){if(typeof t!="string"||!/^[0-9a-f]{64}$/.test(t))throw new Error("INVALID_DOC_CREATE_LEDGER_ACCOUNT_KEY")}function xo(t){if(typeof t!="string"||t.length<1||t.length>128)throw new Error("INVALID_DOC_CREATE_LEDGER_REQUEST_ID")}function Lo(t){if(t!=="human"&&t!=="app_create"&&t!=="app_reattach")throw new Error("INVALID_DOC_CREATE_LEDGER_SOURCE")}function un(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("INVALID_DOC_CREATE_LEDGER_TIME")}var Mo=1e4,Va=12e4,pn=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||!Fo(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(Ya({bindingId:n.bindingId,session:n.session,workspaceId:n.workspaceId,resolvedRootSegments:n.resolvedRootSegments}),!n.session?.authenticated||n.session.accountKey!==e.accountKey||n.workspaceId!==e.workspaceId||!Fo(e.rootSegments,n.resolvedRootSegments))throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}requireCurrentSession(e,n){if(!Number.isSafeInteger(n)||n<1)throw new h("APP_SYNC_SESSION_STALE");let r=this.sessionFence.currentToken(e.accountKey);if(!r||this.sessionFence.activeAccountKey!==e.accountKey||r.epoch!==n)throw new h("APP_SYNC_SESSION_STALE");return r}requireHumanOperationBinding(e){let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new h("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(!Uo(e.eligibility)||!Zn(n.status))throw new h("DOC_APP_GRANT_REQUIRED",409);let o=this.continuationStore.getConflict(e.conflictId);if(!o)throw new h("APP_SYNC_CONFLICT_NOT_FOUND",404);if(qo(o,n),o.preservationStatus!=="ready"||!o.vaultHandle||o.state==="purging")throw new h("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){Ja(e);let n=this.sessionFence.currentToken(e.session.accountKey);if(!n||n.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==e.session.accountKey)throw new h("APP_SYNC_SESSION_STALE");let r=de(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 h("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 h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}this.assertHumanBindingIdentity(s,e);let i=this.requireCurrentSession(s,e.expectedSessionEpoch);if(this.hasPendingRevoke(s.bindingId))throw new h("APP_SYNC_REVOKE_PENDING",409);let a=this.purgeFenceGrant(s),c={allowNonTransferStatus:true,purgeRequestId:e.requestId},u=this.createArchiveFenceContext(s,a,i,c),_=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),_=this.createArchiveFenceContext(s,a,i,c);let f=this.continuationStore.listConflicts(s.bindingId);for(let g of f)try{_.fence.assertCurrent();let w=g.state==="purging"?g:this.continuationStore.markConflictPurging({conflictId:g.conflictId,fence:_.fence,now:this.now()});w.vaultHandle&&(await this.continuation.conflictVault.remove({accountKey:s.accountKey,handle:w.vaultHandle,fence:_.fence}),_.fence.assertCurrent()),this.continuationStore.deletePurgedConflict({conflictId:w.conflictId,expectedVaultHandle:w.vaultHandle,fence:_.fence,now:this.now()});}catch(w){if(!this.isFenceCurrent(_))throw w;let R=this.continuationStore.listConflicts(s.bindingId).length;return {requestId:e.requestId,status:"cleanup_pending",remainingArchiveCount:R}}return this.continuationStore.finishAccountDataPurge({requestId:e.requestId,binding:s,fence:_.fence,now:this.now()}),{requestId:e.requestId,status:"purged",remainingArchiveCount:0}}finally{this.sessionFence.release(u.grantToken),_!==u&&this.sessionFence.release(_.grantToken);}}async resolveConflict(e){Xa(e);let n=this.dependencies.store.getBinding(e.bindingId);if(!n)throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH");this.assertHumanBindingIdentity(n,e);let r=this.requireCurrentSession(n,e.expectedSessionEpoch);if(!Uo(e.eligibility)||!Zn(n.status))throw new h("DOC_APP_GRANT_REQUIRED",409);if(!n.grantId||!n.grantGeneration||!n.scopeVersion||n.status==="revoked"||n.status==="stopping"||n.status==="unavailable")throw new h("DOC_APP_GRANT_REQUIRED",409);if(this.hasPendingRevoke(n.bindingId))throw new h("APP_SYNC_REVOKE_PENDING");let o=tr(n);if(r.epoch!==e.expectedSessionEpoch||this.sessionFence.activeAccountKey!==n.accountKey)throw new h("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 h("APP_SYNC_CONFLICT_NOT_FOUND",404);if(qo(a,n),a.state==="purging")throw new h("APP_SYNC_CONFLICT_PURGING",409);if(!(a.state==="superseded"&&e.choice==="keep_both")&&!await this.readActiveGrant(i))throw new h("DOC_APP_GRANT_STALE",409);if(a.state==="resolved"||a.state==="kept_both"){if(a.resolutionRequestId!==e.requestId||a.resolutionChoice!==e.choice)throw new h("APP_SYNC_CONFLICT_ALREADY_RESOLVED",409);return this.cleanupResolvedConflict(a,i)}if(a.preservationStatus!=="ready"||!a.vaultHandle)throw new h("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(nr(i,a.ref,u.refreshed.remote.docId,u.refreshed.remote),u.refreshed.local,u.refreshed.remote,i):await this.refreshConflictAfterStale(a,i),new h("APP_SYNC_CONFLICT_STALE",409);let _=this.continuationStore.finishConflictResolution({conflictId:a.conflictId,requestId:e.requestId,choice:e.choice,fence:i.fence,now:this.now()});return this.cleanupResolvedConflict(_,i)}catch(a){if(this.isFenceCurrent(i)){let c=this.continuationStore.getConflict(e.conflictId);c?.state==="resolving"&&c.resolutionRequestId===e.requestId&&(Ue(a)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"?this.continuationStore.markConflictResolutionUnknown({conflictId:e.conflictId,requestId:e.requestId,fence:i.fence,now:this.now()}):Qa(a)||this.continuationStore.abortConflictResolution({conflictId:e.conflictId,requestId:e.requestId,state:"failed",errorCode:er(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(),Va);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,A,de(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(q(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 _=await this.dependencies.creationBudget.runCreate({accountKey:e.accountKey,signal:a.signal,dispatch:async()=>{c.fence.assertCurrent();let w=await this.readRemoteDocument(o.documentId,c);if(q(w.markdown)!==o.fingerprint||w.markdownVersion!==o.fingerprint||!this.scopeRegistry.validateFrontMatter(o.ref,w.markdown).valid)return {kind:"changed"};let R=this.dependencies.createLedger?Bt({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 h("APP_SYNC_REVOKE_PENDING")}}):void 0,T;try{T=await this.dependencies.remote.createGrantedDocument({accountKey:e.accountKey,appId:A,ref:o.ref,requestId:o.requestId,markdown:w.markdown,appVersion:s.appVersion,appGrant:{grantId:n.grantId,generation:n.generation},signal:a.signal,fence:c.fence,...R?{dispatchGate:R}:{}});}catch(E){if(E instanceof We)return {kind:"budget_deferred",retryAt:E.retryAt};throw E}if(R&&R.calls===0){let E=new h("APP_SYNC_DISPATCH_GATE_NOT_CALLED");try{this.dependencies.createLedger.reserveForced({accountKey:e.accountKey,requestId:o.requestId,source:"app_reattach",now:this.now()});}catch(b){this.dependencies.onAdapterError?.(b);}throw this.dependencies.onAdapterError?.(E),E}return c.fence.assertCurrent(),{kind:"created",created:T}}});if(c.fence.assertCurrent(),_.status==="deferred"){let w=this.now();return this.deferClaim(i,_.retryAt,w),void 0}if(_.value.kind==="budget_deferred"){let w=this.now();return this.deferClaim(i,_.value.retryAt,w),void 0}if(_.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=_.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 g=await this.readRemoteDocument(o.documentId,c);if(g.appGrantId!==n.grantId||g.appGrantGeneration!==n.generation||g.markdownVersion!==o.fingerprint||q(g.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(ft(u)){this.dependencies.store.updateCreation(o.jobId,{status:"waiting",nextAttemptAt:this.now()+6e4,now:this.now()});return}let _=Za(u);this.dependencies.store.updateCreation(o.jobId,{status:_?"waiting":"failed",nextAttemptAt:_?this.now()+Math.min(1e3*2**Math.min(i.attempts,10),3e5):0,now:this.now()}),_&&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(!ed(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 h("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:A,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 h("APP_SYNC_DOCS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new h("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Mo)throw new h("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 h("DOC_APP_CURSOR_INVALID",400);r.add(i);}let a=await n.call(this.dependencies.remote,{accountKey:e.binding.accountKey,appId:A,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 h("APP_SYNC_DELETED_REFS_PAGE_INVALID");if(a.nextCursor!==null&&r.has(a.nextCursor))throw new h("DOC_APP_CURSOR_INVALID",400);if(o+=1,o>Mo)throw new h("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!==A||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||e.scopeVersion!==n.grant.scopeVersion||!ln(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new h("APP_SYNC_DOCS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!X(o.docId,128)||!X(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"||!ln(o.updatedAt)||!this.scopeRegistry.validateRef(o.ref).valid||r.has(o.ref))throw new h("APP_SYNC_DOCS_PAGE_INVALID");if(!o.needsReattach&&o.appGrantGeneration!==n.grant.generation)throw new h("APP_SYNC_DOCS_PAGE_INVALID");r.add(o.ref);}}validateDeletedRefsPage(e,n){if(!e||e.appId!==A||e.grantId!==n.grant.grantId||e.generation!==n.grant.generation||!ln(e.listedAt)||!Array.isArray(e.items)||!(e.nextCursor===null||typeof e.nextCursor=="string"&&e.nextCursor.length<=512))throw new h("APP_SYNC_DELETED_REFS_PAGE_INVALID");let r=new Set;for(let o of e.items){if(!/^[0-9a-f]{64}$/.test(o.refHash)||!ln(o.deletedAt)||r.has(o.refHash))throw new h("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:A,signal:e.fence.signal,fence:e.fence});return e.fence.assertCurrent(),n.appId!==A||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(ft(o)){this.continuationStore.updatePendingDiscovery({bindingId:r.bindingId,grantId:r.grantId,generation:r.grantGeneration,ref:r.ref,fence:e.fence,patch:{status:"waiting",errorCode:er(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:er(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,A,de(e.ref)))return "complete";let r=await this.inspectLocal(e.ref,n),o=this.continuationStore.listConflicts(n.binding.bindingId).filter(T=>T.accountKey===n.binding.accountKey&&T.ref===e.ref);if(r.exists){if(o.some(b=>b.state==="kept_both"&&b.localVersion===r.localVersion&&b.localFingerprint===r.localFingerprint))return "complete";let E=o.find(b=>(b.state==="open"||b.state==="resolving")&&b.preservationStatus==="ready"&&b.vaultHandle!==null&&b.localVersion===r.localVersion&&b.localFingerprint===r.localFingerprint&&b.documentId===e.docId&&b.remoteRevision===e.listedRevision&&b.remoteFingerprint===e.listedFingerprint);if(E)return E.state==="open"&&(E.grantId!==n.grant.grantId||E.grantGeneration!==n.grant.generation||E.needsReattach!==e.needsReattach)&&this.continuationStore.rebindConflict({conflictId:E.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,_=e;if(e.needsReattach){let T=await this.queueOrConfirmReattachment(e,c,n);if(!T)return "retry";u=T.document,_=T.pending;}let f=await this.inspectLocal(e.ref,n);if(f.exists&&f.localFingerprint===u.markdownVersion){let T={kind:"attach_equal",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,expectedLocalFingerprint:f.localFingerprint,fence:n.fence},E=await this.applyEffect(T,n);if(E.status==="applied")return this.recordOutcome(n,e.ref,f.localFingerprint,u.markdownVersion,u.docId,"synced",null),"complete";if(E.status==="stale_local")return this.reconcileAfterLocalRace(_,u,n);if(E.status==="conflict")return this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n);if(E.status==="deferred"||E.status==="failed")return "retry"}let g=f.baseline??s;if(!f.exists){let T={kind:"create_absent",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:null,fence:n.fence},E=await this.applyEffect(T,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(_,u,n):E.status==="conflict"?this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n):"retry"}if(!g)return this.preserveConflict(_,f,u,n);let w=f.localFingerprint!==g.markdownVersion,R=u.currentRevision!==g.revision||u.markdownVersion!==g.markdownVersion;if(w&&R)return this.preserveConflict(_,f,u,n);if(R&&!w){let T={kind:"cas_pull",binding:n.binding,grant:n.grant,ref:e.ref,document:u,expectedLocalVersion:f.localVersion,fence:n.fence},E=await this.applyEffect(T,n);return E.status==="applied"?(this.recordOutcome(n,e.ref,u.markdownVersion,u.markdownVersion,u.docId,"synced",null),"complete"):E.status==="stale_local"?this.reconcileAfterLocalRace(_,u,n):E.status==="conflict"?this.preserveConflict(_,await this.inspectLocal(e.ref,n),u,n):"retry"}return w&&!R?this.applyConditionalSave(e.ref,u.docId,f,u.currentRevision,u.markdownVersion,_.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 h("APP_SYNC_LOCAL_INSPECTION_INVALID");if(o.exists){if(!rr(o.localVersion)||!/^sha256:[0-9a-f]{64}$/.test(o.localFingerprint)||q(o.markdown)!==o.localFingerprint||!this.scopeRegistry.validateFrontMatter(e,o.markdown).valid)throw new h("APP_SYNC_LOCAL_STATE_INVALID")}else if(o.localVersion!==null||o.localFingerprint!==null||o.markdown!==null)throw new h("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 h("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(),Ue(r)==="DOC_NOT_FOUND"&&Bo(r)===404)return this.continuationStore.recordKnownDeletion({binding:n.binding,grant:n.grant,ref:e.ref,refHash:de(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)||q(e.markdown)!==e.markdownVersion||!X(e.appGrantId,128)||!Number.isSafeInteger(e.appGrantGeneration)||e.appGrantGeneration<1||!this.scopeRegistry.validateFrontMatter(n.ref,e.markdown).valid)throw new h("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 h("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(q(s.markdown)!==s.markdownVersion||!this.scopeRegistry.validateFrontMatter(e.ref,s.markdown).valid)throw new h("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,A,de(e)))return {ok:false,reason:"deleted"};let w=await this.inspectLocal(e,a);return !w.exists||w.localVersion!==r.localVersion||w.localFingerprint!==r.localFingerprint?{ok:false,reason:"stale"}:(a.fence.assertCurrent(),{ok:true,localVersion:w.localVersion,markdown:w.markdown,fingerprint:w.localFingerprint})}},u;try{u=await this.applyEffect(c,a);}catch(w){throw this.isFenceCurrent(a)&&!ft(w)&&this.markPendingForReconcile(a.binding,a.grant,e,a,"APP_SYNC_SAVE_RESPONSE_UNKNOWN"),w}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 _=this.continuationStore.getPendingDiscovery(a.binding.bindingId,a.grant.grantId,a.grant.generation,e),f=await this.readRemoteById(n,_,a);if(!f)return "complete";let g=await this.inspectLocal(e,a);if(u.status==="conflict"||g.exists&&g.localFingerprint!==f.markdownVersion)return this.preserveConflict(_??nr(a,e,n,f),g,f,a);if(g.exists&&g.localFingerprint===f.markdownVersion){let w={kind:"attach_equal",binding:a.binding,grant:a.grant,ref:e,document:f,expectedLocalVersion:g.localVersion,expectedLocalFingerprint:g.localFingerprint,fence:a.fence};return (await this.applyEffect(w,a)).status==="applied"?(this.recordOutcome(a,e,g.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 h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if((s.status==="applied"||s.status==="conflict")&&s.dispatch!=="attempted")throw new h("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_${de(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(),!rr(u.handle)||u.fingerprint!==r.markdownVersion||q(r.markdown)!==u.fingerprint)throw new h("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||q(r.markdown)!==r.markdownVersion)throw new h("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 T=await this.inspectLocal(n.ref,r);return !T.exists||T.localVersion!==e.expectedLocalVersion||T.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 h("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 h("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 _=await this.readVerifiedArchive(n,r);if(e.choice==="keep_both")return {status:"resolved"};if(e.choice==="use_cloud"){let T={kind:"cas_pull",binding:r.binding,grant:r.grant,ref:n.ref,document:{...o,markdown:_},expectedLocalVersion:e.expectedLocalVersion,fence:r.fence},E;try{E=await this.applyEffect(T,r);}catch(b){throw ft(b)?b:new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN")}if(E.status==="applied")return {status:"resolved"};if(E.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(E.status==="conflict"){let b=await this.readRemoteDocument(n.documentId,r),Ie=await this.inspectLocal(n.ref,r);return {status:"stale",...Ie.exists?{refreshed:{local:Ie,remote:b}}:{}}}if(E.status==="failed"||E.status==="deferred")throw E.dispatch==="attempted"?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new h(E.errorCode??"APP_SYNC_CONFLICT_RESOLUTION_FAILED");return {status:"stale",refreshed:{local:i,remote:o}}}if(n.needsReattach||!s){let T=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}),E={session:e.session,eligibility:e.eligibility,appVersion:e.appVersion};T.status!=="completed"&&await this.dispatchReattachCreation(r.binding,r.grant,r.session,T,E);let b=await this.readRemoteDocument(n.documentId,r);if(b.appGrantId!==r.grant.grantId||b.appGrantGeneration!==r.grant.generation||b.currentRevision!==o.currentRevision||b.markdownVersion!==o.markdownVersion){let Ie=await this.inspectLocal(n.ref,r);if(b.currentRevision!==o.currentRevision||b.markdownVersion!==o.markdownVersion)return {status:"stale",...Ie.exists?{refreshed:{local:Ie,remote:b}}:{}};throw new h("APP_SYNC_REATTACH_PENDING")}}let g=false,w={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()=>{g=true,r.fence.assertCurrent();let T=await this.inspectLocal(n.ref,r);return !T.exists||T.localVersion!==e.expectedLocalVersion||T.localFingerprint!==n.localFingerprint?{ok:false,reason:"stale"}:{ok:true,localVersion:T.localVersion,markdown:T.markdown,fingerprint:T.localFingerprint}}},R;try{R=await this.applyEffect(w,r);}catch(T){throw ft(T)?T:g?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):T}if(R.status==="applied")return {status:"resolved"};if(R.status==="conflict"){let T=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return {status:"stale",...E.exists?{refreshed:{local:E,remote:T}}:{}}}if(R.status==="stale_local"){let T=await this.readRemoteDocument(n.documentId,r),E=await this.inspectLocal(n.ref,r);return E.exists&&E.localFingerprint===T.markdownVersion?{status:"resolved"}:{status:"stale",...E.exists?{refreshed:{local:E,remote:T}}:{}}}if(R.status==="failed"||R.status==="deferred")throw R.dispatch==="attempted"?new h("APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"):new h(R.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 h("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||q(r.markdown)!==e.remoteFingerprint||!this.scopeRegistry.validateFrontMatter(e.ref,r.markdown).valid)throw new h("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(nr(n,e.ref,o.docId,o),r,o,n));}archiveFenceGrant(e,n){return e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion?tr(e):{grantId:n.grantId,appId:A,generation:n.grantGeneration,scopeVersion:n.scopeVersion,scope:ge}}purgeFenceGrant(e){if(e.grantId&&e.grantGeneration&&e.scopeVersion===this.scopeRegistry.scopeVersion)return tr(e);let n=this.continuationStore.listConflicts(e.bindingId)[0];return {grantId:n?.grantId??"account-data-purge",appId:A,generation:n?.grantGeneration??1,scopeVersion:this.scopeRegistry.scopeVersion,scope:ge}}createArchiveFenceContext(e,n,r,o={}){if(n.scopeVersion!==this.scopeRegistry.scopeVersion||!this.sessionFence.isCurrent(r)||r.accountKey!==e.accountKey)throw new h("APP_SYNC_SESSION_STALE");let s=this.sessionFence.captureGrant(r,n.grantId,n.generation),i=de(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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("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===de(JSON.stringify(e.rootSegments)))return;throw new h("APP_SYNC_ROOT_STALE")}if(i.accountKey!==e.accountKey||i.workspaceId!==e.workspaceId||de(JSON.stringify(i.rootSegments))!==de(JSON.stringify(e.rootSegments)))throw new h("APP_SYNC_ROOT_STALE");if(i.grantId!==e.grantId||i.grantGeneration!==e.grantGeneration||i.scopeVersion!==e.scopeVersion)throw new h("DOC_APP_GRANT_STALE",409);if(i.status==="stopping")throw new h("APP_SYNC_REVOKE_PENDING",409);if(!s.allowNonTransferStatus&&!Zn(i.status))throw new h("DOC_APP_GRANT_REQUIRED",409);if(i.grantId&&(i.grantId!==n.grantId||i.grantGeneration!==n.generation||i.scopeVersion!==n.scopeVersion))throw new h("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 h("DOC_APP_GRANT_STALE",409);let s=de(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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("APP_SYNC_REVOKE_PENDING");let s=this.dependencies.store.getBinding(e.bindingId);if(!s||s.accountKey!==e.accountKey||s.workspaceId!==e.workspaceId||de(JSON.stringify(s.rootSegments))!==de(JSON.stringify(e.rootSegments)))throw new h("APP_SYNC_ROOT_STALE");if(s.grantId!==n.grantId||s.grantGeneration!==n.generation||s.scopeVersion!==n.scopeVersion)throw new h("DOC_APP_GRANT_STALE",409);if(s.status==="revoked"||s.status==="stopping"||s.status==="unavailable")throw new h(s.status==="stopping"?"APP_SYNC_REVOKE_PENDING":"DOC_APP_GRANT_REQUIRED",409)}isFenceCurrent(e){try{return e.fence.assertCurrent(),!0}catch{return false}}},za=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 de(t){return createHash("sha256").update(t,"utf8").digest("hex")}function Fo(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function X(t,e){return typeof t=="string"&&t.length>0&&t.length<=e&&!t.includes("\0")}function ln(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 rr(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 Uo(t){return t?.featureEnabled===true&&t.ownerAllowlisted===true}function Zn(t){return t==="checking"||t==="syncing"||t==="synced"||t==="partial"}function Ya(t){if(!t||!X(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\")))throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function Ja(t){if(!t||t.intent!=="device_account_data_deleted"||!X(t.bindingId,128)||!t.session?.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.length<1||t.resolvedRootSegments.length>32||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!X(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity))throw new h("APP_SYNC_ACCOUNT_DATA_PURGE_INPUT_INVALID",400)}function Xa(t){if(!t||!t.session||!X(t.bindingId,128)||!t.session.authenticated||!t.session.accountKey||!/^[0-9a-f]{64}$/.test(t.session.accountKey)||!X(t.workspaceId,256)||!Array.isArray(t.resolvedRootSegments)||t.resolvedRootSegments.some(e=>!X(e,128)||e==="."||e===".."||e.includes("/")||e.includes("\\"))||!X(t.conflictId,128)||!X(t.requestId,128)||!/^[0-9a-f]{64}$/.test(t.humanIdentity)||!X(t.appVersion,128)||!Number.isSafeInteger(t.expectedSessionEpoch)||t.expectedSessionEpoch<1||!["keep_local","use_cloud","keep_both"].includes(t.choice)||!rr(t.expectedLocalVersion)||!Number.isSafeInteger(t.expectedRemoteRevision)||t.expectedRemoteRevision<0||!/^sha256:[0-9a-f]{64}$/.test(t.expectedRemoteFingerprint))throw new h("APP_SYNC_CONFLICT_RESOLUTION_INPUT_INVALID",400)}function Ue(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 Bo(t){if(t&&typeof t=="object"&&"status"in t&&typeof t.status=="number")return t.status}function ft(t){return za.has(Ue(t))}function Qa(t){return Ue(t)==="APP_SYNC_CONFLICT_RESOLUTION_UNKNOWN"||Ue(t)==="APP_SYNC_REATTACH_PENDING"}function er(t){let e=Ue(t);return /^[A-Z0-9_:-]{1,128}$/.test(e)?e:"APP_SYNC_OPERATION_FAILED"}function Za(t){if(ft(t))return false;let e=Bo(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(Ue(t))}function ed(t){return Ue(t)==="DOC_APP_GRANT_STALE"||Ue(t)==="DOC_APP_CURSOR_INVALID"}function tr(t){if(!t.grantId||!t.grantGeneration||!t.scopeVersion)throw new h("DOC_APP_GRANT_REQUIRED",409);return {grantId:t.grantId,appId:A,generation:t.grantGeneration,scopeVersion:t.scopeVersion,scope:ge}}function qo(t,e){if(t.bindingId!==e.bindingId||t.accountKey!==e.accountKey||t.workspaceId!==e.workspaceId||t.rootFingerprint!==de(JSON.stringify(e.rootSegments))||t.scopeVersion!==Qe)throw new h("APP_SYNC_CONFLICT_BINDING_MISMATCH",404)}function nr(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 nd=12e4,rd=1e4,od=1e3,sd=15*6e4,id=4,or=new Set(["DOC_STORAGE_LIMIT_REACHED","DOC_SYNC_LIMIT","DOC_PILOT_NOT_ALLOWED"]),Ht=new Set(["DOC_APP_GRANT_NOT_AVAILABLE","DOC_APP_SCOPE_INVALID","DOC_APP_GRANT_SCOPE_MISMATCH"]),sr=new Set(["DOC_APP_GRANT_REQUIRED","DOC_APP_GRANT_STALE"]),_n=new Set(["AUTH_REQUIRED","UNAUTHENTICATED","DOC_SCOPE_REQUIRED","TOKEN_EXPIRED"]),ad=new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]),h=class extends Error{constructor(n,r,o){super(n);this.code=n;this.status=r;this.retryAfterMs=o;this.name="AppSyncRemoteError";}code;status;retryAfterMs},dr=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 qt,this.sessionFence=e.sessionFence??new Ut,this.now=e.now??Date.now,this.createId=e.createId??randomUUID,this.continuationRuntime=e.continuation?new pn(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 ur(id);continuationRuntime;scanEpoch=0;get activeSessionEpoch(){return this.sessionFence.activeSessionEpoch}async bind(e){let n=this.requireAuthenticatedAccount(e.session),r=gt(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:A,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 g=this.dependencies.store.getBinding(e);return g&&await this.holdPendingRevoke(g),this.snapshot(e)}if(!this.isCurrent(i)||!this.isCurrent(c))return this.snapshot(e);let u=this.dependencies.store.listResults(e),_=this.dependencies.store.listRunnableCreations(e,a.grantId,a.generation,this.now()),f=this.limitCreationClaims(s.accountKey,_);if(await Promise.all([...u.filter(g=>!this.continuationRuntime&&this.shouldReconcile(g,a)).map(g=>this.reconcileExisting(s,a,c,g)),...f.map(g=>this.dispatchCreation(s,a,i,g,n))]),this.hasPendingRevoke(e)){let g=this.dependencies.store.getBinding(e);return g&&await this.holdPendingRevoke(g),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 Bt({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 h("APP_SYNC_SESSION_STALE");if(this.hasPendingRevoke(e.bindingId))throw new h("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 h("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 _=this.dependencies.store.getConfirmedRevoke(n.bindingId,n.grantId,n.grantGeneration);if(!(n.status==="revoked"||_!==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:A,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&&!cd(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!==A||!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:cr(),results:[]};let r=this.dependencies.store.listResults(e),o=Ho(r,this.dependencies.store.countDeletedRefs(n.accountKey,A));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:A,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 _=ht(u);return ir(u)&&!Ht.has(_)&&!or.has(_)?await this.pauseAuthentication(r):Ht.has(_)||ud(u)?await this.pauseUnavailableBinding(r,_==="DOC_APP_GRANT_NOT_AVAILABLE"?"ineligible":"scope_mismatch"):sr.has(_)?(r.grantId&&r.grantGeneration&&await this.invalidateStoredGeneration(r,"revoked"),this.dependencies.store.updateBinding(e,{status:"revoked"},this.now())):ar(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!==A||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!==A||!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 _=new Set(u.map(f=>f.ref));for(let f of this.dependencies.store.listResults(e))!_.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,g)=>f.ref.localeCompare(g.ref));for(let[f,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 w=createHash("sha256").update(g.ref,"utf8").digest("hex");if(this.dependencies.store.hasDeletedRef(r.accountKey,A,w)){let Se=this.dependencies.store.getResult(e,g.ref);this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:Se?.syncedFingerprint??null,documentId:Se?.documentId??null,status:"deleted",errorCode:"DOC_APP_REF_DELETED"});continue}let R=this.dependencies.store.getResult(e,g.ref);if(f>=500){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"blocked",errorCode:"APP_LOCAL_QUOTA"});continue}let T=await this.readEligibleFile(r,g.ref,s.signal);if(this.hasPendingRevoke(e))return await this.holdPendingRevoke(r),this.snapshot(e);if(!this.isCurrent(s))return this.snapshot(e);if(T.status==="unsafe"||T.status==="missing"){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"excluded",errorCode:T.status==="unsafe"?"APP_FILE_UNSAFE":"APP_FILE_MISSING"});continue}if(T.status==="read_error"){this.writeResult(r,a,g.ref,{sourceFingerprint:null,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"failed",errorCode:"APP_FILE_READ_FAILED"});continue}let E=this.scopeRegistry.validateFrontMatter(g.ref,T.markdown),b=q(T.markdown);if(!E.valid){this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:"excluded",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});continue}if(R?.status==="conflict"&&R.grantGeneration===a.generation)continue;if(R?.documentId&&R.grantGeneration===a.generation){if(R.status==="synced"&&R.syncedFingerprint===b)continue;let Se=R?.sourceFingerprint===b;this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R.syncedFingerprint,documentId:R.documentId,status:Se?R.status:"waiting",errorCode:Se?R.errorCode:null,nextAttemptAt:Se?R.nextAttemptAt:0});continue}if(R?.status==="failed"&&R.grantGeneration===a.generation&&R.sourceFingerprint===b&&!_n.has(R.errorCode??"")||R?.status==="blocked"&&R.errorCode!=="APP_LOCAL_QUOTA"&&R.grantGeneration===a.generation&&R.sourceFingerprint===b)continue;let Ie=this.dependencies.store.enqueueCreation({jobId:this.createId(),requestId:this.createId(),bindingId:e,accountKey:r.accountKey,grantId:a.grantId,grantGeneration:a.generation,ref:g.ref,fingerprint:b,now:this.now()}),v=R?.sourceFingerprint===b,be=R?.status==="failed"&&_n.has(R.errorCode??"");this.writeResult(r,a,g.ref,{sourceFingerprint:b,syncedFingerprint:R?.syncedFingerprint??null,documentId:R?.documentId??null,status:Ie.status==="completed"?"processing":"waiting",errorCode:v&&!be?R.errorCode:null,nextAttemptAt:v&&!be?R.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<rd;i+=1){if(this.hasPendingRevoke(e.bindingId))return [];let a=await this.dependencies.workspace.listAllowedFiles({rootSegments:e.rootSegments,selectors:Jn,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=ht(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,A,qe(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,A,qe(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:q(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(),nd);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,A,qe(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:q(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(q(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 g=await this.dependencies.creationBudget.runCreate({accountKey:i.accountKey,signal:a.signal,dispatch:async()=>{if(this.hasPendingRevoke(e.bindingId))return {kind:"control_pending"};let v=await this.readEligibleFile(e,i.ref,a.signal);if(!this.isCurrent(a))throw new h("APP_SYNC_SESSION_STALE");if(this.dependencies.store.hasDeletedRef(e.accountKey,A,qe(i.ref)))return {kind:"deleted"};if(v.status!=="ok")return {kind:"local_file",status:v.status};if(!this.scopeRegistry.validateFrontMatter(i.ref,v.markdown).valid)return {kind:"out_of_scope"};let be=q(v.markdown);if(be!==i.fingerprint)return {kind:"source_changed",fingerprint:be};let Se=this.makeDispatchGate({bindingId:e.bindingId,accountKey:i.accountKey,grant:n,token:a,requestId:i.requestId,source:"app_create"}),No;try{No=await this.dependencies.remote.createGrantedDocument({accountKey:i.accountKey,appId:A,ref:i.ref,requestId:i.requestId,markdown:v.markdown,appVersion:s.appVersion,appGrant:{grantId:i.grantId,generation:i.grantGeneration},signal:a.signal,...Se?{dispatchGate:Se}:{}});}catch(Kn){if(Kn instanceof We)return {kind:"budget_deferred",retryAt:Kn.retryAt};throw Kn}if(Se&&Se.calls===0)throw this.recordMissingDispatchGate({accountKey:i.accountKey,requestId:i.requestId,source:"app_create"});return {kind:"created",result:No}}});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(g.status==="deferred"){let v=this.now();if(!this.deferClaim(i,g.retryAt,v))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:g.retryAt});return}if(g.value.kind==="budget_deferred"){let v=this.now();if(!this.deferClaim(i,g.value.retryAt,v))return;this.writeResult(e,n,i.ref,{sourceFingerprint:i.fingerprint,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:"waiting",errorCode:null,nextAttemptAt:g.value.retryAt});return}if(g.value.kind!=="created"){let v=g.value;if(v.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(v.kind==="deleted"){await this.markDeleted(e,n,i,c);return}if(v.kind==="source_changed"){this.writeResult(e,n,i.ref,{sourceFingerprint:v.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 be=v.kind==="local_file"?v.status:"unsafe";this.writeResult(e,n,i.ref,{sourceFingerprint:null,syncedFingerprint:c?.syncedFingerprint??null,documentId:c?.documentId??null,status:be==="read_error"?"failed":"excluded",errorCode:v.kind==="out_of_scope"?"DOC_APP_BODY_OUT_OF_SCOPE":be==="unsafe"?"APP_FILE_UNSAFE":be==="missing"?"APP_FILE_MISSING":"APP_FILE_READ_FAILED"}),this.dependencies.store.updateCreation(i.jobId,{status:be==="read_error"?"failed":"completed",nextAttemptAt:0,now:this.now()});return}let w=g.value.result;if(w.appGrantId!==n.grantId||w.appGrantGeneration!==n.generation)throw new h("DOC_APP_GRANT_STALE",409);let R=await this.readRemoteDocument({accountKey:i.accountKey,docId:w.docId,signal:a.signal});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(a))return;if(!this.validRemoteDocument(R,w,n)){this.recordOutcome(e,n,i.ref,i.fingerprint,c,w.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 T=q(R.markdown),E,b=i.fingerprint;if(!w.replayed&&!w.reattached&&T===i.fingerprint&&R.markdownVersion===i.fingerprint)E=await this.dependencies.documents.attachCreated({binding:e,grant:n,ref:i.ref,document:R,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal});else {let v;if(E=await this.dependencies.documents.reconcileExisting({binding:e,grant:n,ref:i.ref,document:R,localMarkdown:u.markdown,sourceFingerprint:i.fingerprint,signal:a.signal,beforeDispatch:async()=>(v=await this.beforeDocumentDispatch(e,n,a,i.ref),v)}),!v&&E.dispatch!=="none")throw new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(E.dispatch==="attempted"&&!v)throw new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE");if(v&&!v.ok){this.recordBeforeDispatchFailure(e,n,i.ref,c,v,i);return}v?.ok&&E.dispatch!=="none"&&(b=v.fingerprint);}if(!this.isCurrent(a)||!this.bindingHasGrant(e.bindingId,n))return;let Ie=this.recordOutcome(e,n,i.ref,b,c,w.docId,E);this.dependencies.store.updateCreation(i.jobId,{status:Ie==="conflict"?"conflict":Ie==="failed"?"failed":E.status==="failed"&&E.retryAt!==void 0?"waiting":"completed",nextAttemptAt:E.status==="failed"&&E.retryAt!==void 0?this.retryAt(i.attempts+1,E.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:q(s.markdown),syncedFingerprint:o.syncedFingerprint,documentId:o.documentId,status:"failed",errorCode:"DOC_APP_BODY_OUT_OF_SCOPE"});return}let a=q(s.markdown);if(this.dependencies.store.hasDeletedRef(e.accountKey,A,qe(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(_){if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,_);return}if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(this.isCurrent(r)){if(u.appGrantId!==n.grantId||u.appGrantGeneration!==n.generation||q(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 _,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()=>(_=await this.beforeDocumentDispatch(e,n,r,o.ref),_)});if(this.hasPendingRevoke(e.bindingId)){await this.holdPendingRevoke(e);return}if(!this.isCurrent(r)||!this.bindingHasGrant(e.bindingId,n))return;if(!_&&f.dispatch!=="none"){await this.handleExistingError(e,n,o,a,new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(f.dispatch==="attempted"&&!_){await this.handleExistingError(e,n,o,a,new h("APP_SYNC_ADAPTER_DID_NOT_REVALIDATE"));return}if(_&&!_.ok){this.recordBeforeDispatchFailure(e,n,o.ref,o,_);return}let g=_?.ok&&f.dispatch!=="none"?_.fingerprint:a;this.recordOutcome(e,n,o.ref,g,o,o.documentId,f);}catch(_){if(!this.isCurrent(r))return;await this.handleExistingError(e,n,o,a,_);}}}async handleCreationError(e,n,r,o,s){let i=ht(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(Ht.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(sr.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(or.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(ir(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,$o(s,this.now())),c=ar(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=ht(s);if(i==="DOC_APP_REF_DELETED"){this.dependencies.store.suppressDeletedRef(e.accountKey,A,qe(r.ref),this.now()),this.writeResult(e,n,r.ref,{sourceFingerprint:null,syncedFingerprint:r.syncedFingerprint,documentId:r.documentId,status:"deleted",errorCode:i});return}if(sr.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(Ht.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(or.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(ir(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=ar(s),c=r.sourceFingerprint===o?r.attempts+1:1,u=a?this.retryAt(c,$o(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,A,qe(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,_=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(_,a.retryAt):0,attempts:_}),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,A,qe(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=gt(e.resolvedRootSegments);if(!o||r.workspaceId!==e.workspaceId||!dd(r.rootSegments,o))throw new Error("APP_SYNC_CONTROL_REQUEST_IDENTITY_MISMATCH");return {binding:r,accountKey:n,rootFingerprint:qe(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"&&_n.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&&q(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:A,generation:e.grantGeneration,scopeVersion:e.scopeVersion,scope:ge}}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:cr(),results:[]};let r=this.dependencies.store.listResults(e);return {binding:n,status:n.status,counts:Ho(r,this.dependencies.store.countDeletedRefs(n.accountKey,A)),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(od*2**r,sd)}};function cr(){return {N:0,S:0,P:0,I:0,F:0,C:0,B:0,D:0}}function Ho(t,e){let n=cr(),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 dd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function cd(t,e,n){return t.bindingId===e.bindingId&&t.accountKey===e.session.accountKey&&t.workspaceId===e.workspaceId&&t.rootFingerprint===n&&t.appId===A}function qe(t){return createHash("sha256").update(t,"utf8").digest("hex")}function ht(t){return t instanceof h||t&&typeof t=="object"&&"code"in t&&typeof t.code=="string"?t.code:t instanceof Error?t.message:""}function $o(t,e){if(t instanceof h&&t.retryAfterMs!==void 0||t&&typeof t=="object"&&"retryAfterMs"in t&&typeof t.retryAfterMs=="number")return e+Math.max(t.retryAfterMs,0)}function lr(t){return t instanceof h||t&&typeof t=="object"&&"status"in t&&typeof t.status=="number"?t.status:void 0}function ir(t){let e=ht(t);if(Ht.has(e))return false;let n=lr(t);return _n.has(e)||n===401||n===403}function ud(t){let e=lr(t);return e!==void 0&&e>=400&&e<500}function ar(t){let e=lr(t);return e!==void 0?e===408||e===425||e===429||e>=500:ad.has(ht(t))}var ur=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();x();d();x();M();d();x();F();B();M();U();Cr();d();x();F();B();M();U();d();Ur();d();x();F();B();M();d();U();var qr=["outcome_plan","contract_check","feature_link","use_verify","result_review"];new Set(qr);F();B();d();B();U();U();U();U();xt();xt();wo();dn();pt();xt();xt();At();d();x();d();var Ra=["success","failed","completed"];new Set(Ra);Dn();xt();ko();Ln();var mp=[{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",...mp.map(t=>t.field)];Dn();d();x();F();B();M();U();At();pt();d();d();Zt();d();x();F();B();M();U();d();x();F();B();M();U();d();var Ea=["urgent","high","medium","low"],Ta=["investigating","in-progress","in-review","on-hold","done"];new Set(Ea);new Set(Ta);pt();new Set(Us);new Set(Fs);new Set(qs);new Set(Bs);new Set(Hs);d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();F();x();M();B();pt();U();d();x();d();x();F();M();M();d();x();F();M();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();M();U();d();x();F();B();pt();At();Hr();Tt.map(t=>`'${t}'`).join(", ");var bo=class extends P{handle;sqlite;constructor(e){super();let n=e??this.resolveDbPath();this.handle=L(n),this.sqlite=this.handle.sqlite,H(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!==A)throw new Error("APP_SYNC_APP_UNSUPPORTED");let n=gt(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||!va(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&&va(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&&va(i.rootSegments,n))return i;throw new Error("APP_SYNC_ROOT_ALREADY_BOUND")}throw Lp(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?Eo(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?Eo(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||ke(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(!Oa(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?Ao(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={...Ao(r),...e.patch};
|
|
250
|
+
`).get(e.bindingId,e.grantId,e.generation,e.ref);if(!r)return;let o={...Ao(r),...e.patch};Op(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),Wn(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),Wn(r)})()}putConflict(e){return vp(e.conflict),this.sqlite.transaction(()=>{this.assertContinuationFence(e.fence),Pp(e.conflict,e.fence);let r=this.getConflict(e.conflict.conflictId);if(r&&!xp(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?Ca(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(Ca)}beginConflictResolution(e){
|
|
328
|
+
`).all(e).map(Ca)}beginConflictResolution(e){Dp(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||ke(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 Eo(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:A,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 Wn(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 To(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 Ao(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 Ca(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 Eo(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:A,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 Wn(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 To(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 Ao(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 Ca(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 Op(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 vp(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||!Co(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&&!Co(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 Dp(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)||!Co(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 Pp(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 xp(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 Co(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 Na(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 Io(t){return {requestId:t.request_id,bindingId:t.binding_id,accountKey:t.account_key,appId:A,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 Oa(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 ke(t){return createHash("sha256").update(t,"utf8").digest("hex")}function va(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}function Lp(t){return t instanceof Error&&t.code==="SQLITE_CONSTRAINT_UNIQUE"}export{A as APP_SYNC_APP_ID,Yn as APP_SYNC_CONTINUATION_MAX_PAGE_SIZE,Mt as APP_SYNC_CONTINUATION_MIN_INTERVAL_MS,zn as APP_SYNC_FRONT_MATTER_MAX_BYTES,_t as APP_SYNC_LOCAL_RECORD_LIMIT,Vn as APP_SYNC_PAGE_SIZE,ge as APP_SYNC_SCOPE_DEFINITION,Jn as APP_SYNC_SCOPE_SELECTORS,Qe as APP_SYNC_SCOPE_VERSION,We as AppSyncBudgetDeferredError,dr as AppSyncCoordinator,h as AppSyncRemoteError,qt as AppSyncScopeRegistry,Ut as AppSyncSessionFence,Ft as DOC001_CREATE_LIMIT_PER_WINDOW,cn as DOC001_CREATE_WINDOW_MS,bo as SqliteAppSyncStore,Xn as SqliteDocCreateLedger,Bt as createDispatchGate,q as fingerprintMarkdown,gt as normalizeResolvedRootSegments};
|