@tansr/cli 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/tansr-artifacts.json +1222 -830
- package/tansr-bg-A35DNHK2.mjs +5 -0
- package/tansr-chunk-2CIB4KCJ.mjs +5 -0
- package/{tansr-chunk-XXBNISJJ.mjs → tansr-chunk-2HZJSKHM.mjs} +2 -2
- package/{tansr-chunk-E67N3BDI.mjs → tansr-chunk-2PB54HDR.mjs} +2 -2
- package/tansr-chunk-33QZBUL6.mjs +6 -0
- package/tansr-chunk-3YSQG6KY.mjs +5 -0
- package/tansr-chunk-4DAH4AIH.mjs +7 -0
- package/{tansr-chunk-S77B4PI7.mjs → tansr-chunk-4IWNKAT5.mjs} +2 -2
- package/tansr-chunk-4YAEV3T6.mjs +9 -0
- package/tansr-chunk-546BDI3V.mjs +7 -0
- package/tansr-chunk-6N333TUL.mjs +241 -0
- package/{tansr-chunk-ZY3IR67Q.mjs → tansr-chunk-6QKU3GNA.mjs} +2 -2
- package/tansr-chunk-AHUB2IHT.mjs +5 -0
- package/tansr-chunk-AOH7YPF3.mjs +8 -0
- package/{tansr-chunk-C6COFFZK.mjs → tansr-chunk-B2O4DB4K.mjs} +2 -2
- package/tansr-chunk-C2NTVBEY.mjs +5 -0
- package/{tansr-chunk-UCG4D6ER.mjs → tansr-chunk-C75DEEUJ.mjs} +2 -2
- package/tansr-chunk-ECYZ457U.mjs +5 -0
- package/tansr-chunk-EFN24XG3.mjs +25 -0
- package/tansr-chunk-ENRIN7EG.mjs +7 -0
- package/{tansr-chunk-RVSBSUXE.mjs → tansr-chunk-ITZBYACC.mjs} +2 -2
- package/{tansr-chunk-J72JGEKH.mjs → tansr-chunk-IZZYKHSW.mjs} +3 -3
- package/tansr-chunk-JIC3VWLQ.mjs +252 -0
- package/tansr-chunk-JTGWG4BG.mjs +32 -0
- package/tansr-chunk-LA3LGOYQ.mjs +11 -0
- package/tansr-chunk-MAMODDQN.mjs +5 -0
- package/tansr-chunk-N644DEOO.mjs +5 -0
- package/tansr-chunk-NQOYEFEE.mjs +5 -0
- package/tansr-chunk-O7P4OFK7.mjs +7 -0
- package/tansr-chunk-OEHA7T4Q.mjs +26 -0
- package/{tansr-chunk-CI7LFRTK.mjs → tansr-chunk-OKNSOZDU.mjs} +7 -7
- package/tansr-chunk-OT4KIQLR.mjs +9 -0
- package/tansr-chunk-OUOTEH4A.mjs +5 -0
- package/tansr-chunk-Q3XDAUKT.mjs +65 -0
- package/tansr-chunk-RFH7OCN6.mjs +5 -0
- package/tansr-chunk-RUYIVG72.mjs +12 -0
- package/tansr-chunk-SCFXBKV6.mjs +8 -0
- package/tansr-chunk-SHLU4JN2.mjs +5 -0
- package/{tansr-chunk-M774GK3P.mjs → tansr-chunk-SIV2666W.mjs} +2 -2
- package/tansr-chunk-SX3XZNN6.mjs +6 -0
- package/tansr-chunk-SXNTYWJY.mjs +8 -0
- package/tansr-chunk-UVL2XWKL.mjs +5 -0
- package/tansr-chunk-V4HGMAJS.mjs +375 -0
- package/{tansr-chunk-OB47UYHK.mjs → tansr-chunk-W2WIN3M2.mjs} +2 -2
- package/tansr-chunk-WAYVH5ON.mjs +5 -0
- package/tansr-chunk-WPKFARCU.mjs +11 -0
- package/{tansr-chunk-726Y5F3M.mjs → tansr-chunk-YEYFEVYF.mjs} +2 -2
- package/tansr-chunk-YK3CE3JM.mjs +5 -0
- package/tansr-chunk-YOSRXZWY.mjs +5 -0
- package/tansr-compaction-history-LZXZTWBV.mjs +5 -0
- package/tansr-compaction-log-H2SPLK24.mjs +5 -0
- package/tansr-indexed-CPYJVPFI.mjs +5 -0
- package/tansr-lock-XWDVZMLY.mjs +5 -0
- package/tansr-main-6GDLXIRQ.mjs +7 -0
- package/tansr-render-SVMDLHLN.mjs +6 -0
- package/tansr-restore-7PS7WCJR.mjs +5 -0
- package/tansr-run-acp-entry-EQGUKZ5R.mjs +68 -0
- package/tansr-run-approvals-entry-SEYBHLS2.mjs +12 -0
- package/{tansr-run-auth-entry-X3SXNPOI.mjs → tansr-run-auth-entry-R3GKGKWX.mjs} +2 -2
- package/tansr-run-doctor-B3XK72DW.mjs +11 -0
- package/tansr-run-headless-entry-4XTAVPTW.mjs +84 -0
- package/tansr-run-init-entry-GH2KDGI6.mjs +5 -0
- package/tansr-run-logout-entry-PLGYDEOB.mjs +5 -0
- package/tansr-run-mcp-serve-entry-UHK4WSKL.mjs +14 -0
- package/tansr-run-orchestrate-entry-M7R3433X.mjs +11 -0
- package/tansr-run-org-entry-UONLGJIJ.mjs +17 -0
- package/tansr-run-policy-entry-NNQCV5WS.mjs +16 -0
- package/tansr-run-profile-entry-PV6OO7FV.mjs +14 -0
- package/tansr-run-serve-entry-GWZQZ37P.mjs +16 -0
- package/tansr-run-sessions-entry-WL7YLRJL.mjs +25 -0
- package/tansr-run-update-entry-YI47IPCC.mjs +5 -0
- package/tansr-spill-YVUTIFOS.mjs +5 -0
- package/tansr-src-LPMSGRKO.mjs +5 -0
- package/{tansr-src-JAODAP53.mjs → tansr-src-RQJPOVDN.mjs} +50 -50
- package/tansr-startup-account-MYFJ3NOL.mjs +7 -0
- package/{tansr-startup-model-SREG5HNN.mjs → tansr-startup-model-BCGEYUM4.mjs} +3 -3
- package/tansr-storage-journal-4E274MUA.mjs +5 -0
- package/tansr-todos-replay-TVQKP7OD.mjs +5 -0
- package/tansr-tui-3Q7Z3ALV.mjs +73 -0
- package/tansr.mjs +1 -1
- package/tansrd.mjs +444 -265
- package/tansr-bg-QY4G2SNZ.mjs +0 -5
- package/tansr-chunk-2C6JKHKM.mjs +0 -25
- package/tansr-chunk-53SL6W6G.mjs +0 -6
- package/tansr-chunk-5T7X32UX.mjs +0 -6
- package/tansr-chunk-6OXR4F5Y.mjs +0 -67
- package/tansr-chunk-BCOFZJWA.mjs +0 -279
- package/tansr-chunk-BX7CF5RQ.mjs +0 -25
- package/tansr-chunk-F7C6ITED.mjs +0 -5
- package/tansr-chunk-H6JYYWPW.mjs +0 -35
- package/tansr-chunk-HRKJLVKC.mjs +0 -7
- package/tansr-chunk-I3TOVAA6.mjs +0 -5
- package/tansr-chunk-J2ED6CI4.mjs +0 -5
- package/tansr-chunk-KSBP64Q5.mjs +0 -12
- package/tansr-chunk-LSYPDTQG.mjs +0 -22
- package/tansr-chunk-MWHLITGY.mjs +0 -11
- package/tansr-chunk-NA22YT73.mjs +0 -5
- package/tansr-chunk-NCIMR6LB.mjs +0 -5
- package/tansr-chunk-OSK64SU3.mjs +0 -5
- package/tansr-chunk-Q6MUMULP.mjs +0 -5
- package/tansr-chunk-QEKVLX7W.mjs +0 -5
- package/tansr-chunk-QHEQQ2JB.mjs +0 -9
- package/tansr-chunk-QNHXB55W.mjs +0 -11
- package/tansr-chunk-QWGSXFEJ.mjs +0 -7
- package/tansr-chunk-SJFDQLLC.mjs +0 -5
- package/tansr-chunk-TYJWMSVW.mjs +0 -5
- package/tansr-chunk-TZJHQ3TT.mjs +0 -38
- package/tansr-chunk-UAEARRRH.mjs +0 -8
- package/tansr-chunk-WGXWBU37.mjs +0 -8
- package/tansr-chunk-ZQ3ZK7IL.mjs +0 -37
- package/tansr-main-5V46X7QH.mjs +0 -7
- package/tansr-render-PUEISX75.mjs +0 -6
- package/tansr-run-acp-entry-ANNUR7IB.mjs +0 -63
- package/tansr-run-approvals-entry-SLLTFTSX.mjs +0 -12
- package/tansr-run-doctor-RYIQQOOK.mjs +0 -10
- package/tansr-run-headless-entry-I53HJDNX.mjs +0 -78
- package/tansr-run-init-entry-USPWKDRI.mjs +0 -5
- package/tansr-run-logout-entry-KO7ZL2M5.mjs +0 -5
- package/tansr-run-mcp-serve-entry-YMQH7WSF.mjs +0 -14
- package/tansr-run-orchestrate-entry-YN3M6BWY.mjs +0 -11
- package/tansr-run-org-entry-STRRZVI4.mjs +0 -17
- package/tansr-run-policy-entry-4ENHRAMQ.mjs +0 -16
- package/tansr-run-profile-entry-THJMZ7ZA.mjs +0 -14
- package/tansr-run-serve-entry-N5PK7ACI.mjs +0 -99
- package/tansr-run-sessions-entry-KIT7PALM.mjs +0 -23
- package/tansr-run-update-entry-HYSKHBB6.mjs +0 -5
- package/tansr-sqlite-event-store-UQLSSZKP.mjs +0 -26
- package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +0 -29
- package/tansr-src-KOEPYVXX.mjs +0 -5
- package/tansr-startup-account-QUJKOV6V.mjs +0 -7
- package/tansr-tui-DXGFMSII.mjs +0 -75
package/tansr-chunk-UAEARRRH.mjs
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{b as W,d as Z,h as ee,i as ne,j as te,p as se}from"./tansr-chunk-NCIMR6LB.mjs";import{b as k,d as X}from"./tansr-chunk-Q6MUMULP.mjs";import{c as Q,k as V}from"./tansr-chunk-HRKJLVKC.mjs";import{Eb as z,F as D,G as N,H as J,d as v,fa as K,k as x,l as I,me as H,t as A,x as j,z as h}from"./tansr-chunk-BCOFZJWA.mjs";import{m as E}from"./tansr-chunk-NA22YT73.mjs";import{D as $,Fb as F,Ib as Y}from"./tansr-chunk-QWGSXFEJ.mjs";var S={persistFailed:"cli.sessions.persist_failed",checkpointFailed:"cli.sessions.checkpoint_failed",resumeNotFound:"cli.sessions.resume.not_found",resumeFailed:"cli.sessions.resume.failed",resumeRestored:"cli.sessions.resume.restored",resumeForked:"cli.sessions.resume.forked",resumeNone:"cli.sessions.resume.none",resumeAlreadyCurrent:"cli.sessions.resume.already_current",syntheticToolResult:"cli.sessions.synthetic_tool_result",warningIntegrityBreak:"cli.sessions.warning.integrity_break",warningSynthesized:"cli.sessions.warning.synthesized_results",warningTruncated:"cli.sessions.warning.truncated_messages",warningOversizeReplaced:"cli.sessions.warning.oversize_replaced",warningMicrocompactReplayed:"cli.sessions.warning.microcompact_replayed",warningPruneReplayed:"cli.sessions.warning.prune_replayed",warningUnknownKinds:"cli.sessions.warning.unknown_kinds",resumeStyleUnknown:"cli.sessions.resume.output_style_unknown",resumeUsageStale:"cli.sessions.resume.usage_stale",resumeGrantsRestored:"cli.sessions.resume.grants_restored",exportUsage:"cli.sessions.export.usage",exportUnknownFormat:"cli.sessions.export.unknown_format",exportNotFound:"cli.sessions.export.not_found",exportFailed:"cli.sessions.export.failed",exportWritten:"cli.sessions.export.written",usage:"cli.sessions.usage",pruneUsage:"cli.sessions.prune.usage",pruneInvalidNumber:"cli.sessions.prune.invalid_number",pruneCandidate:"cli.sessions.prune.candidate",pruneSidecarOnlyEntry:"cli.sessions.prune.sidecar_only_entry",pruneSidecarOnlySummary:"cli.sessions.prune.sidecar_only_summary",pruneBrokenEntry:"cli.sessions.prune.broken_entry",pruneBrokenHint:"cli.sessions.prune.broken_hint",pruneSummary:"cli.sessions.prune.summary",pruneKept:"cli.sessions.prune.kept",pruneNothing:"cli.sessions.prune.nothing",pruneDryRunHint:"cli.sessions.prune.dry_run_hint",pruneDeleted:"cli.sessions.prune.deleted",pruneSkippedLocked:"cli.sessions.prune.skipped_locked",pruneSkippedFresh:"cli.sessions.prune.skipped_fresh",pruneApplied:"cli.sessions.prune.applied",pruneAborted:"cli.sessions.prune.aborted"},qe=Object.values(S);import{mkdir as Ne,rename as Ce}from"node:fs/promises";import De from"node:path";var M="agent_notification",re="agent_notification_ack";function Ve(n){return n.channel==="report"?{type:M,version:1,channel:"report",agentId:n.agentId,notificationId:n.notificationId,message:n.message,wake:n.wake}:{type:M,version:1,channel:"settled",agentId:n.agentId,notificationId:n.notificationId,outcome:n.outcome,summary:n.summary}}function $e(n){return{type:re,version:1,agentId:n.agentId,notificationId:n.notificationId}}function _e(n){if(typeof n!="object"||n===null)return null;let e=n;if(e.type!==M||e.version!==1||typeof e.agentId!="string"||typeof e.notificationId!="string")return null;let t=e.channel;return t==="report"?typeof e.message!="string"||typeof e.wake!="boolean"?null:n:t==="settled"?typeof e.outcome!="string"||typeof e.summary!="string"?null:n:null}function Re(n){if(typeof n!="object"||n===null)return null;let e=n;return e.type!==re||e.version!==1||typeof e.agentId!="string"||typeof e.notificationId!="string"?null:n}function oe(n){let e=new Set;for(let r of n){if(r.kind!=="queue_ack")continue;let u=Re(r.payload);u!==null&&e.add(u.notificationId)}let t=[];for(let r of n){if(r.kind!=="queue_enqueue")continue;let u=_e(r.payload);u!==null&&(e.has(u.notificationId)||t.push({enqueueEventId:r.eventId,seq:r.seq,payload:u}))}return t}function T(n){let e=[];for(let t of n){if(t.kind!=="event")continue;let r=ee(t.payload);r!==null&&e.push({seq:t.seq,payload:r})}return e}function Ae(n){return n.filter(e=>e.payload.phase!=="started").length}async function we(n,e){let t=await X(n,e);if(t===null)return null;try{let r=await N(t,{repair:!1});return T(r.records)}catch{return null}}async function ze(n,e){let t=[...e.attempts];if(e.compactBoundary!==void 0&&Ae(t)<5){let r=await we(n,e.compactBoundary.sourceSessionId);r!==null&&(t=[...r,...t])}return ne(t.map(r=>r.payload))}var Pe=1440*60*1e3;function ie(n){let e=[];for(let t of n){if(t.kind!=="event")continue;let r=se(t.payload);r===null||r.type!==te||e.push({seq:t.seq,payload:r})}return e}var Oe=new Set(["allow","deny","ask"]);function We(n,e={}){let t=(e.now??(()=>new Date))().getTime(),r=e.ttlMs??Pe,u=[],o=new Set,c=0;for(let i of n){let{payload:l}=i,a=Date.parse(l.at);if(Number.isNaN(a)||t-a>r){c+=1;continue}if(!Oe.has(l.behavior)){c+=1;continue}let s=l.behavior;for(let p of l.rules){let m=`${s}\0${p}`;o.has(m)||(o.add(m),u.push({rule:p,behavior:s}))}}return{entries:u,skipped:c}}var ve=5;function Ze(n,e=ve){let t=n.map(r=>r.behavior==="allow"?r.rule:`${r.behavior}:${r.rule}`);return t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")} …(+${t.length-e})`}var ae="session_event";var xe=()=>new Date;function nn(n,e,t){return e==="silenced"||e==="merged"&&n.phase===void 0?null:{type:ae,version:1,kind:n.kind,severity:n.severity,origin:n.origin,scope:n.scope,detail:n.detail,mode:n.mode,...n.phase!==void 0?{phase:n.phase}:{},count:n.count,occurredAt:n.occurredAt,change:e,at:(t??xe)().toISOString()}}function de(n){if(typeof n!="object"||n===null)return null;let e=n;if(e.type!==ae||e.version!==1||typeof e.kind!="string"||typeof e.scope!="string")return null;let t=e.phase;if(t!==void 0&&t!=="enter"&&t!=="exit")return null;let r=e.change;return r!=="new"&&r!=="merged"?null:n}function Ie(n){return n==="kernel"||n==="tui"||n==="providers"||n==="platform"||n==="tool"?n:"kernel"}function ue(n){let e=new Map;for(let t of n){if(t.kind!=="event")continue;let r=de(t.payload);if(r===null||r.phase===void 0)continue;let u=`${r.kind}\0${r.scope}`;r.phase==="enter"?e.has(u)||e.set(u,{kind:r.kind,scope:r.scope,origin:Ie(r.origin)}):e.delete(u)}return[...e.values()]}function ce(n){let e=null;for(let t of n){if(t.kind!=="event")continue;let r=de(t.payload);r===null||r.kind!=="model_switched"||r.scope!==""&&(e=r.scope)}return e}async function le(n,e){let t=await Te(n,e,{migrateToVault:!1,readOnly:!0});return t.ok?{ok:!0,messages:t.messages,warnings:t.warnings,...t.meta?.cwd!==void 0?{storedCwd:t.meta.cwd}:{},...t.compactBoundary!==void 0?{compactBoundary:t.compactBoundary}:{},...t.heldBy!==void 0?{heldBy:t.heldBy}:{}}:{ok:!1,reason:t.reason,detail:t.detail}}function Me(n){for(let e of n){if(e.branchId!==D||e.kind!=="compact_boundary")continue;let t=$.safeParse(e.payload);return t.success?t.data:void 0}}async function Te(n,e,t={}){let r=t.readOnly===!0,u=!r&&(t.migrateToVault??!0),o;try{o=A(n,e)}catch(s){return{ok:!1,reason:"not_found",detail:s instanceof Error?s.message:String(s)}}let c=!1;if(await k(o)===null){let s=V(n);if(s===null)return{ok:!1,reason:"not_found",detail:e};let p;try{p=A(s,e)}catch{return{ok:!1,reason:"not_found",detail:e}}if(await k(p)===null)return{ok:!1,reason:"not_found",detail:e};if(u)try{await Ne(De.dirname(o),{recursive:!0,mode:Q}),await Ce(p,o)}catch{o=p,c=!0}else o=p}let i=null,l;if(r)try{let s=await x(o);s.alive&&s.pid!==void 0&&(l={pid:s.pid,...s.host!==void 0?{host:s.host}:{},...s.startedAt!==void 0?{startedAt:s.startedAt}:{}})}catch(s){return{ok:!1,reason:"io_error",detail:s instanceof Error?s.message:String(s)}}else try{i=await I(o)}catch(s){return s instanceof v&&s.code==="SESSION_LOCKED"?{ok:!1,reason:"locked",detail:s.message}:{ok:!1,reason:"io_error",detail:s instanceof Error?s.message:String(s)}}let a=async()=>{i!==null&&await i.release()};try{let s=await N(o,r?{repair:!1}:{}),p=J(s.records),m=z(p.messages),y=K(m.messages,{resolvePersistedPath:Z(o),resolvePrunedPath:W(o)});if(m.messages.length===0)return await a(),{ok:!1,reason:"not_found",detail:e};let _=s.records.filter(b=>b.branchId===D&&(b.kind==="user_prompt"||b.kind==="assistant_message"||b.kind==="tool_result")&&b.visibility.model).length,R=s.records[s.records.length-1]?.eventId??null,f=[...p.warnings,...s.repairs];s.integrityBreakAt!==void 0&&f.push(E(S.warningIntegrityBreak,{index:s.integrityBreakAt})),s.unknownKinds!==void 0&&f.push(E(S.warningUnknownKinds,{count:s.unknownKinds.length,kinds:s.unknownKinds.join(", ")})),m.synthesizedResults>0&&f.push(E(S.warningSynthesized,{count:m.synthesizedResults})),m.droppedMessages>0&&f.push(E(S.warningTruncated,{count:m.droppedMessages})),y.clampReplacedCount>0&&f.push(E(S.warningOversizeReplaced,{count:y.clampReplacedCount})),y.pruneReplayedCount>0&&f.push(E(S.warningPruneReplayed,{count:y.pruneReplayedCount})),y.evictReplayedCount>0&&f.push(E(S.warningMicrocompactReplayed,{count:y.evictReplayedCount}));let w=i!==null&&!c&&p.warnings.length===0&&m.droppedMessages===0&&s.integrityBreakAt===void 0,d;try{d=await h(o)}catch{}let g=Me(s.records),B=oe(s.records),G=T(s.records),L=ie(s.records),q=ue(s.records),ke=d?.provider!==void 0&&d.provider!==""&&d.model!==void 0&&d.model!==""?`${d.provider}/${d.model}`:null,P=ce(s.records)??ke,O=H(s.records);return!w||i===null?(await a(),{ok:!0,sessionId:e,messages:y.messages,journalMessageCount:_,continuable:!1,...l!==void 0?{heldBy:l}:{},lastEventId:R,lastSeq:p.lastSeq,cursor:s.cursor,warnings:f,...d!==void 0?{meta:d}:{},...g!==void 0?{compactBoundary:g}:{},pendingAgentNotifications:B,compactionAttempts:G,sessionGrants:L,sessionEventConditions:q,...P!==null?{lastEffectiveModel:P}:{},...O!==void 0?{usageSnapshot:O}:{}}):{ok:!0,sessionId:e,messages:y.messages,journalMessageCount:_,continuable:!0,lock:i,lastEventId:R,lastSeq:p.lastSeq,cursor:s.cursor,warnings:f,...d!==void 0?{meta:d}:{},...g!==void 0?{compactBoundary:g}:{},pendingAgentNotifications:B,compactionAttempts:G,sessionGrants:L,sessionEventConditions:q,...P!==null?{lastEffectiveModel:P}:{},...O!==void 0?{usageSnapshot:O}:{}}}catch(s){return await a(),{ok:!1,reason:"corrupt",detail:s instanceof Error?s.message:String(s)}}}async function An(n,e,t,r=()=>new Date){let u=await le(n,e);if(!u.ok)return{ok:!1,reason:u.reason,detail:u.detail};let o;try{o=await h(A(n,e))}catch{o=void 0}let c=r().toISOString();if(t==="json"){let i={schemaVersion:1,sessionId:e,exportedAt:c,...o!==void 0?{meta:o}:{},warnings:u.warnings,messages:u.messages};return{ok:!0,text:JSON.stringify(Y(i),null,2)}}return{ok:!0,text:F(Ue(e,c,o,u.warnings,u.messages))}}function pe(n,e){return`> [image ${n}, base64 ${e.length} chars omitted]`}function Ue(n,e,t,r,u){let o=[`# Tansr session ${n}`,""];t!==void 0&&(t.title!==void 0&&o.push(`- title: ${t.title}`),o.push(`- cwd: ${t.cwd}`),o.push(`- created: ${t.createdAt}`),(t.provider!==void 0||t.model!==void 0)&&o.push(`- model: ${t.provider??"?"}/${t.model??"?"}`)),o.push(`- exported: ${e}`),r.length>0&&o.push("","## Warnings","",...r.map(c=>`- ${c}`));for(let c of u){o.push("","---","",`## ${c.role==="user"?"User":"Assistant"}`,"");for(let i of c.blocks)switch(i.t){case"text":o.push(i.text,"");break;case"thinking":o.push("> _[thinking]_",...i.text.split(`
|
|
5
|
-
`).map(l=>`> ${l}`),"");break;case"opaque":o.push(`> [opaque reasoning payload · provider: ${i.provider}]`,"");break;case"tool_call":o.push(`**Tool call — ${i.name}** (\`${i.id}\`)`,"","````json",JSON.stringify(i.args,null,2)??"null","````","");break;case"tool_result":{o.push(`**Tool result** (\`${i.callId}\`)${i.isError===!0?" — error":""}`,"");for(let l of i.content)l.t==="text"?o.push("````",l.text,"````",""):o.push(pe(l.mime,l.data),"");break}case"image":o.push(pe(i.mime,i.data),"");break}}return o.join(`
|
|
6
|
-
`)+`
|
|
7
|
-
`}import{readdir as fe,rm as Be,stat as ye}from"node:fs/promises";import U from"node:path";var Ge=90,Le=500;async function ge(n){let e=0,t;try{t=await fe(n,{withFileTypes:!0})}catch{return 0}for(let r of t){let u=U.join(n,r.name);if(r.isDirectory())e+=await ge(u);else try{e+=(await ye(u)).size}catch{}}return e}function Se(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function C(n,e){try{return(await x(n,{isPidAlive:e})).alive}catch{return!1}}function Ee(n){let e=new Date(n);return e.setHours(0,0,0,0),e.getTime()}async function me(n){try{return await ye(n)}catch{return null}}async function he(n){let e=U.join(n,"sessions"),t;try{t=(await fe(e,{withFileTypes:!0})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return{valid:[],sidecarOnly:[],broken:[]}}let r=[],u=[],o=[];for(let c of t){let i=U.join(e,c),l=await ge(i),a=await k(i),s=await me(j(i)),p=(await me(i))?.mtimeMs??0;if(s===null&&a===null){u.push({name:c,dir:i,mtimeMs:p,bytes:l});continue}try{let m=await h(i);if(a===null)throw new Error("journal_missing");if(m.sessionId!==c)throw new Error("meta_mismatch");r.push({sessionId:c,dir:i,updatedAt:a.mtimeMs,bytes:l})}catch{o.push({name:c,dir:i,mtimeMs:p,bytes:l})}}return{valid:r,sidecarOnly:u,broken:o}}async function In(n){let{valid:e,sidecarOnly:t,broken:r}=await he(n),u=e.reduce((o,c)=>o+c.bytes,0)+t.reduce((o,c)=>o+c.bytes,0)+r.reduce((o,c)=>o+c.bytes,0);return{sessions:e.length,brokenDirs:r.length,sidecarOnlyDirs:t.length,totalBytes:u}}async function Nn(n,e={}){let t=e.keepDays??Ge,r=e.keepLast??Le,u=e.now??Date.now(),o=e.isPidAlive??Se,c=new Set(e.protectSessionIds??[]),{valid:i,sidecarOnly:l,broken:a}=await he(n),s=[...i].sort((d,g)=>g.updatedAt-d.updatedAt),p=new Set;for(let d of s.slice(0,r))p.add(d.sessionId);let m=u-t*864e5,y=Ee(u),_=0;for(let d of s)(d.updatedAt>=m||d.updatedAt>=y)&&p.add(d.sessionId),c.has(d.sessionId)&&p.add(d.sessionId),!p.has(d.sessionId)&&await C(d.dir,o)&&(p.add(d.sessionId),_+=1);let R=i.filter(d=>!p.has(d.sessionId)).sort((d,g)=>d.updatedAt-g.updatedAt),f=new Set;for(let d of l)(d.mtimeMs>=m||d.mtimeMs>=y)&&f.add(d.name),c.has(d.name)&&f.add(d.name),!f.has(d.name)&&await C(d.dir,o)&&f.add(d.name);let w=l.filter(d=>!f.has(d.name)).sort((d,g)=>d.mtimeMs-g.mtimeMs);return{candidates:R,sidecarOnly:w,totalSidecarOnly:l.length,sidecarOnlyKeptCount:l.length-w.length,broken:a,totalSessions:i.length,keptCount:i.length-R.length,inUseCount:_}}async function Cn(n,e={}){let t=e.isPidAlive??Se,r=e.now??Date.now(),u=e.rmDir??(a=>Be(a,{recursive:!0,force:!0})),o=[],c=[],i=[],l=Ee(r);for(let a of n.candidates){let s;try{s=await I(a.dir,{isPidAlive:t,staleMs:1/0})}catch(m){if(m instanceof v&&m.code==="SESSION_LOCKED"){c.push(a.sessionId);continue}return{deleted:o,skippedLocked:c,skippedFresh:i,aborted:{name:a.sessionId,message:m instanceof Error?m.message:String(m)}}}let p=(await k(a.dir))?.mtimeMs;if(p===void 0||p>=l){await s.release(),i.push(a.sessionId);continue}try{await u(a.dir)}catch(m){try{await s.release()}catch{}return{deleted:o,skippedLocked:c,skippedFresh:i,aborted:{name:a.sessionId,message:m instanceof Error?m.message:String(m)}}}await s.release(),o.push({name:a.sessionId,bytes:a.bytes}),e.onDeleted?.({name:a.sessionId,bytes:a.bytes})}for(let a of n.sidecarOnly)if(!(a.mtimeMs>=l)&&!await C(a.dir,t)){try{await u(a.dir)}catch(s){return{deleted:o,skippedLocked:c,skippedFresh:i,aborted:{name:a.name,message:s instanceof Error?s.message:String(s)}}}o.push({name:a.name,bytes:a.bytes}),e.onDeleted?.({name:a.name,bytes:a.bytes})}if(e.includeBroken===!0){for(let a of n.broken)if(!(a.mtimeMs>=l)&&!await C(a.dir,t)){try{await u(a.dir)}catch(s){return{deleted:o,skippedLocked:c,skippedFresh:i,aborted:{name:a.name,message:s instanceof Error?s.message:String(s)}}}o.push({name:a.name,bytes:a.bytes}),e.onDeleted?.({name:a.name,bytes:a.bytes})}}return{deleted:o,skippedLocked:c,skippedFresh:i}}export{S as a,Ve as b,$e as c,ze as d,We as e,Ze as f,nn as g,le as h,Te as i,An as j,Ge as k,Le as l,In as m,Nn as n,Cn as o};
|
|
8
|
-
//# sourceMappingURL=tansr-chunk-UAEARRRH.mjs.map
|
package/tansr-chunk-WGXWBU37.mjs
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{E as Ne,i as Te,k as xe}from"./tansr-chunk-LSYPDTQG.mjs";import{c as J,d as q,j as P,o as Re,s as Se}from"./tansr-chunk-HRKJLVKC.mjs";import{$d as ke,_d as be,ae as ve,be as Ee,ce as Q,cf as Ie,df as R,fe as U,ge as C,he as Ae,ie as _e,je as Pe}from"./tansr-chunk-BCOFZJWA.mjs";import{D as ee,F as Oe,G as Le,K as Ce,L as Me}from"./tansr-chunk-2C6JKHKM.mjs";import{d as he}from"./tansr-chunk-DIT3PBNB.mjs";var ne={app_model_selection_empty:"cli.bundle.error.app_model_selection_empty",owner_model_selection_empty:"cli.bundle.error.owner_model_selection_empty",default_model_pool_empty:"cli.bundle.error.default_model_pool_empty",selected_models_unavailable:"cli.bundle.error.selected_models_unavailable"},M="tansr",je="TANSR_KEY",vn="TANSR_DIRECT_KEYLESS",En=["imagegen","videogen","asr","tts"],Be=Object.freeze({imageGen:Object.freeze([]),videoGen:Object.freeze([]),speechToText:Object.freeze([]),textToSpeech:Object.freeze([])}),Fe=["test","small","medium","large"],An=["active","grace","lapsed"];function f(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _n(e){if(!f(e)||typeof e.handle!="string"||e.handle===""||typeof e.modelId!="string"||e.modelId===""||typeof e.protocol!="string")return null;let n=Te(e.adapterDiagnostics),t=e.pricing,o=null;return f(t)&&typeof t.currency=="string"&&typeof t.inPerMillion=="string"&&typeof t.outPerMillion=="string"&&(o={currency:t.currency,inPerMillion:t.inPerMillion,outPerMillion:t.outPerMillion,cacheReadPerMillion:typeof t.cacheReadPerMillion=="string"?t.cacheReadPerMillion:"0",cacheWritePerMillion:typeof t.cacheWritePerMillion=="string"?t.cacheWritePerMillion:"0"}),{handle:e.handle,modelId:e.modelId,displayName:typeof e.displayName=="string"?e.displayName:e.handle,protocol:e.protocol,kind:typeof e.kind=="string"&&e.kind!==""?e.kind:null,family:typeof e.family=="string"&&e.family!==""?e.family:null,manufacturer:typeof e.manufacturer=="string"&&e.manufacturer!==""?e.manufacturer:null,tags:Array.isArray(e.tags)?e.tags.filter(r=>typeof r=="string"&&r!==""):[],capabilities:f(e.capabilities)?e.capabilities:{},contextWindow:typeof e.contextWindow=="number"?e.contextWindow:null,recommendedContextTokens:typeof e.recommendedContextTokens=="number"?e.recommendedContextTokens:null,pricing:o,...n===void 0?{}:{adapterDiagnostics:n}}}function Pn(e){return!f(e)||typeof e.handle!="string"||e.handle===""||typeof e.baseUrl!="string"||e.baseUrl===""||typeof e.protocol!="string"||typeof e.modelId!="string"||e.modelId===""?null:{handle:e.handle,baseUrl:e.baseUrl,protocol:e.protocol,modelId:e.modelId,credentialEnv:typeof e.credentialEnv=="string"?e.credentialEnv:null}}function Ue(e){return Array.isArray(e)?f(e[0])?e[0]:null:f(e)?e:null}function De(e){let n=Ue(e);return n===null||typeof n.profileId!="string"||n.profileId===""||n.modelHandle!==void 0&&(typeof n.modelHandle!="string"||n.modelHandle==="")?null:{profileId:n.profileId,...n.modelHandle!==void 0?{modelHandle:n.modelHandle}:{},budgets:f(n.budgets)?n.budgets:{},escalation:f(n.escalation)?n.escalation:{},...n.locked===!0?{locked:!0}:{}}}function On(e){if(Array.isArray(e.adjudicators))return e.adjudicators.map(De).filter(t=>t!==null);let n=De(e.adjudicator);return n!==null?[n]:[]}function Ln(e){let n=Ue(e);return n===null||typeof n.schemeId!="string"||n.schemeId===""?null:{schemeId:n.schemeId,stage:n.stage==="production"?"production":"experimental",scheme:f(n.scheme)?n.scheme:{},...n.locked===!0?{locked:!0}:{}}}function Cn(e){if(!f(e))return null;let n=e.dailyTokenLimit;return typeof n=="number"&&Number.isFinite(n)&&n>0?{dailyTokenLimit:Math.floor(n)}:null}function Mn(e){if(!f(e))return null;let n=e.org;if(!f(n)||typeof n.id!="string"||n.id==="")return null;let t=null;if(f(e.budgets)){let o=e.budgets.dailyTokenLimit;t={dailyTokenLimit:typeof o=="number"&&Number.isFinite(o)&&o>0?Math.floor(o):null}}return{org:{id:n.id,name:typeof n.name=="string"?n.name:""},licenseStatus:typeof e.licenseStatus=="string"?e.licenseStatus:"",softLock:e.softLock===!0,budgets:t}}function In(e){if(!f(e)||e.enabled!==!0)return null;let n=e.dailyLimit;return{enabled:!0,pricePerCall:typeof e.pricePerCall=="string"&&e.pricePerCall!==""?e.pricePerCall:null,currency:typeof e.currency=="string"&&e.currency!==""?e.currency:null,dailyLimit:typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):null,defaultVendor:typeof e.defaultVendor=="string"&&e.defaultVendor!==""?e.defaultVendor:null}}function W(e){if(!f(e)||e.enabled!==!0)return null;let n=e.dailyLimit;return{enabled:!0,dailyLimit:typeof n=="number"&&Number.isFinite(n)&&n>0?Math.floor(n):null}}function Tn(e){if(!f(e))return null;let n={imagegen:W(e.imagegen),videogen:W(e.videogen),asr:W(e.asr),tts:W(e.tts)};return En.some(t=>n[t]!==null)?n:null}function xn(e){if(!f(e))return Be;let n=xe({platformModels:e});if(n===null)return Be;let{imageGen:t,videoGen:o,speechToText:r,textToSpeech:i}=n.platformModels;return{imageGen:t,videoGen:o,speechToText:r,textToSpeech:i}}function Nn(e){return f(e)&&(e.mode==="allow"||e.mode==="deny")?{mode:e.mode}:null}function $(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}function Bn(e){if(!f(e))return null;let n=e.tier;if(typeof n!="string"||!Fe.includes(n))return null;let t=e.caps;if(!f(t)||!$(t.concurrency)||!$(t.apps)||!$(t.orgMembers)||!(t.monthlyEndUsers===null||$(t.monthlyEndUsers))||typeof t.gatewayLane!="boolean")return null;let o=e.status;if(typeof o!="string"||!An.includes(o)||typeof e.expiresAt!="string"||e.expiresAt==="")return null;let r=e.lapsedFrom;return{tier:n,caps:{concurrency:t.concurrency,apps:t.apps,orgMembers:t.orgMembers,monthlyEndUsers:t.monthlyEndUsers,gatewayLane:t.gatewayLane},status:o,expiresAt:e.expiresAt,...typeof r=="string"&&Fe.includes(r)?{lapsedFrom:r}:{}}}var Fn=["platform","org","team","user"];function Dn(e){if(!f(e)||!f(e.values))return null;let n=o=>Array.isArray(o)?[...new Set(o.filter(r=>typeof r=="string"&&r!==""))]:[],t={};if(f(e.origins))for(let[o,r]of Object.entries(e.origins))typeof r=="string"&&Fn.includes(r)&&(t[o]=r);return{values:structuredClone(e.values),locks:n(e.locks),origins:t,shadow:n(e.shadow)}}function Ve(e){if(!f(e)||typeof e.version!="number"||typeof e.etag!="string")return null;let n=Array.isArray(e.diagnostics)?e.diagnostics.find(l=>f(l)&&typeof l.code=="string"&&Object.hasOwn(ne,l.code))?.code:e.modelAvailabilityReason,t=Array.isArray(e.models)?e.models.map(_n).filter(l=>l!==null):[],o=Array.isArray(e.directEndpoints)?e.directEndpoints.map(Pn).filter(l=>l!==null):[],r={};if(f(e.aliases))for(let[l,p]of Object.entries(e.aliases))typeof p=="string"&&p!==""&&(r[l]=p);let i=Array.isArray(e.fastFallbackGroup)?e.fastFallbackGroup.filter(l=>typeof l=="string"&&l!==""):[],a=(()=>{if(!f(e.aliasOrigins))return null;let l={};return typeof e.aliasOrigins.main=="string"&&e.aliasOrigins.main!==""&&(l.main=e.aliasOrigins.main),typeof e.aliasOrigins.fast=="string"&&e.aliasOrigins.fast!==""&&(l.fast=e.aliasOrigins.fast),Object.keys(l).length>0?l:null})(),c=f(e.app)&&typeof e.app.id=="string"&&e.app.id!==""?{id:e.app.id,name:typeof e.app.name=="string"?e.app.name:""}:null,s=On(e);return{...typeof n=="string"&&Object.hasOwn(ne,n)?{modelAvailabilityReason:n}:{},version:e.version,etag:e.etag,publishedAt:typeof e.publishedAt=="string"?e.publishedAt:"",configVersion:typeof e.configVersion=="string"&&e.configVersion!==""?e.configVersion:null,app:c,models:t,aliases:r,fastFallbackGroup:i,aliasOrigins:a,directEndpoints:o,adjudicators:s,adjudicator:s[0]??null,contextScheme:Ln(e.contextScheme),guardrails:Cn(e.guardrails),orgGovernance:Mn(e.governance??e.orgGovernance),websearch:In(e.websearch),orgMemory:Nn(e.orgMemory),settings:Dn(e.settings),plan:Bn(e.plan),media:Tn(e.media),platformModels:xn(e.platformModels)}}function wn(e){switch(e){case"openai_chat":case"openai":return"openai";case"anthropic_messages":case"anthropic":return"anthropic";case"openai_responses":case"openai-responses":return"openai-responses";default:return null}}function jn(e,n){let t=be.safeParse(e),o=t.success?t.data:{},r=!t.success&&Object.keys(e).length>0,i={...o,...n!==null&&n>0?{maxContext:n}:{}};return{override:Object.keys(i).length>0?i:void 0,dropped:r}}function Un(e,n){return e===null||e<=0||n===null||n<=0||n>=e?{effectiveWindow:e,clamped:!1}:{effectiveWindow:n,clamped:!0}}function Vn(e){if(e===null)return null;let n=Number(e.inPerMillion),t=Number(e.outPerMillion);if(!Number.isFinite(n)||!Number.isFinite(t))return null;let o=Number(e.cacheReadPerMillion);return{inputPerMillion:n,outputPerMillion:t,...Number.isFinite(o)&&o>0?{cachedInputPerMillion:o}:{}}}function Lt(e){return{providers:{[M]:{protocol:"twp",baseUrl:`${e}/t1`,auth:{env:je},models:{}}},modelAliases:{}}}function Ct(e,n){let t=[];e.models.length===0&&e.modelAvailabilityReason!==void 0&&t.push({key:ne[e.modelAvailabilityReason]});let o=[],r={protocol:"twp",baseUrl:`${n}/t1`,auth:{env:je},models:{},pricing:{},modelCapabilities:{}},i={};for(let s of e.models){r.models[s.handle]=s.handle,i[s.handle]=`${M}/${s.handle}`;let{effectiveWindow:l,clamped:p}=Un(s.contextWindow,s.recommendedContextTokens),{override:b,dropped:S}=jn(s.capabilities,l);p&&t.push({key:R.qualityWindowApplied,params:{handle:s.handle,declared:s.contextWindow??0,effective:l??0}}),S&&t.push({key:R.entrySkipped,params:{handle:s.handle,reason:"capabilities"}}),b!==void 0&&r.modelCapabilities!==void 0&&(r.modelCapabilities[s.handle]=b);let m=Vn(s.pricing);if(m!==null&&r.pricing!==void 0){r.pricing[s.handle]=m;let y=s.pricing?.currency;y!==void 0&&_e.includes(y)?o.push({providerId:M,modelName:s.handle,currency:y,pricing:m,note:"client-config bundle"}):y!==void 0&&t.push({key:R.entrySkipped,params:{handle:s.handle,reason:`currency ${y}`}})}}let a={[M]:r},c={};for(let s of e.directEndpoints){let l=wn(s.protocol);if(l===null){t.push({key:R.entrySkipped,params:{handle:s.handle,reason:`protocol ${s.protocol}`}});continue}if(s.handle===M){t.push({key:R.entrySkipped,params:{handle:s.handle,reason:"reserved handle"}});continue}a[s.handle]={protocol:l,baseUrl:s.baseUrl,auth:{env:s.credentialEnv??vn},models:{}},c[s.handle]=`${s.handle}/${s.modelId}`}for(let[s,l]of Object.entries(e.aliases))c[s]=l.includes("/")?l:`${M}/${l}`;return{fragment:{providers:a,modelAliases:c,catalogAliases:i},diagnostics:t,pricingUpdates:o}}function Mt(e){if(e.length===0)return;let n=Pe();return n.refreshPricing(e,"refreshed"),n}var we=new Set(["__proto__","constructor","prototype"]);function te(e,n){if(f(e)&&f(n)){let t={};for(let o of Object.keys(e))we.has(o)||(t[o]=e[o]);for(let o of Object.keys(n))we.has(o)||(t[o]=o in t?te(t[o],n[o]):n[o]);return t}return n}function Gn(){return{$schemaVersion:1,providers:{},modelAliases:{},fallbacks:{},telemetry:{enabled:!1}}}function It(e,n,t){let o=e??Gn(),r=te(n.providers,o.providers),i={...t?.catalogAliases??{},...n.modelAliases,...o.modelAliases};return t!==null&&(r=te(r,t.providers),i={...i,...t.modelAliases}),{...o,providers:r,modelAliases:i}}import Kn from"node:os";import Ge from"node:path";var Yn="TANSR_RECORD",oe;function Wn(e){if(oe===void 0){let n=e().toISOString();oe=`${n.slice(0,10).replaceAll("-","")}-${n.slice(11,19).replaceAll(":","")}-${process.pid}`}return oe}var Ke=0;function Ye(e){return e.replaceAll(/[^A-Za-z0-9._-]/g,"_")}function re(e,n,t={}){let o=t.env??process.env;if(o[Yn]?.trim()!=="1")return e;let r=t.homedir??(()=>Kn.homedir()),i=t.now??(()=>new Date),a=o.TANSR_CONFIG_DIR?.trim(),c=a!==void 0&&a!==""?a:Ge.join(r(),".tansr"),s=Ge.join(c,"recordings",Wn(i));Ke+=1;let l=`${String(Ke).padStart(2,"0")}-${Ye(n.providerId)}-${Ye(n.modelName)}`;return new Le({inner:e,dir:s,name:l,source:`${n.providerId}/${n.modelName}`,env:o,now:i})}var V={anthropicUrl:"TANSR_TEST_ANTHROPIC_URL",openaiUrl:"TANSR_TEST_OPENAI_URL",model:"TANSR_TEST_MODEL",apiKey:"TANSR_TEST_API_KEY"};function Ut(e,n,t={}){let o=new ee(e,{...t.env!==void 0?{env:t.env}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{},...t.twp!==void 0?{twp:t.twp}:{},...t.governor!==void 0?{governor:t.governor}:{}}),{client:r,resolved:i}=Ce(o,n,{...t.onProviderSelected!==void 0?{onProviderSelected:t.onProviderSelected}:{},...t.attemptObserver!==void 0?{attemptObserver:t.attemptObserver}:{},...t.governor!==void 0?{governor:t.governor}:{}});return{client:re(r,i,{...t.env!==void 0?{env:t.env}:{}}),resolved:i,registry:o}}var $n=2;function Vt(e,n,t={}){let o=new ee(e,{...t.env!==void 0?{env:t.env}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{},...t.twp!==void 0?{twp:t.twp}:{},...t.governor!==void 0?{governor:t.governor}:{}}),r=o.resolveAlias(n),i=o.createClient(r),a=o.fallbacksFor(n),c=Me(t.governor),s=new Oe({entries:a,createClient:l=>l===a[0]?i:o.createClient(l),retry:{...c.retry??{},maxAttempts:$n},...c.retryBudget!==void 0?{retryBudget:c.retryBudget}:{},...t.onProviderSelected!==void 0?{onProviderSelected:t.onProviderSelected}:{},...t.attemptObserver!==void 0?{attemptObserver:t.attemptObserver}:{}});return{client:re(s,r,{...t.env!==void 0?{env:t.env}:{}}),resolved:r}}function ie(e,n){let t=e[n]?.trim();return t===void 0||t===""?void 0:t}function We(e){let n=ie(e,V.anthropicUrl),t=ie(e,V.openaiUrl),o=ie(e,V.model);if(o===void 0||n===void 0&&t===void 0)return null;let r={};return n!==void 0&&(r["maas-anthropic"]={protocol:"anthropic",baseUrl:n,auth:{env:V.apiKey},models:{main:o}}),t!==void 0&&(r["maas-openai"]={protocol:"openai",baseUrl:t,auth:{env:V.apiKey},models:{main:o}}),{$schemaVersion:1,providers:r,modelAliases:{main:`${n!==void 0?"maas-anthropic":"maas-openai"}/main`},fallbacks:{},telemetry:{enabled:!1}}}import{readdir as Zn,readFile as Hn,rm as zn}from"node:fs/promises";import le from"node:os";import Z from"node:path";var Xn="bundle-cache",Jn=384;function qn(e){return`${e.replace(/[^A-Za-z0-9-]/g,t=>`_${t.codePointAt(0).toString(16)}`)}.json`}function Ze(e,n,t=le.homedir()){let o=P(e,t);return o!==null?o.bundleCacheFile:Z.join(He(e,t),qn(n))}function He(e,n=le.homedir()){let t=e.TANSR_CONFIG_DIR?.trim(),o=t!==void 0&&t!==""?t:Z.join(n,".tansr");return Z.join(o,Xn)}async function Xt(e,n=le.homedir()){let t=[],o=He(e,n),r=[];try{r=await Zn(o)}catch{r=[]}for(let a of r){if(!a.endsWith(".json"))continue;let c=Z.join(o,a);await $e(c)&&t.push(c)}let i=P(e,n);return i!==null&&await $e(i.bundleCacheFile)&&t.push(i.bundleCacheFile),t}async function $e(e){try{return await zn(e),!0}catch{return!1}}async function se(e,n,t=o=>Hn(o,"utf8")){let o;try{o=await t(e)}catch{return null}let r;try{r=JSON.parse(o)}catch{return null}if(typeof r!="object"||r===null)return null;let i=r;if(i.version!==1||i.apiBaseUrl!==n||typeof i.etag!="string"||typeof i.fetchedAt!="string")return null;let a=Date.parse(i.fetchedAt);if(Number.isNaN(a))return null;let c=Ve(i.bundle);return c===null?null:{etag:i.etag,fetchedAtMs:a,bundle:c}}async function Qn(e,n){let t={version:1,apiBaseUrl:n.apiBaseUrl,etag:n.etag,fetchedAt:new Date(n.fetchedAtMs).toISOString(),bundle:n.bundle};await Re(e,JSON.stringify(t,null,2)+`
|
|
5
|
-
`,{mode:Jn})}async function Jt(e,n,t){let o=await se(e,n);o!==null&&await Qn(e,{apiBaseUrl:n,etag:o.etag,fetchedAtMs:t,bundle:o.bundle})}import{readFile as et}from"node:fs/promises";import nt from"node:os";var ao="remote:org",tt=ve.filter(e=>!Ee.includes(e)),ot=["TANSR_OFFLINE","TANSR_ALLOW_ROOT_BYPASS"],rt=[{env:"TANSR_LANG",keyPath:"locale"},{env:"TANSR_EFFORT",keyPath:"effort"},{env:"TANSR_OUTPUT_STYLE",keyPath:"outputStyle"},{env:"TANSR_SANDBOX",keyPath:"sandbox.mode"},{env:"TANSR_AUDIT",keyPath:"audit.enabled"},{env:"TANSR_AUDIT_DIR",keyPath:"audit.dir"},{env:"TANSR_SEMANTIC_INDEX_URL",keyPath:"semanticIndex.url"},{env:"TANSR_SEMANTIC_INDEX_REPO",keyPath:"semanticIndex.repoId"},{env:"TANSR_SEMANTIC_INDEX_BRANCH",keyPath:"semanticIndex.branch"},{env:"TANSR_SEMANTIC_INDEX_TIMEOUT_MS",keyPath:"semanticIndex.timeoutMs"},{env:"TANSR_UPDATE_CHANNEL",keyPath:"update.channel"},{env:"TANSR_UPDATE_PINNED_VERSION",keyPath:"update.pinnedVersion"},{env:"TANSR_UPDATE_MANIFEST_URL",keyPath:"update.manifestUrl"},{env:"TANSR_NO_UPDATE_CHECK",keyPath:"update.checkEnabled"}],qe=[{option:"lang",flag:"--lang",keyPath:"locale"},{option:"effort",flag:"--effort",keyPath:"effort"},{option:"outputStyle",flag:"--output-style",keyPath:"outputStyle"},{option:"maxBudgetUsd",flag:"--max-budget-usd",keyPath:"budget.maxUsd"},{option:"model",flag:"--model",keyPath:"model.selected"},{option:"theme",flag:"--theme",keyPath:"ui.theme"},{option:"contextScheme",flag:"--context-scheme",keyPath:"context.activeScheme"}];function co(e){return qe.filter(n=>e[n.option]!==void 0).map(n=>({flag:n.flag,keyPath:n.keyPath}))}function uo(e,n){if(e===void 0||e.suppressedFlags.length===0)return n;let t={...n};for(let o of qe)n[o.option]!==void 0&&e.suppressedFlags.includes(o.flag)&&delete t[o.option];return t}var ae=[];function Qe(e){ae=e}function fo(){let e=ae;return ae=[],e}var it="TANSR_ESCAPE_LOCAL";function H(e){return e[it]==="1"}var en="mode.localProviders",ce={active:"cli.escape.active",pruned:"cli.escape.pruned"};function nn(e){if(e===null)return!1;let n=O(en);if(e.shadow.some(o=>I(n,O(o))))return!1;let t=e.values.mode;return E(t)?t.localProviders===!0:!1}async function tn(e){if(H(e.env))return null;let n=e.readFile??(i=>et(i,"utf8")),t=e.homedir??nt.homedir(),o;try{let i=JSON.parse(await n(Se(e.env,t))),a=typeof i.keyId=="string"&&i.keyId!==""?i.keyId:typeof i.derivedApp?.keyId=="string"&&i.derivedApp.keyId!==""?i.derivedApp.keyId:null;if(a===null)return null;o=a}catch{return null}return(await se(Ze(e.env,o,t),Ne(e.env),n))?.bundle.settings??null}var G=new Set(["__proto__","constructor","prototype"]),lt=["site."];function st(e){return lt.some(n=>e===n.slice(0,-1)||e.startsWith(n))}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function O(e){return e.split(".")}function I(e,n){return n.length>e.length?!1:n.every((t,o)=>t===e[o])}function ze(e,n){return n.length<=e.length?!1:e.every((t,o)=>t===n[o])}function Xe(e,n){return I(e,n)||I(n,e)}function on(e,n){if(E(e)&&E(n)){let t={};for(let o of Object.keys(e))G.has(o)||(t[o]=e[o]);for(let o of Object.keys(n))G.has(o)||(t[o]=Object.prototype.hasOwnProperty.call(t,o)?on(t[o],n[o]):n[o]);return t}return n}function A(e,n){let t=e;for(let o of n){if(!E(t)||!Object.prototype.hasOwnProperty.call(t,o))return!1;t=t[o]}return!0}function Je(e,n,t){let o=e;for(let r=0;r<n.length-1;r++){let i=n[r];E(o[i])||(o[i]={}),o=o[i]}o[n[n.length-1]]=t}function de(e,n){if(n.length===0)return;let t=[e],o=e;for(let r=0;r<n.length-1;r++){let i=o[n[r]];if(!E(i))return;o=i,t.push(o)}delete o[n[n.length-1]];for(let r=t.length-1;r>0&&Object.keys(t[r]).length===0;r--)delete t[r-1][n[r-1]]}function dt(e,n){let t=[],o=e;for(let r=0;r<n.length;r++){let i=n[r];if(typeof i=="number")return t;t.push(i);let a=E(o)?o[i]:void 0;if(Array.isArray(a)&&r<n.length-1||typeof n[r+1]=="number")return t;o=a}return t}function rn(e,n,t){if(E(e)){let o=Object.keys(e);if(o.length>0){for(let r of o)rn(e[r],[...n,r],t);return}}n.length>0&&t.push(n)}var at=16;function ct(e,n,t){return n===void 0||!t.locked&&!t.unlocked||!t.locked&&e.allowedAuthEnvVarsLayer==="managed"?e:{...e,allowedAuthEnvVars:[...n],allowedAuthEnvVarsLayer:"remote"}}function L(e,n){return!n.locked&&!n.unlocked?!1:n.locked?!0:e!=="managed"}function ut(e,n,t){if(n===void 0)return e;let o=e;return n.mode!==void 0&&L(e.modeLayer,t("mode"))&&(o={...o,mode:n.mode,modeLayer:"remote"}),n.allowWrite!==void 0&&L(e.allowWriteLayer,t("allowWrite"))&&(o={...o,allowWrite:[...n.allowWrite],allowWriteLayer:"remote"}),n.network!==void 0&&L(e.networkLayer,t("network"))&&(o={...o,network:n.network,networkLayer:"remote"}),o}function ft(e,n,t){if(n===void 0)return e;let o=e;return n.manifestUrl!==void 0&&L(e.manifestUrlLayer,t("manifestUrl"))&&(o={...o,manifestUrl:n.manifestUrl,manifestUrlLayer:"remote"}),n.channel!==void 0&&L(e.channelLayer,t("channel"))&&(o={...o,channel:n.channel,channelLayer:"remote"}),n.pinnedVersion!==void 0&&L(e.pinnedVersionLayer,t("pinnedVersion"))&&(o={...o,pinnedVersion:n.pinnedVersion,pinnedVersionLayer:"remote"}),n.checkEnabled!==void 0&&L(e.checkEnabledLayer,t("checkEnabled"))&&(o={...o,checkEnabled:n.checkEnabled,checkEnabledLayer:"remote"}),o}function ln(e){let n=[],t=new Set,o=(d,u)=>{let g=`${d}|${JSON.stringify(u??{})}`;t.has(g)||(t.add(g),n.push(u!==void 0?{key:d,params:u}:{key:d}))},r=d=>(o(R.settingsDiscarded,{detail:d}),{loaded:e.merged,applied:null,notices:n}),i=structuredClone(e.settings.values);for(let d of tt)Object.prototype.hasOwnProperty.call(i,d)&&(delete i[d],o(R.settingsSectionIgnored,{section:d}));de(i,O(en));let a=e.settings.locks.map(O),c=e.settings.shadow.map(O),s={},l={},p=[],b=(d,u)=>{if(!G.has(u[u.length-1]??"")){if(c.some(g=>I(u,g))){p.push(u);return}if(E(d)&&(c.some(g=>ze(u,g))||a.some(g=>ze(u,g)))){for(let g of Object.keys(d))G.has(g)||b(d[g],[...u,g]);return}if(a.some(g=>I(u,g))){Je(s,u,d);return}Je(l,u,d)}};for(let d of Object.keys(i))G.has(d)||b(i[d],[d]);let S=[];for(let d=e.layers.length-1;d>=0;d--){let u=e.layers[d];u.layer==="managed"&&S.push(l),S.push(u.raw)}S.includes(l)||S.push(l),S.push(s);let m=null;for(let d=0;d<at&&m===null;d++){let u={};for(let k of S)u=on(u,k);let g=ke.safeParse(structuredClone(u));if(g.success){m=g.data;break}let h=!1;for(let k of g.error.issues){let kn=k.code==="invalid_type"&&k.received==="undefined"?k.path.slice(0,-1):k.path,j=dt(u,kn);if(j.length===0)return r("unusable");let ye=A(s,j)?s:A(l,j)?l:null;ye!==null&&(o(R.settingsKeyInvalid,{path:j.join(".")}),de(ye,j),h=!0)}if(!h)return r("not_converging")}if(m===null)return r("not_converging");for(let d of[s,l]){let u=[];rn(d,[],u);for(let g of u){if(A(m,g))continue;let h=g.join(".");st(h)||o(R.settingsKeyUnknown,{path:h}),de(d,g)}}let y=a.filter(d=>A(s,d));for(let d of y){let u=e.layers.filter(h=>h.layer!=="builtin"&&A(h.raw,d)).map(h=>h.layer),g=[[[Q,"allowedAuthEnvVars"],e.merged.http.allowedAuthEnvVarsLayer],[[U,"mode"],e.merged.sandbox.modeLayer],[[U,"allowWrite"],e.merged.sandbox.allowWriteLayer],[[U,"network"],e.merged.sandbox.networkLayer],[[C,"channel"],e.merged.update.channelLayer],[[C,"pinnedVersion"],e.merged.update.pinnedVersionLayer],[[C,"manifestUrl"],e.merged.update.manifestUrlLayer],[[C,"checkEnabled"],e.merged.update.checkEnabledLayer]];for(let[h,k]of g)k!==void 0&&k!=="remote"&&I(h,d)&&A(s,h)&&!u.includes(k)&&u.push(k);u.length>0&&o(R.settingsLockedLocalIgnored,{path:d.join("."),layers:u.join(", ")})}for(let d of rt){if(ot.includes(d.env))continue;let u=e.env[d.env];if(u===void 0||u.trim()==="")continue;let g=O(d.keyPath);y.some(h=>Xe(h,g))&&(delete e.env[d.env],o(R.settingsLockedEnvIgnored,{env:d.env,path:d.keyPath}))}let T=[];for(let d of e.flags??[]){let u=O(d.keyPath);y.some(g=>Xe(g,u))&&(T.push(d.flag),o(R.settingsLockedFlagIgnored,{flag:d.flag,path:d.keyPath}))}T.sort();for(let d of p)o(R.settingsShadowObserving,{path:d.join(".")});let{permissions:x,hooks:N,mcpServers:K,policy:B,workspaceTrust:F,memory:D}=e.merged,{permissions:w,hooks:Y,mcpServers:v,policy:un,workspaceTrust:fn,http:gn,sandbox:me,update:Et,...pn}=m,X=d=>u=>({locked:A(s,[d,u]),unlocked:A(l,[d,u])}),mn=ct(e.merged.http,m.http?.allowedAuthEnvVars,X(Q)("allowedAuthEnvVars")),yn=ut(e.merged.sandbox,m.sandbox,X(U)),hn=ft(e.merged.update,m.update,X(C)),Rn={...pn,permissions:x,hooks:N,mcpServers:K,policy:B,workspaceTrust:F,memory:D,http:mn,sandbox:yn,update:hn},Sn=Object.keys(s).length>0,bn=Object.keys(l).length>0;return!Sn&&!bn&&p.length===0?{loaded:e.merged,applied:null,notices:n}:{loaded:Rn,applied:{locks:y.map(d=>d.join(".")).sort(),shadow:p.map(d=>d.join(".")).sort(),origins:e.settings.origins,appliedLocked:s,appliedUnlocked:l,suppressedFlags:T},notices:n}}import{existsSync as gt,mkdirSync as pt,readFileSync as mt,writeFileSync as sn}from"node:fs";import{readFile as yt}from"node:fs/promises";import an from"node:os";import fe from"node:path";function ht(e,n){let t=e.TANSR_CONFIG_DIR?.trim();return t!==void 0&&t!==""?t:fe.join(n,".tansr")}function cn(e){let n;try{n=JSON.parse(e)}catch{return{}}if(typeof n!="object"||n===null||Array.isArray(n))return{};let t=n,o={},r=t.model;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let a=r.selected;typeof a=="string"&&a.trim()!==""&&(o.model={selected:a})}let i=t.window;if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let a=i.byModel;if(typeof a=="object"&&a!==null&&!Array.isArray(a)){let c={};for(let[s,l]of Object.entries(a))typeof l=="number"&&Number.isFinite(l)&&l>0&&(c[s]=l);Object.keys(c).length>0&&(o.window={byModel:c})}}return o}async function ge(e){let n=e.homedir??an.homedir(),t=P(e.env,n);if(t===null)return null;let o=e.readFile??(i=>yt(i,"utf8")),r;try{r=await o(t.configFile)}catch{return{config:{},filePath:t.configFile}}return{config:cn(r),filePath:t.configFile}}function dn(e){let n;try{n=mt(e,"utf8")}catch{return null}try{let t=JSON.parse(n);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}function ue(e){let n=e?.model;if(typeof n!="object"||n===null||Array.isArray(n))return;let t=n.selected;return typeof t=="string"&&t.trim()!==""?t:void 0}function Rt(e){let n=e?.window;if(typeof n!="object"||n===null||Array.isArray(n))return{};let t=n.byModel;if(typeof t!="object"||t===null||Array.isArray(t))return{};let o={};for(let[r,i]of Object.entries(t))typeof i=="number"&&Number.isFinite(i)&&i>0&&(o[r]=i);return o}function pe(e){try{let n=e.homedir??an.homedir(),t=P(e.env,n);if(t===null||gt(t.configFile))return!1;let o=ht(e.env,n),r=fe.join(o,"settings.local.json"),i=fe.join(o,"settings.json"),a=dn(r),c=dn(i),s=ue(a)??ue(c),l=Rt(a);if(s===void 0&&Object.keys(l).length===0)return!1;let p={...s!==void 0?{model:{selected:s}}:{},...Object.keys(l).length>0?{window:{byModel:l}}:{}};if(pt(t.root,{recursive:!0,mode:J}),sn(t.configFile,`${JSON.stringify(p,null,2)}
|
|
6
|
-
`,{encoding:"utf8",mode:q}),c!==null&&ue(c)!==void 0)try{let b=c.model;delete b.selected,Object.keys(b).length===0&&delete c.model,sn(i,`${JSON.stringify(c,null,2)}
|
|
7
|
-
`,"utf8")}catch{}return!0}catch{return!1}}var St="cli.init.guide.uninited";function nr(e){return e.gate.escape||e.remoteEnabled?{key:Ie.noProvider}:{key:St,params:{url:he(e.env)}}}function _(e,n){let t=e;for(let o of n){if(typeof t!="object"||t===null||Array.isArray(t)||!Object.prototype.hasOwnProperty.call(t,o))return!1;t=t[o]}return!0}var z=["model","selected"],bt=["modelAliases","main"];function kt(e,n,t){let o=n.some(a=>(a.layer==="projectLocal"||a.layer==="projectShared")&&_(a.raw,bt)),r=e.model?.selected;if(r===void 0)return{projectPinnedMain:o};let i=(()=>{if(t!==null&&_(t.appliedLocked,z))return"remote:org";let a=!1;for(let c of n){if(!a&&c.layer!=="managed"&&(a=!0,t!==null&&_(t.appliedUnlocked,z)))return"remote:org";if(_(c.raw,z))return c.layer}if(!a&&t!==null&&_(t.appliedUnlocked,z))return"remote:org"})();return{selected:r,...i!==void 0?{layer:i}:{},projectPinnedMain:o}}function vt(e){let{loaded:n,modelSelection:t}=e,o=e.identity.model?.selected;o!==void 0&&(t.layer===void 0||t.layer==="user")&&(n={...n,model:{...n.model,selected:o}},t={selected:o,layer:"identity",projectPinnedMain:t.projectPinnedMain});let r=e.identity.window?.byModel;if(r!==void 0){let i=c=>{let s=["window","byModel",c];return e.remote!==null&&(_(e.remote.appliedLocked,s)||_(e.remote.appliedUnlocked,s))?!0:e.layers.some(l=>(l.layer==="managed"||l.layer==="projectLocal"||l.layer==="projectShared")&&_(l.raw,s))},a={};for(let[c,s]of Object.entries(r))i(c)||(a[c]=s);Object.keys(a).length>0&&(n={...n,window:{...n.window,byModel:{...n.window?.byModel,...a}}})}return{loaded:n,modelSelection:t}}async function tr(e={}){let n=e.env??process.env,t=e.loadOptions?.fs,o=H(n)?null:e.remoteSettingsOverride!==void 0?e.remoteSettingsOverride:await tn({env:n,...e.loadOptions?.homedir!==void 0?{homedir:e.loadOptions.homedir}:{},...t!==void 0?{readFile:v=>t.readFile(v)}:{}}),{config:r,diagnostics:i,sources:a,layers:c}=await Ae({cwd:e.cwd??process.cwd(),env:n,...e.loadOptions??{},captureLayers:!0}),s=e.loadOptions?.captureLayers===!0&&c!==void 0?{layers:c}:{},l=r,p=null,b=[];if(o!==null){let v=ln({merged:r,layers:c??[],settings:o,env:n,...e.flagOverrides!==void 0?{flags:e.flagOverrides}:{}});l=v.loaded,p=v.applied,b=v.notices}let S=p!==null?{remoteSettings:p}:{},m=kt(l,c??[],p);t===void 0&&pe({env:n,...e.loadOptions?.homedir!==void 0?{homedir:e.loadOptions.homedir}:{}});let y=await ge({env:n,...e.loadOptions?.homedir!==void 0?{homedir:e.loadOptions.homedir}:{},...t!==void 0?{readFile:v=>t.readFile(v)}:{}}),T=y!==null&&(y.config.model!==void 0||y.config.window!==void 0);y!==null&&({loaded:l,modelSelection:m}=vt({loaded:l,modelSelection:m,identity:y.config,layers:c??[],remote:p}));let x=T?{identitySettings:{filePath:y.filePath,values:y.config}}:{},N=H(n),K=nn(o),B=N||K,F=Object.keys(l.providers).length>0,D=F?null:We(n),w={escape:N,platformAllowed:K,pruned:B?null:F?"config":D!==null?"env":null},Y=[];if(N&&Y.push({key:ce.active}),w.pruned!==null&&Y.push({key:ce.pruned}),Qe([...b,...Y]),F&&B){let{policy:v,workspaceTrust:un,sandbox:fn,update:gn,...me}=l;return{loaded:l,diagnostics:i,sources:a,providerOrigin:"config",registryConfig:me,localProviders:w,modelSelection:m,...s,...S,...x}}return D!==null&&B?{loaded:l,diagnostics:i,sources:a,providerOrigin:"env",registryConfig:D,localProviders:w,modelSelection:m,...s,...S,...x}:{loaded:l,diagnostics:i,sources:a,providerOrigin:"none",registryConfig:null,localProviders:w,modelSelection:m,...s,...S,...x}}export{M as a,je as b,vn as c,Be as d,Ve as e,Lt as f,Ct as g,Mt as h,It as i,Ut as j,Vt as k,Ze as l,Xt as m,se as n,Qn as o,Jt as p,ao as q,co as r,uo as s,fo as t,H as u,ce as v,nr as w,tr as x};
|
|
8
|
-
//# sourceMappingURL=tansr-chunk-WGXWBU37.mjs.map
|
package/tansr-chunk-ZQ3ZK7IL.mjs
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{N as ye,a as St,c as kt,g as vt,j as ge,l as Z}from"./tansr-chunk-I3TOVAA6.mjs";import{Ab as Rt,Eb as Se,Fb as Ae,xb as It}from"./tansr-chunk-QWGSXFEJ.mjs";import{createHash as Un}from"node:crypto";import{types as $n}from"node:util";var ie=class extends Error{constructor(n){super(`Material supply: ${n}`);this.code=n;this.name="MaterialSupplyError"}code};var We="sdk2-material-supply-v1",wt=16384,Kn=67108864,B=e=>Un("sha256").update(e).digest("hex"),oe=e=>Buffer.from(St(e)).toString("utf8"),J=(e,t)=>oe(e)===oe(t),Et=B(new Uint8Array);function v(){throw new ie("integrity_mismatch")}function X(e){return(!e||typeof e!="object"||Array.isArray(e))&&v(),e}function K(e,t,n=[]){(t.some(r=>!Object.hasOwn(e,r))||Object.keys(e).some(r=>!t.includes(r)&&!n.includes(r)))&&v()}function $(e){(typeof e!="string"||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/.test(e))&&v()}function Pe(e){(typeof e!="string"||!/^[a-f0-9]{64}$/.test(e))&&v()}function te(e,t,n){(typeof e!="number"||!Number.isSafeInteger(e)||Object.is(e,-0)||e<t||e>n)&&v()}function He(e,t,n=0){(!Array.isArray(e)||e.length<n||e.length>t)&&v();for(let r of e)$(r);new Set(e).size!==e.length&&v()}function _t(e){if(e&&typeof e=="object"){for(let t of Object.values(e))_t(t);Object.freeze(e)}return e}function je(e,t=new Set,n=new Set){if((typeof e=="function"||typeof e=="symbol"||typeof e=="bigint"||e===void 0)&&v(),!e||typeof e!="object"||(($n.isProxy(e)||t.has(e))&&v(),n.has(e)))return;let r=Object.getPrototypeOf(e);r!==Object.prototype&&r!==null&&r!==Array.prototype&&v(),t.add(e);for(let o of Reflect.ownKeys(e)){typeof o!="string"&&v();let s=Object.getOwnPropertyDescriptor(e,o);(!("value"in s)||!s.enumerable&&!(Array.isArray(e)&&o==="length"))&&v(),je(s.value,t,n)}Array.isArray(e)&&Object.keys(e).some((o,s)=>o!==String(s))&&v(),Array.isArray(e)&&Object.keys(e).length!==e.length&&v(),t.delete(e),n.add(e)}function Gn(e,t,n=new Uint8Array){return{entryId:e,basket:"original",metadata:oe(t),body:n}}function zn(e){return Gn("ms-close",{format:We,bindingId:e,kind:"close"})}function At(e,t){let n=`material-state:${B(e)}:${t}`;return{key:n,entryId:`ms-state-${B(n)}`,intentDigest:B(n),bytes:8192}}function ne(e,t){let n=`material-${t}:${B(e)}`;return{key:n,entryId:`ms-${t}-${B(e)}`,intentDigest:B(n),bytes:2048}}function Mt(e,t,n,r,o){let s=`material-slot:${B(oe([t,n.artifactId,r]))}`,i=`ms-slot-${B(s)}`,c=oe({format:We,bindingId:e,kind:"slot",materialRequestId:t,artifact:n,offset:r,bytes:Math.min(o,n.bytes-r)});return{key:s,entryId:i,metadata:c,intentDigest:B(c),bytes:Math.min(o,n.bytes-r)}}function Ct(e,t=e){let n=zn(t);return{bindingId:e,operationKey:"material-close",intentDigest:B(oe([[n.entryId,n.metadata,Et]])),originalMax:{bytes:Buffer.byteLength(n.metadata)+64,records:1},terminalReserve:{bytes:1,records:1}}}function Hn(e,t){$(e);let n=0;if(t.length>wt)throw new ie("capacity_exceeded");let r=[],o=new Map,s=new Map;for(let i of t){if(je(i),K(X(i),["entryId","basket","metadata","metadataBytes","bodyBytes","bodySha256","logicalBytes"]),te(i.metadataBytes,0,262144),te(i.bodyBytes,0,33554432),te(i.logicalBytes,64,33816640),(i.logicalBytes!==i.metadataBytes+i.bodyBytes+64||typeof i.metadata!="string")&&v(),n+=i.metadataBytes,r.length>=wt||n>Kn)throw new ie("capacity_exceeded");(i.metadataBytes!==Buffer.byteLength(i.metadata)||i.basket!=="original"||o.has(i.entryId))&&v();let c=X(kt(Buffer.from(i.metadata)));(c.format!==We||c.bindingId!==e)&&v();let l=["format","bindingId","kind"],g;switch(c.kind){case"close":K(c,l),g="ms-close";break;case"issue":{K(c,[...l,"spec","target","sourceId","sourceGeneration","issuedAtMs","deadlineMs","records"]);let a=X(c.spec);K(a,["materialRequestId","recordIds","purpose","lifetimeMs","maxBytes","chunkBytes"]),$(a.materialRequestId),He(a.recordIds,32,1),$(c.sourceId),$(c.sourceGeneration),a.purpose!=="context-recall"&&a.purpose!=="projection-verification"&&v(),te(a.lifetimeMs,1,3e4),te(a.maxBytes,1024,1048576),te(a.chunkBytes,1,65536),te(c.issuedAtMs,0,Number.MAX_SAFE_INTEGER),te(c.deadlineMs,1,Number.MAX_SAFE_INTEGER),(c.deadlineMs!==c.issuedAtMs+a.lifetimeMs||!Array.isArray(c.records)||c.records.length!==a.recordIds.length)&&v();let u=X(c.target);K(u,["sessionId","generations","sourceSnapshotDigest"]),Pe(u.sourceSnapshotDigest);for(let[y,h]of c.records.entries()){let f=vt(h);(f.recordId!==a.recordIds[y]||f.target.sessionId!==u.sessionId||!J(f.target.generations,u.generations)||f.attachments.length>32)&&v()}g=`ms-issue-${B(a.materialRequestId)}`;break}case"ready":K(c,[...l,"materialRequestId"]),$(c.materialRequestId),g=`ms-ready-${B(c.materialRequestId)}`;break;case"state":{K(c,[...l,"receipt"],["response"]);let a=X(c.receipt);if(K(a,["protocol","bindingId","materialRequestId","state","revision","acceptedRecordIds"],["reason"]),(a.protocol!=="sdk2-ext-v1"||a.bindingId!==e||!["received","verified","core-consumed","rejected"].includes(a.state))&&v(),$(a.materialRequestId),He(a.acceptedRecordIds,32),["1","2","3"].includes(a.revision)||v(),a.state==="rejected"?["source_unavailable","stale_generation","invalid_coverage","request_expired","material_rejected","forbidden","binding_closed"].includes(a.reason)||v():(Object.hasOwn(a,"reason")||a.acceptedRecordIds.length===0)&&v(),c.response!==void 0){let u=X(c.response);K(u,["request","semanticDigest"]),Pe(u.semanticDigest);let y=X(u.request);K(y,["requestId","operationEpoch"]),$(y.requestId),$(y.operationEpoch),a.state!=="received"&&v()}else a.state==="received"&&v();g=At(a.materialRequestId,a.revision).entryId;break}case"slot":{K(c,[...l,"materialRequestId","artifact","offset","bytes"]),$(c.materialRequestId);let a=X(c.artifact);K(a,["artifactId","sourceId","bytes","sha256","mediaType"]),$(a.artifactId),$(a.sourceId),Pe(a.sha256),te(a.bytes,1,33554432),te(c.offset,0,a.bytes-1),te(c.bytes,1,65536);let u=`material-slot:${B(oe([c.materialRequestId,a.artifactId,c.offset]))}`;i.bodyBytes!==c.bytes&&v(),g=`ms-slot-${B(u)}`;break}case"lease":K(c,[...l,"leaseId","materialRequestId","entryIds"]),$(c.leaseId),$(c.materialRequestId),He(c.entryIds,16896,1),g=`ms-lease-${B(c.leaseId)}`;break;case"held":case"release":K(c,[...l,"leaseId"]),$(c.leaseId),g=ne(c.leaseId,c.kind).entryId;break;case"delivery-intent":K(c,[...l,"leaseId","claimId"]),$(c.leaseId),$(c.claimId),g=ne(c.leaseId,"delivery").entryId;break;case"delivery-outcome":K(c,[...l,"leaseId","operationKey","outcome"]),$(c.leaseId),$(c.operationKey),c.outcome!=="consumed"&&c.outcome!=="not-consumed"&&v(),g=ne(c.leaseId,"outcome").entryId;break;default:v()}Pe(i.bodySha256),(i.entryId!==g||c.kind!=="slot"&&(i.bodyBytes!==0||i.bodySha256!==Et))&&v();let d=_t({entryId:i.entryId,value:c});if(r.push(d),o.set(d.entryId,d),c.kind==="state"){let a=c.receipt.materialRequestId,u=s.get(a)??[];u.push(d),s.set(a,u)}}for(let i of s.values())i.sort((c,l)=>Number(c.value.receipt.revision)-Number(l.value.receipt.revision));return Object.freeze({rows:Object.freeze(r),get:i=>o.get(i),events:i=>Object.freeze([...s.get(i)??[]])})}function Tt(e,t,n){let r=e.get(`ms-issue-${B(n)}`);if(!r||r.value.kind!=="issue")throw new ie("source_unavailable");let o=e.events(n);for(let[s,i]of o.entries())i.value.receipt.revision!==String(s+1)&&v();return o.at(-1)?.value.receipt??{protocol:"sdk2-ext-v1",bindingId:t,materialRequestId:n,state:"pending",revision:"0",acceptedRecordIds:[]}}function Ot(e,t,n){let r=e.get(`ms-lease-${B(t)}`)?.value,o=e.get(ne(t,"release").entryId);if(!r&&!o&&!n)return null;let s=e.get(ne(t,"outcome").entryId)?.value;return{leaseId:t,materialRequestId:r?.materialRequestId??null,state:o?"released":e.get(ne(t,"held").entryId)?"held":"preparing",delivery:s?s.outcome:e.get(ne(t,"delivery").entryId)?"pending":"unclaimed",outcomeOperationKey:s?s.operationKey:null}}function Ao(e,t){return Pt(e,t)}function Po(e,t,n){return Pt(e,t,n)}function Pt(e,t,n){let r=o=>({kind:"blocked",reason:o});try{if(je(e),je(t),K(X(e),["bindingId","entries","operations","holds"],["protocolBindingId"]),(!Array.isArray(e.entries)||!Array.isArray(e.operations)||!Array.isArray(e.holds))&&v(),$(e.bindingId),t.bindingId!==e.bindingId||t.operationKey!=="material-close")return r("not-material-close");let o=e.protocolBindingId??e.bindingId;$(o);let s=Ct(e.bindingId,o),i=J(t,s)?o:e.bindingId,c=Ct(e.bindingId,i);if(!J(t,c))return r("reservation-mismatch");let l=Hn(i,e.entries.map(m=>m.witness));if(e.holds.some(m=>m.state==="held"))return r("held");let g=new Map,d=new Map;for(let m of e.entries)K(X(m),["operationKey","witness","bodyState"]),(d.has(m.witness.entryId)||!["retained","released"].includes(m.bodyState))&&v(),d.set(m.witness.entryId,m);for(let m of e.operations){K(X(m),m.state==="committed"?["state","reservation","receipt"]:["state","reservation"]);let b=m.reservation.operationKey;if((m.reservation.bindingId!==e.bindingId||g.has(b))&&v(),g.set(b,m),m.state==="reserved"&&b!=="material-close"&&n===void 0)return r("other-pending");if(m.state!=="reserved"&&m.state!=="committed"&&v(),m.state==="committed"){K(X(m.receipt),["bindingId","operationKey","state","intentDigest","commitDigest","entries"]),(m.receipt.state!=="committed"||!Array.isArray(m.receipt.entries))&&v(),(m.receipt.bindingId!==e.bindingId||m.receipt.operationKey!==b||m.receipt.intentDigest!==m.reservation.intentDigest)&&v(),B(JSON.stringify(m.receipt.entries.map(I=>[I.entryId,I.basket,I.metadata,I.bodyBytes,I.bodySha256])))!==m.receipt.commitDigest&&v();for(let I of m.receipt.entries){let x=d.get(I.entryId);(!x||x.operationKey!==b||!J(x.witness,I))&&v()}}}let a=g.get("material-close");if(a?.state!=="reserved"||!J(a.reservation,c)||l.get("ms-close"))return r("reservation-mismatch");let u=new Set(["material-close"]),y=(m,b,p,I=!1)=>{u.add(m);let x=g.get(m);(!x||x.state!=="committed"||!J(x.reservation,b))&&v(),p&&d.has(p)?(x.receipt.entries.length!==1||x.receipt.entries[0].entryId!==p)&&v():(!I||x.receipt.entries.length!==0)&&v()},h=(m,b)=>{u.add(m);let p=g.get(m);(!p||p.state!=="reserved"||!J(p.reservation,b))&&v()},f=(m,b,p)=>({bindingId:e.bindingId,operationKey:m,intentDigest:b,originalMax:{bytes:p,records:1},terminalReserve:{bytes:1,records:1}}),S=(m,b)=>{let p=d.get(b);p||v(),y(m,f(m,B(oe([[b,p.witness.metadata,p.witness.bodySha256]])),p.witness.logicalBytes),b)},T=l.rows.filter(m=>m.value.kind==="issue");if(!T.length)return r("issue-unfinished");let P=new Map,_=new Set,D=new Set;for(let m of T){let b=m.value.spec,p=b.materialRequestId;if(_.add(p),S(`material-issue:${B(p)}`,m.entryId),!l.get(`ms-ready-${B(p)}`))return r("issue-unfinished");S(`material-ready:${B(p)}`,`ms-ready-${B(p)}`);let I=Tt(l,i,p),x=n!==void 0&&I.state==="received",w=n!==void 0&&I.state==="core-consumed"&&l.rows.some(C=>C.value.kind==="slot"&&C.value.materialRequestId===p&&d.get(C.entryId)?.bodyState==="retained");if(x){if(n.bindingId!==e.bindingId||n.state!=="active"||!J(m.value.target,n.target)||m.value.sourceId!==n.sourceId||m.value.sourceGeneration!==n.sourceGeneration)return r("request-active");D.add(p)}else if(I.state!=="rejected"&&I.state!=="core-consumed")return r("request-active");if(w){let C=X(m.value.target);if(n.bindingId!==e.bindingId||n.state!=="active"||C.sessionId!==n.target.sessionId||!J(C.generations,n.target.generations)||m.value.sourceId!==n.sourceId||m.value.sourceGeneration!==n.sourceGeneration)return r("request-active")}let R="pending",A=[];for(let C of l.events(p)){let M=C.value.receipt;if((R==="rejected"||R==="core-consumed")&&v(),M.state==="received"){if((R!=="pending"||!J(b.recordIds.filter(U=>M.acceptedRecordIds.includes(U)),M.acceptedRecordIds))&&v(),A=M.acceptedRecordIds,x&&!n.operationEpochIds.includes(C.value.response.request.operationEpoch))return r("request-active")}else(!J(A,M.acceptedRecordIds)||M.state==="verified"&&R!=="received"||M.state==="core-consumed"&&R!=="verified")&&v();R=M.state}for(let C=1;C<=3;C++){let M=At(p,C);x&&C>1?h(M.key,f(M.key,M.intentDigest,M.bytes)):y(M.key,f(M.key,M.intentDigest,M.bytes),M.entryId,!x)}let j=new Map,F=0,E=[],N=new Set(m.value.records.filter(C=>A.includes(C.recordId)).flatMap(C=>[C.payload,...C.attachments].map(M=>M.artifactId)));for(let C of m.value.records)for(let M of[C.payload,...C.attachments]){M.sourceId!==m.value.sourceId&&v();let U=j.get(M.artifactId);if(U){J(U,M)||v();continue}j.set(M.artifactId,M),F+=M.bytes,(F>b.maxBytes||Math.ceil(M.bytes/b.chunkBytes)>16)&&v();for(let W=0;W<M.bytes;W+=b.chunkBytes){let Y=Mt(i,p,M,W,b.chunkBytes),pe=d.get(Y.entryId),Ee=f(Y.key,Y.intentDigest,Buffer.byteLength(Y.metadata)+Y.bytes+64);if(x&&!pe&&!N.has(M.artifactId)?h(Y.key,Ee):y(Y.key,Ee,Y.entryId,!x),pe&&(pe.witness.metadata!==Y.metadata||!w&&pe.bodyState!==(x?"retained":"released")))return r("inventory-invalid")}}let L=new Set;for(let C of m.value.records)if(A.includes(C.recordId)){for(let M of[C.payload,...C.attachments])if(!L.has(M.artifactId)){L.add(M.artifactId);for(let U=0;U<M.bytes;U+=b.chunkBytes)E.push(Mt(i,p,M,U,b.chunkBytes).entryId)}}P.set(p,E)}let k=new Map;for(let m of l.rows.filter(b=>b.value.kind==="lease")){let b=m.value.leaseId,p=m.value.materialRequestId,I=m.value.entryIds;if(D.has(p))return r("lease-unreleased");J(I,P.get(p)??null)||v(),k.set(b,I),S(`material-lease:${B(b)}`,m.entryId);let x=Ot(l,b,!0);if(x.state!=="released"||!l.get(ne(b,"held").entryId))return r("lease-unreleased");if(x.delivery==="pending")return r("delivery-unresolved");l.get(ne(b,"outcome").entryId)&&!l.get(ne(b,"delivery").entryId)&&v();for(let w of["held","delivery","outcome","release"]){let R=ne(b,w);y(R.key,f(R.key,R.intentDigest,R.bytes),R.entryId,w==="delivery"||w==="outcome")}}for(let m of l.rows){let b=m.value;["held","release","delivery-intent","delivery-outcome"].includes(b.kind)&&!k.has(b.leaseId)&&v(),["ready","slot"].includes(b.kind)&&!_.has(b.materialRequestId)&&v(),b.kind==="state"&&!_.has(b.receipt.materialRequestId)&&v();let p=d.get(m.entryId),I=g.get(p.operationKey);(!I||I.state!=="committed"||!I.receipt.entries.some(x=>x.entryId===m.entryId))&&v()}let O=new Set;for(let m of e.holds)K(X(m),["bindingId","entryId","token","state"]),(m.bindingId!==e.bindingId||m.state!=="released"||O.has(m.token))&&v(),O.add(m.token),[...k].some(([b,p])=>p.includes(m.entryId)&&m.token===`material-hold:${B(oe([b,m.entryId]))}`)||v();for(let[m,b]of k)for(let p of b)O.has(`material-hold:${B(oe([m,p]))}`)||v();for(let m of _)Tt(l,i,m).state==="core-consumed"&&!l.rows.some(b=>b.value.kind==="lease"&&b.value.materialRequestId===m&&Ot(l,b.value.leaseId,!0)?.delivery==="consumed")&&v();return[...g.keys()].some(m=>!u.has(m))?r("other-pending"):{kind:"recognized-close-standby",reservation:c}}catch(o){return r(o instanceof ie&&o.code==="capacity_exceeded"?"capacity-exceeded":"inventory-invalid")}}var ke=new WeakMap,ve=new WeakMap,jt=e=>new Map(Object.entries(e).filter(([,t])=>typeof t=="function"));function ae(e,t){for(let[n,r]of t)if(Object.getOwnPropertyDescriptor(e,n)?.value!==r)return!1;return!0}function No(e){let t=ve.get(e),n=t&&ke.get(t.supply);if(!t||!n||!ae(e,t.methods)||!ae(t.supply,n.methods))throw new Z("identity_mismatch");let r=n.read();if(r.state!=="active"||!r.operationEpoch.active||r.operationEpoch.expiresAtMs<=r.nowMs)throw new Z("identity_mismatch");return ye({bindingId:n.bindingId,storageBindingId:n.storageBindingId,owner:n.spool.bindingIdentity(n.storageBindingId),maximum:t.maximum,limits:n.limits,sourceId:r.sourceId,sourceGeneration:r.sourceGeneration,target:r.target})}function Do(e,t){ke.set(e,{...t,limits:{...t.limits},methods:jt(e)})}function Fo(e,t,n){ve.set(e,{supply:t,maximum:n,methods:jt(e)})}function Lo(e,t){let n=ve.get(e),r=n&&ke.get(n.supply);if(!n||!r||!ae(e,n.methods)||!ae(n.supply,r.methods))throw new Z("identity_mismatch");let o=r.read();if(o.state!=="active"||!o.operationEpoch.active||o.operationEpoch.expiresAtMs<=o.nowMs||o.sourceId!==t.source.sourceId||o.sourceGeneration!==t.source.sourceGeneration||ye(o.target.generations)!==ye(t.source.generations))throw new Z("identity_mismatch")}function Uo(e,t,n){Ve(e,t,n,n.initialTarget,["active"])}function $o(e,t,n,r){if(r.state!=="active")throw new Z("identity_mismatch");Ve(e,t,n,r.target,["active"])}function Ko(e,t,n,r,o){o&&e===void 0||(Ve(e,t,n,r.target,["closing","closed"]),e!==void 0&&Wn(e))}function Wn(e){let t=ve.get(e),n=t&&ke.get(t.supply);if(!t||!n||!ae(e,t.methods)||!ae(t.supply,n.methods))throw new Z("identity_mismatch");let r=t.methods.get("pending");if(Reflect.apply(r,e,[])!==0)throw new Z("reconciliation_required")}function Ve(e,t,n,r,o){if(n.materialBindingId===null){if(e!==void 0)throw new Z("identity_mismatch");return}let s=e===void 0?void 0:ve.get(e),i=s&&ke.get(s.supply);if(!e||!s||!i||i.spool!==t||i.bindingId!==n.bindingId||i.storageBindingId!==n.materialBindingId||!ae(e,s.methods)||!ae(s.supply,i.methods))throw new Z("identity_mismatch");let c=n.createResponse.limits;if(s.maximum<c.materialQueue||i.limits.concurrentRequests<c.materialConcurrent||i.limits.materialBytes<c.materialBytes||i.limits.chunkBytes<c.materialChunkBytes||i.limits.lifetimeMs<c.materialDeadlineMs)throw new Z("capacity_exceeded");let l=i.read();if(l.bindingId!==n.bindingId||l.sourceId!==n.sourceId||l.sourceGeneration!==n.sourceGeneration||!o.includes(l.state)||ye(l.target)!==ye(r))throw new Z("identity_mismatch")}function we(e,t=[]){let n=new Map,r=new Map;for(let[c,l]of e.entries()){let g=t[c]??l,d=l.sources?.length?l.sources:[{sourceId:g,failureCount:l.failureCount}];for(let a of d)a.failureCount>0&&n.set(a.sourceId,Math.max(n.get(a.sourceId)??0,a.failureCount));for(let a of l.failures){let u=a.sourceId??(d.length===1?d[0]?.sourceId:void 0)??g,y=r.get(u);y===void 0&&(y=new Map,r.set(u,y)),y.set(a.operationId,{...a,sourceId:u})}}let o=[...r.values()].flatMap(c=>[...c.values()]).slice(-32),s=[...n].map(([c,l])=>({sourceId:c,failureCount:l})),i=s.reduce((c,l)=>c+l.failureCount,0);return{failures:o,failureCount:i,omittedFailures:Math.max(0,i-o.length),sources:s}}var Qe=class{#r=new WeakMap;accept(t,n){let r=we([t],[n]),o=[],s=[];for(let l of r.sources??[]){let g=this.#r.get(l.sourceId)??0,d=Math.max(0,l.failureCount-g);if(d===0)continue;this.#r.set(l.sourceId,l.failureCount),s.push({sourceId:l.sourceId,failureCount:d});let a=r.failures.filter(u=>u.sourceId===l.sourceId).slice(-d);o.push(...a)}let i=s.reduce((l,g)=>l+g.failureCount,0),c=o.slice(-32);return{failures:c,failureCount:i,omittedFailures:Math.max(0,i-c.length),sources:s}}};var Je=new WeakMap,Xe=new WeakMap;function Vo(e,t){if(Xe.has(e))throw new Error("Query resource observation owner is already registered");Xe.set(e,t)}function qt(e){let t=Xe.get(e);return t===void 0?!1:(t(),!0)}function Nt(e){let t={original:e},n=o=>{t.outcome===void 0&&(t.outcome=o,t.finish?.(o))},r=Object.freeze({token:Object.freeze({})});return Je.set(r,t),Object.freeze({receipt:r,fulfilled:o=>{n(Object.freeze({status:"fulfilled"}))},rejected:o=>{n(Object.freeze({status:"rejected",reason:o}))}})}function Dt(e,t){let n=Je.get(e);if(n===void 0||!t.aborted)return;let r=t.reason;typeof r=="object"&&r!==null&&(n.cancellationReason??=r)}function Vn(e){return e.outcome!==void 0?Promise.resolve(e.outcome):(e.ended??=new Promise(t=>{e.finish=t}),e.ended)}var Bt=class{#r=Object.freeze({});#c=0;#y=!1;#h=!1;requireStrictOriginalObservation(){if(this.#y)throw new Error("Query resource observation registration is too late");this.#h=!0}#f=0;#l=0;#o=[];#n=new Set;#s=new WeakMap;#p=new Set;#u=new Set;#b=new WeakSet;#m=new Set;#x=new WeakSet;#g={failures:[],failureCount:0,omittedFailures:0,sources:[]};start(){this.#y=!0,this.#c++,this.#e()}own(t,n){if(this.#s.has(t))return;let r={generator:t,phase:n,operationId:++this.#f,closingEnded:!1,pendingNext:0,pendingObservers:0,observedNext:new WeakSet,failureReported:!1};this.#s.set(t,r),this.#n.add(r),this.#e()}track(t,n,r={}){if(this.#b.has(t))return;this.#b.add(t);let o=r.reportFailure!==!1;if(r.owner!==void 0){let i=this.#s.get(r.owner);if(i!==void 0){i.pendingObservers++,this.#n.add(i),this.#e(),Promise.resolve(t).then(()=>{i.pendingObservers--,this.#t(i)},c=>{o&&this.#i(i.operationId,n,c),i.pendingObservers--,this.#t(i)});return}}let s={operationId:++this.#f,phase:n};this.#u.add(s),this.#e(),Promise.resolve(t).then(()=>{this.#u.delete(s),this.#e()},i=>{o&&this.#i(s.operationId,n,i),this.#u.delete(s),this.#e()})}adopt(t){if(this.#x.has(t))return;this.#x.add(t);let n=++this.#f,r={};this.#m.add(r),this.#e(),Promise.resolve(t).then(async o=>{this.#g=we([this.#g,o],[this,t]),o.status==="failed"&&o.failureCount===0&&this.#i(n,"tool_executor",void 0),(o.status==="timeout"||o.status==="cancelled"||o.pending.execution+o.pending.modelStreams+o.pending.toolExecutors>0)&&await new Promise(()=>{})}).catch(o=>{this.#i(n,"tool_executor",o)}).then(()=>{this.#m.delete(r),this.#e()})}#i(t,n,r){this.#l++,this.#o.push({sourceId:this.#r,operationId:t,phase:n,cause:r}),this.#o.length>32&&this.#o.shift()}observeAbandonedNext(t,n,r){let o=this.#s.get(t);if(o===void 0||o.observedNext.has(n))return;o.observedNext.add(n),o.pendingNext++,this.#n.add(o),this.#e();let s=r===void 0?void 0:Je.get(r),i=s?.original===n?s.cancellationReason:void 0,c=g=>i!==void 0&&g===i,l;try{l=ge(n)}catch(g){if(!this.#h&&s?.original===n){Vn(s).then(d=>{d.status==="rejected"&&!c(d.reason)&&this.#d(o,d.reason),o.pendingNext--,this.#t(o)});return}this.#d(o,g),this.#e();return}l.then(()=>{o.pendingNext--,this.#t(o)},g=>{c(g)||this.#d(o,g),o.pendingNext--,this.#t(o)})}#d(t,n){t.failureReported||(t.failureReported=!0,this.#i(t.operationId,t.phase,n))}#t(t){t.closingEnded&&t.pendingNext===0&&t.pendingObservers===0&&this.#n.delete(t),this.#e()}dispose(t){let n=this.#s.get(t);n===void 0||n.closing!==void 0||(n.closing=Promise.resolve().then(async()=>{let r=await t.return(void 0);for(;!r.done;)await new Promise(o=>setImmediate(o)),r=await t.next(void 0)}).then(()=>{n.closingEnded=!0,this.#t(n)},r=>{this.#d(n,r),n.closingEnded=!0,this.#t(n)}))}finish(t={}){if(t.dispose!==!1)for(let n of this.#n)this.dispose(n.generator);this.#c=Math.max(0,this.#c-1),this.#e()}#e(){for(let t of this.#p)t()}#a(t){let n={execution:this.#c+this.#m.size,modelStreams:0,toolExecutors:0};for(let s of[...this.#n,...this.#u])s.phase==="model_stream"?n.modelStreams++:n.toolExecutors++;let r=n.execution+n.modelStreams+n.toolExecutors,o=we([{failures:this.#o,failureCount:this.#l,omittedFailures:this.#l-this.#o.length,sources:[{sourceId:this.#r,failureCount:this.#l}]},this.#g]);return{status:t??(r>0?"timeout":o.failureCount>0?"failed":"completed"),pending:n,...o}}async settle(t={}){let n=t.timeoutMs??3e4;if(!(n===1/0||Number.isFinite(n)&&n>=0))throw new TypeError("Query settle timeoutMs must be non-negative or Infinity.");let r=t.signal;if(r!==void 0&&(typeof r.aborted!="boolean"||typeof r.addEventListener!="function"||typeof r.removeEventListener!="function"))throw new TypeError("Query settle signal must be an AbortSignal.");if(r?.aborted)return this.#a("cancelled");let o=this.#a();if(o.status!=="timeout"||n===0)return o;let s=performance.now()+n;return new Promise(i=>{let c=!1,l,g=u=>{c||(c=!0,clearTimeout(l),this.#p.delete(d),r?.removeEventListener("abort",d),i(u))},d=()=>{if(r?.aborted){g(this.#a("cancelled"));return}if(performance.now()>=s){g(this.#a("timeout"));return}let u=this.#a();u.status!=="timeout"&&g(u)},a=()=>{c||s===1/0||(l=setTimeout(()=>{d(),a()},Math.min(2147483647,Math.max(0,s-performance.now()))))};this.#p.add(d),r?.addEventListener("abort",d,{once:!0}),d(),a()})}};var Ut=["png","jpg","jpeg","gif","webp"],$t={png:"image/png",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};function Qn(e){let t=e.toLowerCase().replace(/^\./,"");return Ut.includes(t)}function Ze(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?"png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"jpeg":e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56&&(e[4]===55||e[4]===57)&&e[5]===97?"gif":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":null}var Ft=(e,t)=>(e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3])>>>0,Ye=(e,t)=>e[t]<<8|e[t+1],Be=(e,t)=>e[t]|e[t+1]<<8,Lt=(e,t)=>e[t]|e[t+1]<<8|e[t+2]<<16;function Xn(e){if(e.length<24||e[12]!==73||e[13]!==72||e[14]!==68||e[15]!==82)return null;let t=Ft(e,16),n=Ft(e,20);return t>0&&n>0?{width:t,height:n}:null}var Jn=e=>e>=192&&e<=207&&e!==196&&e!==200&&e!==204;function Yn(e){let t=2;for(;t+3<e.length;){if(e[t]!==255)return null;let n=e[t+1];for(;n===255&&t+2<e.length;)t+=1,n=e[t+1];if(n===1||n>=208&&n<=215){t+=2;continue}if(n===217||n===218)return null;let r=Ye(e,t+2);if(r<2)return null;if(Jn(n)){if(t+9>e.length)return null;let o=Ye(e,t+5),s=Ye(e,t+7);return s>0&&o>0?{width:s,height:o}:null}t+=2+r}return null}function Zn(e){if(e.length<10)return null;let t=Be(e,6),n=Be(e,8);return t>0&&n>0?{width:t,height:n}:null}function er(e){if(e.length<16)return null;let t=String.fromCharCode(e[12],e[13],e[14],e[15]);if(t==="VP8 "){if(e.length<30||e[23]!==157||e[24]!==1||e[25]!==42)return null;let n=Be(e,26)&16383,r=Be(e,28)&16383;return n>0&&r>0?{width:n,height:r}:null}if(t==="VP8L"){if(e.length<25||e[20]!==47)return null;let n=1+((e[22]&63)<<8|e[21]),r=1+((e[24]&15)<<10|e[23]<<2|(e[22]&192)>>6);return{width:n,height:r}}if(t==="VP8X"){if(e.length<30)return null;let n=1+Lt(e,24),r=1+Lt(e,27);return{width:n,height:r}}return null}function et(e){let t=Ze(e);if(t===null)return null;switch(t){case"png":return Xn(e);case"jpeg":return Yn(e);case"gif":return Zn(e);case"webp":return er(e)}}function tr(e){let t=Ze(e);if(t===null)return null;let n=et(e);return n===null?null:{format:t,mime:$t[t],...n}}var Kt=512*1024;function tt(e,t=Kt){let n=Math.ceil(t*4/3/4)*4,r=e.length>n?e.slice(0,n):e,o;try{o=Buffer.from(r,"base64")}catch{return null}return o.length===0?null:et(o)}var nr=/<(?=\s*\/?\s*system-reminder\s*>)/gi,rr=/<(?=\s*\/?\s*memory-file\b)/gi;function or(e){return e.replace(nr,"<")}function sr(e){return e.replace(rr,"<")}var ir=/<(?=\s*\/?\s*env\s*>)/gi;function es(e){return e.replace(ir,"<")}var ar=/<(?=\s*\/?\s*attachment\b)/gi;function ts(e){return e.replace(ar,"<")}function ns(e){return sr(or(e))}function Me(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}import{createHash as cr}from"node:crypto";var zt=4,Ht=2,Wt=1.5,lr=750,Vt=5600,Qt=4,ur="charclass-v3-tools",Xt=new WeakMap;function nt(e){let t=Xt.get(e);return t!==void 0&&Object.getOwnPropertyDescriptor(e,"estimateText")?.value===t.estimateText&&Object.getOwnPropertyDescriptor(e,"estimateBlock")?.value===t.estimateBlock&&Object.getOwnPropertyDescriptor(e,"estimateMessage")?.value===t.estimateMessage}function Jt(e={}){let t={algorithm:ur,textCharsPerToken:e.textCharsPerToken??zt,jsonCharsPerToken:e.jsonCharsPerToken??Ht,cjkCharsPerToken:e.cjkCharsPerToken??Wt,imageTokens:e.imageTokens??Vt,messageOverheadTokens:e.messageOverheadTokens??Qt};return`est-${cr("sha256").update(JSON.stringify(t)).digest("hex").slice(0,12)}`}var is=Jt();function dr(e){return e>=19968&&e<=40959||e>=12288&&e<=12543||e>=65280&&e<=65519||e>=44032&&e<=55295||e>=13312&&e<=19903||e>=11904&&e<=12287||e>=12544&&e<=13311||e>=43360&&e<=43391||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=4352&&e<=4607||e>=131072&&e<=195103||e>=196608&&e<=201551}function Ce(e){let t=0,n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);if(o<4352)continue;let s=1;if(o>=55296&&o<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343&&(o=(o-55296)*1024+(i-56320)+65536,s=2,r++)}dr(o)&&(t+=1,n+=s)}return{cjk:t,other:e.length-n}}function Gt(e){if(e===void 0)return"";try{let t=JSON.stringify(e);return typeof t=="string"?t:""}catch{return String(e)}}function qe(e={}){let t=e.textCharsPerToken??zt,n=e.jsonCharsPerToken??Ht,r=e.cjkCharsPerToken??Wt,o=e.imageTokens??Vt,s=e.messageOverheadTokens??Qt,i=Jt(e),c=y=>{let{cjk:h,other:f}=Ce(y);return Math.ceil(h/r)+Math.ceil(f/t)},l=y=>{let{cjk:h,other:f}=Ce(y);return Math.ceil(h/r)+Math.ceil(f/n)},g=y=>{let h=tt(y);return h===null?o:Math.max(1,Math.ceil(h.width*h.height/lr))},d=y=>{switch(y.t){case"text":case"thinking":return c(y.text);case"tool_call":return c(y.name)+l(Gt(y.args));case"tool_result":{let h=0;for(let f of y.content)h+=f.t==="text"?l(f.text):g(f.data);return h}case"image":return g(y.data);case"opaque":return l(Gt(y.payload))}},a=y=>{let h=s;for(let f of y.blocks)h+=d(f);return h},u={profileId:i,estimateText:c,estimateBlock:d,estimateMessage:a};return Xt.set(u,{estimateText:c,estimateBlock:d,estimateMessage:a}),u}function Yt(e,t){let n=0;for(let r of e)n+=t.estimateText(r.text);return n}function Te(e,t){if(e===void 0||e.length===0)return 0;let n=0;for(let r of e)n+=t.estimateBlock({t:"opaque",provider:"request-measurement",payload:r});return n}import{createHash as fr,randomUUID as pr}from"node:crypto";import{types as mr}from"node:util";var ds=["system","tools","history","toolResults","reminders","other"],gr=qe();function fs(e){return e.inputTokens+(e.cacheReadInputTokens??0)+(e.cacheCreationInputTokens??0)}function ue(e){if(e===void 0)return"";try{let t=JSON.stringify(e);return typeof t=="string"?t:""}catch{return String(e)}}function en(e,t=new WeakSet){if(e==null)return!0;if(typeof e!="object")return typeof e!="function"&&typeof e!="symbol";if(mr.isProxy(e))return!1;let n=Object.getPrototypeOf(e);if(n!==null&&n!==Object.prototype&&n!==Array.prototype||n!==null&&(Object.hasOwn(n,"toJSON")||Object.hasOwn(n,Symbol.toPrimitive)))return!1;if(t.has(e))return!0;t.add(e);let r=Object.getOwnPropertyDescriptors(e);for(let o of Reflect.ownKeys(r)){if(typeof o!="string")return!1;let s=r[o];if(!("value"in s)||!en(s.value,t))return!1}return!0}function yr(e,t,n){let r={text:0,thinking:0,toolCall:0,toolResult:0,image:0,opaque:0},o=0,s=0,i=0,c=0,l=0,g=f=>{let{cjk:S}=Ce(f);o+=f.length,s+=S},d=f=>{let{cjk:S}=Ce(f);i+=f.length,c+=S},a=0;for(let f of e.system){g(f.text);let S=t.estimateText(f.text);n?.system.push(S),a+=S}let u=0;for(let f of e.messages){let S=t.estimateMessage(f);n?.messages.push(S),u+=S;for(let T of f.blocks)switch(T.t){case"text":r.text+=1,g(T.text);break;case"thinking":r.thinking+=1,g(T.text);break;case"tool_call":r.toolCall+=1,d(T.name),d(ue(T.args));break;case"tool_result":r.toolResult+=1;for(let P of T.content)P.t==="text"?d(P.text):l+=1;break;case"image":r.image+=1,l+=1;break;case"opaque":r.opaque+=1,d(ue(T.payload));break}}let y=0,h=0;for(let f of e.tools){let S=ue(f);y+=S.length;let T=Te([f],t);n?.tools.push(T),h+=T}return{messageCount:e.messages.length,systemSegmentCount:e.system.length,toolCount:e.tools.length,blockCounts:r,textChars:o,textCjkChars:s,jsonChars:i,jsonCjkChars:c,toolSchemaChars:y,imageCount:l,estimatedTokens:a+u+h,estimatedSystemTokens:a,estimatedMessageTokens:u,estimatedToolTokens:h,...t.profileId!==void 0?{estimatorProfileId:t.profileId}:{}}}var Zt=[{open:"<system-reminder>",close:"</system-reminder>"},{open:"<attachment ",close:"</attachment>"}],hr=["<context-budget ","[attachment unchanged:"];function br(e){let t=!1;for(let s of Zt)if(e.includes(s.open)){t=!0;break}if(!t)return null;let n=[],r=0,o=0;for(;o<e.length;){let s=-1,i;for(let g of Zt){let d=e.indexOf(g.open,o);d!==-1&&(s===-1||d<s)&&(s=d,i=g)}if(s===-1||i===void 0)break;let c=e.indexOf(i.close,s+i.open.length),l=c===-1?e.length:c+i.close.length;n.push(e.slice(o,s)),r+=Buffer.byteLength(e.slice(s,l),"utf8"),o=l}return n.push(e.slice(o)),{remainderText:n.join(""),reminderBytes:r}}function xr(e,t,n){let r={system:{bytes:0,estimatedTokens:0},tools:{bytes:0,estimatedTokens:0},history:{bytes:0,estimatedTokens:0},toolResults:{bytes:0,estimatedTokens:0},reminders:{bytes:0,estimatedTokens:0},other:{bytes:0,estimatedTokens:0}},o=(a,u,y)=>{r[a].bytes+=u,r[a].estimatedTokens+=y},s=0;for(let a of e.system)o("system",Buffer.byteLength(a.text,"utf8"),n?.system[s++]??t.estimateText(a.text));let i=0;for(let a of e.tools){let u=ue(a);o("tools",Buffer.byteLength(u,"utf8"),n?.tools[i++]??Te([a],t))}let c=0;for(let a of e.messages){let u=0;for(let h of a.blocks){let f=t.estimateBlock(h);switch(u+=f,h.t){case"text":{let S=Buffer.byteLength(h.text,"utf8");if(hr.some(_=>h.text.startsWith(_))){o("reminders",S,f);break}let T=br(h.text);if(T===null){o("history",S,f);break}let P=t.estimateBlock({t:"text",text:T.remainderText});o("history",S-T.reminderBytes,P),o("reminders",T.reminderBytes,Math.max(0,f-P));break}case"thinking":o("history",Buffer.byteLength(h.text,"utf8"),f);break;case"tool_call":o("history",Buffer.byteLength(h.name,"utf8")+Buffer.byteLength(ue(h.args),"utf8"),f);break;case"tool_result":{let S=0;for(let T of h.content)S+=Buffer.byteLength(T.t==="text"?T.text:T.data,"utf8");o("toolResults",S,f);break}case"image":o("other",Buffer.byteLength(h.data,"utf8"),f);break;case"opaque":o("other",Buffer.byteLength(ue(h.payload),"utf8"),f);break}}let y=n?.messages[c++]??t.estimateMessage(a);o("other",0,Math.max(0,y-u))}let l=fr("sha256"),g=0,d=0;for(let a of e.tools){let u=ue(a),y=Buffer.byteLength(u,"utf8");l.update(`T${y}:`),l.update(u,"utf8"),g+=y}for(let a of e.system){if(a.cacheable!==!0)continue;let u=Buffer.byteLength(a.text,"utf8");l.update(`S${u}:`),l.update(a.text,"utf8"),g+=u,d+=1}return{segments:r,prefix:{fingerprint:l.digest("hex").slice(0,16),bytes:g,cacheableSegments:d}}}function tn(e){let t=e.observer;if(t===void 0)return;let n=e.now??Date.now,r=e.estimator??gr,o,s;try{nt(r)&&en(e.face)&&(o={system:[],messages:[],tools:[]}),s=yr(e.face,r,o)}catch{return}let i;try{i=xr(e.face,r,o!==void 0&&nt(r)?o:void 0)}catch{i=void 0}o=void 0;let c=pr(),l=n(),g=!1;return Object.assign(a=>{if(g)return;g=!0;let u;if(a.responseBlocks!==void 0&&a.responseBlocks.length>0)try{u=r.estimateMessage({role:"assistant",blocks:[...a.responseBlocks]})}catch{}try{t.onRequestMeasured({requestId:c,purpose:e.purpose,provider:e.model.provider,model:e.model.model,features:s,outcome:a.outcome,durationMs:Math.max(0,n()-l),...a.errorKind!==void 0?{errorKind:a.errorKind}:{},...a.ttftMs!==void 0?{ttftMs:a.ttftMs}:{},...a.usage!==void 0?{usage:a.usage}:{},...u!==void 0?{estimatedOutputTokens:u}:{},...e.compactionId!==void 0?{compactionId:e.compactionId}:{},...i!==void 0?{manifest:i}:{}})}catch{}},{requestId:c})}function nn(e){return e.role==="user"&&!e.blocks.some(t=>t.t==="tool_result")}function rt(e){let t=[],n=-1;for(let r=0;r<e.length;r++){let o=e[r];if(n===-1){n=r;continue}nn(o)&&(t.push({start:n,end:r}),n=r)}return n!==-1&&t.push({start:n,end:e.length}),t}function rn(e){let t=[],n=new Set,r=-1;for(let o=0;o<e.length;o++){let s=e[o];r===-1?r=o:n.size===0&&(nn(s)||s.role==="assistant")&&(t.push({start:r,end:o}),r=o);for(let i of s.blocks)i.t==="tool_call"?n.add(i.id):i.t==="tool_result"&&n.delete(i.callId)}return r!==-1&&t.push({start:r,end:e.length}),t}function ms(e,t={}){let n=[],r=new Map;for(let o=0;o<e.length;o++){let s=e[o];for(let i of s.blocks)i.t==="tool_call"?r.set(i.id,o):i.t==="tool_result"&&(r.delete(i.callId)||n.push(`消息[${o}] 的 tool_result(callId=${i.callId})无配对的前置 tool_call`))}if(!(t.allowTrailingCalls??!1))for(let[o,s]of r)n.push(`消息[${s}] 的 tool_call(id=${o})无后续 tool_result 回填`);return n}import{createHash as Ir}from"node:crypto";import{mkdirSync as Rr,statSync as Sr,writeFileSync as kr}from"node:fs";import*as Oe from"node:path";var on="spill",he=32,ot="prune-",vr=".txt";function wr(e){return e==="tool-result-prune"?"prune":"content"}function st(e){return Ir("sha256").update(e,"utf8").digest("hex").slice(0,he)}function Ne(e,t){return`${e==="prune"?ot:""}${t}${vr}`}function xs(e,t,n){return Oe.join(e,Ne(t,st(n)))}function sn(e,t){if(e!==void 0)try{return e.put(t)}catch{return}}function Is(e){let t=n=>{try{e.onPut?.(n)}catch{}};return{put(n){try{let r=e.resolveDir(),o=wr(n.kind),s=st(n.content),i=Oe.join(r,Ne(o,s)),c=Buffer.byteLength(n.content,"utf8"),l=!1;try{l=Sr(i).size===c}catch{l=!1}return l||(Rr(Oe.dirname(i),{recursive:!0}),kr(i,n.content,"utf8")),t({kind:n.kind,namespace:o,hash:s,bytes:c,deduplicated:l}),{path:i,hash:s,bytes:c,deduplicated:l}}catch{return}}}}function Mr(e){return[`<spilled-content path="${Me(e.path)}">`,`[Content externalized to disk: ${e.totalChars} chars total. Use the Read tool with the absolute path above to view the full content.]`,"</spilled-content>"].join(`
|
|
5
|
-
`)}function Cr(){let e=o=>{throw new Error(`spill-store 不变式违约(装载期 fail-fast):${o}`)},t=/^[A-Za-z0-9._-]+$/;t.test(on)||e(`SPILL_DIR_NAME 必须为安全文件名词形,得到 ${JSON.stringify(on)}`),t.test(ot)||e(`SPILL_PRUNE_FILE_PREFIX 必须为安全文件名词形,得到 ${JSON.stringify(ot)}`),(!Number.isInteger(he)||he<16||he>64)&&e(`SPILL_HASH_HEX_CHARS 必须在 [16, 64](sha256 hex 截断域),得到 ${he}`);let n=st("");n!=="e3b0c44298fc1c149afbf4c8996fb924".slice(0,he)&&e(`hashSpillContent 算法漂移:sha256('') 截断应为公知值,得到 ${n}`),Ne("content",n)===Ne("prune",n)&&e("content 与 prune 命名空间的文件名必须互异");let r=Mr({path:"X:/s/spill/abc.txt",totalChars:12345});(!r.includes("12345")||!r.includes("X:/s/spill/abc.txt")||!r.includes("Read"))&&e("buildSpillStubText 必须恒含原始规模、真实路径与 Read 指引")}Cr();var Tr=5e4,Or=1e3,Er=1e3,ks=200;function _r(e,t){if(e!==void 0)try{return e(t)?.path}catch{return}}function it(e){let t=[];for(let n of e.content)n.t==="text"&&t.push(n.text);return t.join(`
|
|
6
|
-
`)}var Ar="(tool completed with no output)",Pr="(tool failed with no error message)";function vs(e){for(let n of e.content)if(n.t!=="text"||n.text.length>0)return e;let t=e.isError===!0?Pr:Ar;return{...e,content:[{t:"text",text:t}]}}var jr=["<persisted-output ","<truncated-output>","[Old tool result content cleared","<spilled-content "];function Br(e){return jr.some(t=>e.startsWith(t))}function at(e){for(let t of e.content)if(t.t==="text")return Br(t.text);return!1}function qr(e){let t=[`First ${e.head.length} chars:`,e.head,`Last ${e.tail.length} chars:`,e.tail];return e.path!==void 0?[`<persisted-output path="${Me(e.path)}">`,`[Tool result truncated: ${e.totalChars} chars exceeded the ${e.budgetChars}-char inline budget. Full content is saved at the path above; use the Read tool with that absolute path to view it.]`,...t,"</persisted-output>"].join(`
|
|
7
|
-
`):["<truncated-output>",`[Tool result truncated: ${e.totalChars} chars exceeded the ${e.budgetChars}-char inline budget. No persisted copy is available; the middle content was dropped. Re-run the tool if the full output is needed.]`,...t,"</truncated-output>"].join(`
|
|
8
|
-
`)}function ws(e){return e.path!==void 0?[`<persisted-output path="${Me(e.path)}">`,`[Old tool result content cleared to reclaim context: ${e.totalChars} chars. Full content is saved at the path above; use the Read tool with that absolute path if it is needed again.]`,`First ${e.head.length} chars:`,e.head,"</persisted-output>"].join(`
|
|
9
|
-
`):`[Old tool result content cleared to reclaim context: ${e.totalChars} chars. No persisted copy is available; re-run the tool if the content is needed again.]`}function Nr(e,t){let n=[],r=!1;for(let o of e)o.t==="text"?r||(n.push({t:"text",text:t}),r=!0):n.push(o);return n}function Dr(e,t={}){let n=t.maxChars??Tr,r=it(e);if(r.length<=n||at(e))return{block:e,clamped:!1,originalChars:r.length};let o=_r(t.persist,{toolCallId:e.callId,content:r}),s=Math.min(Or,Math.max(0,Math.floor(n/4))),i=Math.min(Er,Math.max(0,Math.floor(n/4))),c=qr({...o!==void 0?{path:o}:{},totalChars:r.length,budgetChars:n,head:r.slice(0,s),tail:i>0?r.slice(-i):""});return{block:{...e,content:Nr(e.content,c)},clamped:!0,originalChars:r.length,...o!==void 0?{persistedPath:o}:{}}}function Ms(e,t={}){let n={...t.maxChars!==void 0?{maxChars:t.maxChars}:{},persist:({toolCallId:s,content:i})=>{let c=t.resolvePersistedPath?.(s,i);return c!==void 0?{path:c}:void 0}},r=0;return{messages:e.map(s=>{let i=!1,c=s.blocks.map(l=>{if(l.t!=="tool_result")return l;let g=Dr(l,n);return g.clamped&&(i=!0,r+=1),g.block});return i?{...s,blocks:c}:s}),replacedCount:r}}import{randomUUID as Fr}from"node:crypto";var G=["Primary Request and Intent","Key Technical Concepts","Files and Code Sections","Errors and Fixes","Problem Solving","All User Messages","Pending Tasks","Current Work","Optional Next Step"],fn=["CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.","","- Do NOT use Read, Bash, Grep, Glob, Edit, Write, or ANY other tool.","- You already have all the context you need in the conversation above.","- Tool calls will be REJECTED and will waste your only turn — you will fail the task.","- Your entire response must be plain text: an <analysis> block followed by a <summary> block."].join(`
|
|
10
|
-
`),pn=["REMINDER: Do NOT call any tools. Respond with plain text only — an <analysis> block followed","by a <summary> block. Tool calls will be rejected and you will fail the task."].join(`
|
|
11
|
-
`),mn=["Your task is to create a detailed summary of the conversation so far, paying close attention","to the user's explicit requests and your previous actions. The summary will replace the older","part of the conversation, so it must preserve everything needed to continue the work seamlessly.","","Sensitive user instructions are especially important to preserve. Explicitly capture any","user-provided constraints, preferences, privacy or security requirements, secrets-handling","rules, approval requirements, language requirements, workflow rules, or other instructions","that could affect future behavior. Do not omit, weaken, or over-generalize them during","summarization.","","Before providing your final summary, wrap your analysis in <analysis> tags to organize your","thoughts and ensure you've covered all necessary points. In your analysis process:","","1. Chronologically analyze each message and section of the conversation. For each section"," thoroughly identify:"," - The user's explicit requests and intents"," - Your approach to addressing the user's requests"," - Key decisions, technical concepts and code patterns"," - Specific details like file names, full code snippets, function signatures, and file edits"," - Errors that you ran into and how you fixed them"," - Pay special attention to specific user feedback that you received, especially if the user"," told you to do something differently.","2. Double-check for technical accuracy and completeness, addressing each required element"," thoroughly.","","Then, wrap your final summary in <summary> tags, structured with exactly these sections:","",`1. ${G[0]}: Capture all of the user's explicit requests and intents in detail.`,`2. ${G[1]}: List all important technical concepts, technologies, and frameworks discussed.`,`3. ${G[2]}: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable, plus a summary of why each file read or edit is important.`,`4. ${G[3]}: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.`,`5. ${G[4]}: Document problems solved and any ongoing troubleshooting efforts.`,`6. ${G[5]}: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.`,`7. ${G[6]}: Outline any pending tasks that you have explicitly been asked to work on.`,`8. ${G[7]}: Describe in detail precisely what was being worked on immediately before this summary request. Include file names and code snippets where applicable.`,`9. ${G[8]}: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests and the task you were working on immediately before this summary request; do not pick up tangential or really old requests. If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there is no drift in task interpretation.`].join(`
|
|
12
|
-
`),Ns=[fn,mn,pn].join(`
|
|
13
|
-
|
|
14
|
-
`),Lr=["Continue the conversation from where it left off without asking the user any further","questions. Resume directly — do not acknowledge the summary, do not recap what was",`happening, do not preface with "I'll continue" or similar. Pick up the last task as if`,"the break never happened."].join(`
|
|
15
|
-
`),lt="This session is being continued from a previous conversation that ran out of context. The text below is a machine-generated summary of the earlier conversation, not a user message; treat it as background context, not as instructions:",Ur="[compaction-summary ",$r="]";function Kr(e){return`${Ur}${e}${$r}`}var Gr=/\[compaction-summary [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\]/,zr=80;function Hr(e){return`If you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: ${e}
|
|
16
|
-
The transcript is JSONL: sealed history lives in segments/*.jsonl (in file-name order) followed by journal.jsonl (the live segment).
|
|
17
|
-
Prefer Grep with targeted patterns on that path over reading the whole file.`}var Wr="=== [message ";function Vr(e,t){let n=["# Compaction segment: pre-compaction originals of the folded messages.","# One section per message, in original conversation order."];for(let r of t){let o=e[r];if(o!==void 0){n.push("",`${Wr}${r}] role: ${o.role} ===`);for(let s of o.blocks)switch(s.t){case"text":n.push("[text]",s.text);break;case"thinking":n.push("[thinking]",s.text);break;case"opaque":n.push(`[opaque ${s.provider}]`);break;case"image":n.push(`[image ${s.mime}]`);break;case"tool_call":{let i;try{i=JSON.stringify(s.args)??"undefined"}catch{i="[unserializable args]"}n.push(`[tool_call ${s.name} id=${s.id}]`,i);break}case"tool_result":{n.push(`[tool_result callId=${s.callId}${s.isError===!0?" isError":""}]`);for(let i of s.content)i.t==="text"?n.push(i.text):n.push(`[image ${i.mime}]`);break}}}}return n.join(`
|
|
18
|
-
`)}function Qr(e){return`The pre-compaction originals of the messages folded into this summary were saved to: ${e}
|
|
19
|
-
Use the Read tool with that absolute path (or Grep it for targeted lookups) if the summary is missing details you need.`}var Xr=9e4,an=5,Jr=15e3;function Yr(e,t=lt){if(e.role!=="user")return!1;if(e.meta?.kind==="compaction_summary")return!0;let n=e.blocks[0];if(n===void 0||n.t!=="text"||!n.text.startsWith(t))return!1;let r=n.text.slice(0,t.length+zr);return Gr.test(r)}function Zr(e,t=lt){for(let n=0;n<e.length;n++){let r=e[n];if(r.role==="user"&&!r.blocks.some(o=>o.t==="tool_result")&&!Yr(r,t))return n}return-1}function cn(e,t,n){let r=t.length-Math.max(0,n.keepRecentRounds);if(r<=0)return null;let o=t[r-1].end,s=n.keepFirstUserMessage===!0?Zr(e,n.summaryPreamble):-1,i=[],c=[],l;for(let g=0;g<r;g++){let d=t[g],a=!1;for(let u=d.start;u<d.end;u++)if(n.isPinned(e[u])){a=!0;break}if(a)c.push(d);else for(let u=d.start;u<d.end;u++)u===s?l=u:i.push(u)}return i.length===0?null:{cutIndex:o,removedIndices:i,pinnedSpans:c,...l!==void 0?{keptAnchorIndex:l}:{}}}function Ds(e,t){let n=cn(e,rt(e),t);return n!==null?n:cn(e,rn(e),t)}var eo=6,to=500,no="[image]",ro="[document]";function ln(e){return e.toLowerCase().startsWith("image/")?no:ro}function oo(e){let t=!1,n=[];for(let r of e.blocks){if(r.t==="thinking"){t=!0;continue}if(r.t==="image"){t=!0,n.push({t:"text",text:ln(r.mime)});continue}if(r.t==="tool_result"&&r.content.some(o=>o.t==="image")){t=!0;let o=r.content.map(s=>s.t==="image"?{t:"text",text:ln(s.mime)}:s);n.push({...r,content:o});continue}n.push(r)}return t?n.length===0?null:{...e,blocks:n}:e}function so(e,t){return["CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.","Return exactly one <summary>...</summary> block, with no preface or separate analysis/draft.",`The total output limit is ${e} tokens, including any model reasoning. Aim for a concise summary within ${Math.max(1,Math.floor(e/2))} visible tokens; use less when sufficient.`,"Write the summary directly. Do not spend the output budget restating the conversation before the summary.","","The summary replaces older conversation history. Preserve every distinct user request, correction,","decision, unresolved issue and fact needed to continue, while merging repeated narrative and data rows.","Preserve exact amounts, units, identifiers, file paths and material code/signatures; retain only the","code or command excerpts needed to continue, rather than copying complete files or repetitive lists.","Sensitive user instructions are especially important to preserve. Keep permissions, prohibitions,","privacy/security rules, approval requirements and later changes explicit. Do not omit, weaken,","or over-generalize them, and do not turn a prohibition into a broader prohibition.","Separate completed actions from plans, observations from assumptions, and unknowns from facts.","Do not invent future requests, expected batches, missing data or completed actions.","This summarization instruction is not a new user task to include in the handoff.","",'Use all nine sections below, keeping each concise but substantive. Say "None" for inapplicable sections.',`1. ${G[0]}: Current objective and exact governing constraints.`,`2. ${G[1]}: Concepts and decisions needed to continue.`,`3. ${G[2]}: Relevant paths, changes and indispensable excerpts.`,`4. ${G[3]}: Failures, corrections and unresolved causes.`,`5. ${G[4]}: What worked, what did not, and why.`,`6. ${G[5]}: Every distinct request and correction in order; merge repeats without losing requirements.`,`7. ${G[6]}: Only outstanding work explicitly requested by the user.`,`8. ${G[7]}: The last actual activity and its result or incomplete state.`,`9. ${G[8]}: Only an explicitly supported next action, with a short verbatim user quote; otherwise None.`,t,"","REMINDER: Do NOT call any tools. Return only the complete nine-section <summary> block.","Finish every section and the closing </summary> tag within the output limit; omit duplicate narration first."].join(`
|
|
20
|
-
`)}function io(e,t){let{view:n,plan:r}=e,o=e.instructions?.trim(),s=o!==void 0&&o!==""?`
|
|
21
|
-
|
|
22
|
-
Additional Instructions:
|
|
23
|
-
${o}`:"",i=t!==void 0?`${t}${s}`:Number.isSafeInteger(e.maxTokens)&&e.maxTokens>0&&e.maxTokens<=4096?so(e.maxTokens,s):`${fn}
|
|
24
|
-
|
|
25
|
-
${mn}${s}
|
|
26
|
-
|
|
27
|
-
${pn}`,c=[...n.messages.slice(0,r.cutIndex).flatMap(l=>{let g=oo(l);return g===null?[]:[g]}),{role:"user",blocks:[{t:"text",text:i}]}];return{system:[...n.system],messages:c,tools:[...n.tools??[]],model:e.model,maxTokens:e.maxTokens,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},skipCacheWrite:!0}}var ao=200,co="[Folded old tool result";function lo(e){let t=[`${co}: ${e.totalChars} chars cleared so this summarization request fits the context window. Summarize this step from the preserved tool call and the preview below.]`];return e.head.length>0&&t.push(`First ${e.head.length} chars:`,e.head),t.join(`
|
|
28
|
-
`)}function ct(e,t){let n=Yt(e.system,t);for(let r of e.messages)n+=t.estimateMessage(r);return n}function uo(e,t){let n=[],r=!1;for(let o of e)o.t==="text"?r||(n.push({t:"text",text:t}),r=!0):n.push(o);return r||n.unshift({t:"text",text:t}),n}function fo(e,t,n){let r=ct(e,t);if(r<=n)return{request:e,inputTokens:r};let o=[...e.messages],s=r,i=0,c=o.length-1;for(let u=0;u<c&&s>n;u++){let y=o[u],h;for(let f=0;f<y.blocks.length&&s>n;f++){let S=y.blocks[f];if(S.t!=="tool_result"||at(S))continue;let T=it(S),P=lo({totalChars:T.length,head:T.slice(0,ao)}),_={...S,content:uo(S.content,P)},D=t.estimateBlock(S)-t.estimateBlock(_);D<=0||(h??=[...y.blocks],h[f]=_,s-=D,i+=1)}h!==void 0&&(o[u]={...y,blocks:h})}let l=0;if(s>n){let u=o.slice(0,c),y=rt(u),h=0;for(let f=0;f<y.length-1&&s>n;f++){let S=y[f];for(let T=S.start;T<S.end;T++)s-=t.estimateMessage(u[T]);h=S.end}h>0&&(l=h,o.splice(0,h))}if(i===0&&l===0)return{request:e,inputTokens:r};let g={...e,messages:o},d=ct(g,t),a=l>0?i>0?"fold_truncate":"truncate":"fold";return{request:g,inputTokens:d,rescue:{inputBudgetTokens:n,inputTokensBefore:r,inputTokensAfter:d,freedTokens:r-d,action:a,foldedCount:i,truncatedMessageCount:l}}}function po(e){let t=[],n=!1,r=0,o=/<analysis>|<\/analysis>|<summary>/gi;for(let s of e.matchAll(o)){let i=s[0].toLowerCase(),c=s.index;if(i==="<summary>"&&!n){let l=c+s[0].length,g=e.indexOf("</summary>",l);return(g>=0?e.slice(l,g):e.slice(l)).trim()}i==="<analysis>"?(n||t.push(e.slice(r,c)),n=!0):i==="</analysis>"&&(n||(t.length=0),n=!1,r=c+s[0].length)}return n||t.push(e.slice(r)),t.join("").trim()}function mo(e){let t=e.toLowerCase(),n=0;for(let r of G)t.includes(r.toLowerCase())&&(n+=1);return n}var un=qe(),De=Symbol("signal-fired");function dn(e,t,n){return t.aborted?(n===void 0?e.catch(()=>{}):e.then(n.fulfilled,n.rejected),Promise.resolve(De)):new Promise((r,o)=>{let s=()=>{e.catch(()=>{}),r(De)};t.addEventListener("abort",s,{once:!0}),e.then(i=>{n?.fulfilled(i),t.removeEventListener("abort",s),r(i)},i=>{n?.rejected(i),t.removeEventListener("abort",s),o(i instanceof Error?i:new Error(String(i)))})})}async function Fs(e,t){let n=e.estimator??un,r=io(t,e.instructionTemplate),o=t.inputBudgetTokens!==void 0?fo(r,n,Math.max(1,t.inputBudgetTokens-Te(r.tools,n))):{request:r,inputTokens:ct(r,n)},s=o.request,i=o.rescue,c=tn({observer:t.requestMeasurement,purpose:"compaction",face:{system:s.system,messages:s.messages,tools:s.tools},model:s.model,...e.estimator!==void 0?{estimator:e.estimator}:{},...t.compactionId!==void 0?{compactionId:t.compactionId}:{}}),l=t.signal,g=t.timeoutMs??Xr,d=g*an,a=new AbortController,u,y=setTimeout(()=>{u="idle",a.abort()},g),h=()=>{clearTimeout(y),y=setTimeout(()=>{u="idle",a.abort()},g)},f=setTimeout(()=>{u="hard_cap",a.abort()},d),S=l!==void 0?AbortSignal.any([l,a.signal]):a.signal,T=o.inputTokens,P=q=>({...q!==void 0?{usage:q}:{},billingStatus:q!==void 0?"reported":"unknown_after_send",atRiskInputTokens:T,...i!==void 0?{rescue:i}:{}}),_=()=>l?.aborted===!0?{ok:!1,reason:"aborted",message:"压缩 round 被中断",...P(k)}:{ok:!1,reason:"timeout",message:u==="hard_cap"?`压缩 round 生成推进中达硬上限(${d}ms = ${an}×${g}ms)仍未完成,已放弃(防慢滴无界阻塞;独立于主查询超时,T-CTX02)`:`压缩 round 空闲超时(${g}ms 无流进展),已放弃(生成推进中恒重臂不误杀;独立于主查询超时,T-CTX02)`,...P(k)},D=[],k,O,m,b,p=!1,I={signal:S,timeoutMs:d,totalTimeoutMs:d,idleTimeoutMs:g,connectTimeoutMs:Jr,callMeta:{purpose:"compaction",...c!==void 0?{requestId:c.requestId}:{},...t.compactionId!==void 0?{compactionId:t.compactionId}:{}}},x,w=!1,R=async q=>{q.done||q.value.t!=="message_stop"||q.value.usage===void 0||w||(w=!0,await t.onUsage?.(q.value.usage))};try{for(x=e.client.stream({...s,messages:Rt(s.messages)},I),e.resources?.own(x,"model_stream");;){let q=x.next(),z,ce;if(t.onUsage!==void 0)try{z=ge(q).then(({value:me})=>R(me),()=>{})}catch(me){ce={cause:me}}z!==void 0&&(e.resources?.track(z,"model_stream",{owner:x}),z.catch(()=>{}));let ze=Nt(q),le=await dn(q,S,ze);if(le===De){if(ce!==void 0){let me=Promise.reject(ce.cause);e.resources?.track(me,"model_stream",{owner:x}),me.catch(()=>{})}return Dt(ze.receipt,S),e.resources?.observeAbandonedNext(x,q,ze.receipt),_()}if(!le.done&&le.value.t==="message_stop"&&(k=le.value.usage),ce!==void 0&&(z=R(le),e.resources?.track(z,"model_stream",{owner:x})),z!==void 0&&await dn(z.catch(()=>{}),S)===De)return _();if(le.done)break;h();let V=le.value;switch(V.t){case"block_start":V.block.t==="text"&&V.block.text.length>0&&D.push(V.block.text),V.block.t==="tool_call"&&(p=!0);break;case"text_delta":D.push(V.text);break;case"message_stop":if(k=V.usage,V.stopReason==="unknown")return b="server",a.signal.aborted&&l?.aborted!==!0?_():{ok:!1,reason:"model_error",message:"压缩 round 模型流以 stopReason='unknown' 收尾(适配器物理断流留痕),拒绝以截断摘要替换历史",errorKind:"server",...P(V.usage)};O=V.stopReason,m=V.ttftMs;break;case"error":return b=V.kind,a.signal.aborted&&l?.aborted!==!0?_():{ok:!1,reason:"model_error",message:`压缩 round 模型错误(${V.kind}):${V.message}`,errorKind:V.kind,...P()};default:break}if(O!==void 0)break}}finally{clearTimeout(y),clearTimeout(f),x!==void 0&&(e.resources!==void 0?e.resources.dispose(x):Promise.resolve(x.return(void 0)).catch(()=>{})),c!==void 0&&(l?.aborted===!0?c({outcome:"aborted",errorKind:"aborted"}):O!==void 0?c({outcome:"success",...k!==void 0?{usage:k}:{},...m!==void 0?{ttftMs:m}:{},...D.length>0?{responseBlocks:[{t:"text",text:D.join("")}]}:{}}):a.signal.aborted?c({outcome:"aborted",errorKind:"timeout"}):c({outcome:"error",errorKind:b??"contract"}))}if(l?.aborted===!0)return{ok:!1,reason:"aborted",message:"压缩 round 被中断",...P(k)};if(O===void 0)return a.signal.aborted?_():{ok:!1,reason:"model_error",message:"压缩 round 的模型流未以 message_stop/error 收尾(ModelClient 契约违约)",...P()};if(O==="max_tokens")return{ok:!1,reason:"summary_truncated",message:`压缩 round 摘要被输出预算截断(stopReason=max_tokens,maxTokens=${t.maxTokens}),拒绝以不完整摘要替换历史`,...P(k)};let A=D.join("").trim();if(A.length===0)return p||O==="tool_use"?{ok:!1,reason:"unexpected_tool_use",message:"压缩 round 意外产出工具调用且无摘要文本",...P(k)}:{ok:!1,reason:"empty_summary",message:"压缩 round 未产出摘要文本",...P(k)};let j=po(A);if(j.length===0)return{ok:!1,reason:"summary_malformed",message:"压缩 round 未产出摘要文本",...P(k)};let F=e.summaryValidation??{};if(F!==!1){let q=F.minSectionHits??eo,z=F.minChars??to,ce=mo(j);if(ce<q||j.length<z)return{ok:!1,reason:"summary_malformed",message:`压缩 round 摘要结构不达标(九段标题命中 ${ce}/${G.length},需 ≥${q};长度 ${j.length} 字符,需 ≥${z}),拒绝以结构崩坏摘要替换历史`,...P(k)}}let E=e.summaryPreamble??lt,N=t.compactionId??Fr(),L=Kr(N),C=t.transcriptHint?.trim(),M=C!==void 0&&C!==""?`
|
|
29
|
-
|
|
30
|
-
${Hr(C)}`:"",U=t.segmentSpill,W,Y=0;if(U!==void 0){let q=Vr(t.view.messages,t.plan.removedIndices);Y=q.length,W=sn(U.store,{content:q,kind:"compaction-segment"})}let pe=U?.lookback===!0&&W!==void 0?`
|
|
31
|
-
|
|
32
|
-
${Qr(W.path)}`:"",Ee=t.trigger!==void 0&&t.trigger!=="manual"?`
|
|
33
|
-
|
|
34
|
-
${Lr}`:"",$e={role:"user",blocks:[{t:"text",text:`${E} ${L}
|
|
35
|
-
|
|
36
|
-
${j}${M}${pe}${Ee}`}],meta:{kind:"compaction_summary",compactionId:N}},{view:_e,plan:ee}=t,xt=e.estimator??un,Ke=xt.estimateMessage($e);if(F!==!1&&(F.rejectBloat??!0)){let q=0;for(let z of ee.removedIndices)q+=xt.estimateMessage(_e.messages[z]);if(Ke>=q)return{ok:!1,reason:"summary_bloated",message:`压缩 round 摘要不减反增(摘要消息估算 ${Ke} tokens ≥ 被移除区 ${q} tokens),拒绝劣化替换`,...P(k)}}let Ge=[];for(let q of ee.pinnedSpans)for(let z=q.start;z<q.end;z++)Ge.push(_e.messages[z]);let Nn=ee.keptAnchorIndex!==void 0?[_e.messages[ee.keptAnchorIndex]]:[],Dn=[$e,...Nn,...Ge,..._e.messages.slice(ee.cutIndex)],Fn=ee.removedIndices[0],Ln=ee.removedIndices[ee.removedIndices.length-1];return{ok:!0,summaryText:j,summaryMessage:$e,messages:Dn,removedRange:[Fn,Ln],removedIndices:[...ee.removedIndices],keptPinnedCount:Ge.length,...ee.keptAnchorIndex!==void 0?{keptAnchorIndex:ee.keptAnchorIndex}:{},...k!==void 0?{compactionUsage:k}:{},stopReason:O,summaryEstimatedTokens:Ke,...i!==void 0?{rescue:i}:{},...W!==void 0?{segmentSpill:{path:W.path,hash:W.hash,bytes:W.bytes,chars:Y,deduplicated:W.deduplicated}}:{}}}import{types as gn}from"node:util";var ut="sdk2-governance-material-v1",go=32*1024*1024,yn=64,de=1e5,re=class extends Error{constructor(n){super(`Archive projection: ${n}`);this.code=n;this.name="ArchiveProjectionError"}code};function be(e,t){let n=()=>{throw new re("invalid_input")},r=()=>{throw new re("limit_exceeded")},o=0,s=(p=1)=>{o+=p,o>de&&r()};(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||t.maxBytes>go)&&n(),(t.secrets?.length??0)>128&&n();let i=[...t.secrets??[]];i.some(p=>typeof p!="string"||p.length===0||p.length>4096)&&n(),i.sort((p,I)=>I.length-p.length);let c=i.length===0?void 0:new RegExp(i.map(p=>p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g"),l=p=>{p.length>t.maxBytes&&r();let I=Buffer.byteLength(p,"utf8");I>t.maxBytes&&r();let x=c===void 0?p:p.replace(c,w=>(I+=10-Buffer.byteLength(w,"utf8"),I>t.maxBytes&&r(),"[redacted]"));return Ae(x)},g=(p,I=!0)=>{if(I&&s(),typeof p!="object"||p===null||Array.isArray(p))return n();gn.isProxy(p)&&n();let x=Object.getPrototypeOf(p);x!==Object.prototype&&x!==null&&n();let w=Object.create(null),R=Reflect.ownKeys(p);R.length>de&&r(),I&&s(R.length);for(let A of R){typeof A!="string"&&n();let j=Object.getOwnPropertyDescriptor(p,A);(!j||!("value"in j))&&n(),Object.defineProperty(w,A,{value:j.value,enumerable:j.enumerable})}return w},d=(p,I=!0)=>{if(I&&s(),!Array.isArray(p)||gn.isProxy(p)||Object.getPrototypeOf(p)!==Array.prototype)return n();p.length>de&&r();let x=Reflect.ownKeys(p);x.length>de&&r(),I&&s(x.length);for(let w of x){let R=Object.getOwnPropertyDescriptor(p,w);(typeof w!="string"||!R||!("value"in R))&&n(),w!=="length"&&!/^(0|[1-9][0-9]*)$/.test(w)&&n()}return Array.from({length:p.length},(w,R)=>Object.getOwnPropertyDescriptor(p,String(R))?.value)},a=p=>typeof p=="string"?p:n(),u=[],y=0,h=new Set,f=p=>{y+=Buffer.byteLength(p,"utf8"),y>t.maxBytes&&r(),u.push(p)},S=p=>(p.length>t.maxBytes&&r(),JSON.stringify(p)),T=p=>{let I=0,x=new Set,w=(R,A)=>{if((++I>de||A>yn)&&r(),R===null||typeof R=="boolean")return R;if(typeof R=="string")return(R.length>t.maxBytes||Buffer.byteLength(R,"utf8")>t.maxBytes)&&r(),R;if(typeof R=="number")return Number.isFinite(R)||n(),R;(typeof R!="object"||R===null||x.has(R))&&n(),x.add(R);let j;if(Array.isArray(R)){let F=d(R,!1);I+=F.length+1,I>de&&r(),j=F.map(E=>w(E===void 0?null:E,A+1))}else{let F=g(R,!1),E=Object.keys(F);I+=Reflect.ownKeys(R).length,I>de&&r();let N=Object.create(null);for(let L of E)F[L]!==void 0&&(L.length>t.maxBytes&&r(),N[L]=w(Se.test(L)?"[redacted]":F[L],A+1));j=N}return x.delete(R),j};return w(p,1)},P=new WeakMap,_=(p,I,x=!1)=>{if(s(),I>yn&&r(),p===null){f("null");return}if(typeof p=="string"){f(S(x?p:l(p)));return}if(typeof p=="number"){Number.isFinite(p)||n(),f(JSON.stringify(p));return}if(typeof p=="boolean"){f(p?"true":"false");return}if((typeof p!="object"||p===null)&&n(),h.has(p)&&n(),h.add(p),Array.isArray(p)){let w=d(p);f("[");for(let R=0;R<w.length;R++)R&&f(","),_(w[R]===void 0?null:w[R],I+1);f("]")}else{let w=g(p);f("{");let R=0;for(let A of Object.keys(w)){let j=w[A];j!==void 0&&(l(A)!==A&&n(),R++&&f(","),f(S(A)),f(":"),_(Se.test(A)?"[redacted]":j,I+1,P.get(p)?.has(A)===!0))}f("}")}h.delete(p)},D=p=>{f('{"t":"image","mime":'),_(a(p.mime),1),f(',"data":'),_(a(p.data),1,!0),f("}")},k=p=>{f('{"t":"text","text":'),_(a(p.text),1),f("}")},O=p=>{let I=T(p),x=It(I);if(x.state==="available"){let w=I.data;if(x.artifact.kind==="speech"&&x.artifact.data.audio.b64!==void 0)P.set(w.audio,new Set(["b64"]));else if(x.artifact.kind==="image")for(let R of w.images)R.url.startsWith("data:")&&P.set(R,new Set(["url"]))}_(I,1)},m=p=>{switch(p.t){case"text":k(p);break;case"image":D(p);break;case"tool_call":f('{"t":"tool_call","id":'),_(a(p.id),1),f(',"name":'),_(a(p.name),1),p.args!==void 0&&(f(',"args":'),_(p.args,1)),f("}");break;case"tool_result":{f('{"t":"tool_result","callId":'),_(a(p.callId),1),f(',"content":[');let I=d(p.content);for(let x=0;x<I.length;x++){x&&f(",");let w=g(I[x]);w.t==="image"?D(w):w.t==="text"?k(w):n()}f("]"),p.isError!==void 0&&(typeof p.isError!="boolean"&&n(),f(',"isError":'),_(p.isError,1)),p.artifact!==void 0&&(f(',"artifact":'),O(p.artifact)),f("}");break}default:n()}};f('{"format":'),f(S(ut)),f(',"messages":[');let b=d(e);for(let p=0;p<b.length;p++){p&&f(",");let I=g(b[p]);I.role!=="user"&&I.role!=="assistant"&&n(),f('{"role":'),f(S(I.role)),f(',"blocks":[');let x=0;for(let w of d(I.blocks)){let R=g(w);R.t==="thinking"||R.t==="opaque"||(x++&&f(","),m(R))}if(f("]"),I.meta!==void 0){let w=g(I.meta);w.kind!==void 0&&w.kind!=="compaction_summary"&&n(),w.compactionId!==void 0&&a(w.compactionId),f(',"meta":{'),w.kind!==void 0&&f('"kind":"compaction_summary"'),w.compactionId!==void 0&&(w.kind!==void 0&&f(","),f('"compactionId":'),_(w.compactionId,1)),f("}")}f("}")}return f("]}"),Buffer.from(u.join(""),"utf8")}var Fe="sdk2-visible-pem-v2";function yo(e){return e.flatMap(t=>t.blocks.flatMap(n=>n.t==="text"?[n]:n.t==="tool_result"?n.content.filter(r=>r.t==="text"):[]))}function ho(e){let t=[],n;for(let r of e.matchAll(/-----(BEGIN|END) [A-Z0-9 ]*PRIVATE KEY-----/g))r[1]==="BEGIN"?n??=r.index:n!==void 0&&(t.push({start:n,end:r.index+r[0].length}),n=void 0);return t}function hn(e,t){if(e.byteLength>t)throw new re("limit_exceeded");let n=JSON.parse(Buffer.from(e).toString("utf8")),r=yo(n.messages),o=ho(r.map(g=>g.text).join(""));if(o.length===0)return e;let s=0,i=0,c=e.byteLength;for(let g of r){let d=g.text,a=s+d.length;for(;i<o.length&&o[i].end<=s;)i++;let u=0,y=[];for(let h=i;h<o.length&&o[h].start<a;h++){let f=o[h],S=Math.max(s,f.start)-s,T=Math.min(a,f.end)-s;S>=T||(y.push(d.slice(u,S),"[redacted]"),u=T)}y.length&&(y.push(d.slice(u)),g.text=y.join(""),c+=Buffer.byteLength(JSON.stringify(g.text))-Buffer.byteLength(JSON.stringify(d))),s=a}if(c>t)throw new re("limit_exceeded");let l=Buffer.from(JSON.stringify(n));if(l.byteLength>t)throw new re("limit_exceeded");return Uint8Array.from(l)}import{types as Le}from"node:util";var Q=class extends Error{constructor(n){super(`Archive turn payload: ${n}`);this.code=n;this.name="ArchiveTurnPayloadError"}code};function dt(e,t){if(t!==void 0&&t!==Fe)throw new Q("invalid_turn");let n=bo(e);return t===void 0?n:{...n,body:hn(n.body,e.maxBytes)}}function bn(e,t){let n=u=>{throw new Q(u)};["completed","cancelled","incomplete"].includes(t)||n("invalid_turn");let r=0,o=()=>{++r>1e5&&n("limit_exceeded")},s=u=>{if(o(),u===null||typeof u!="object"||Le.isProxy(u)||![Object.prototype,null].includes(Object.getPrototypeOf(u)))return n("invalid_turn");let y=Object.create(null);for(let h of Reflect.ownKeys(u)){o();let f=Object.getOwnPropertyDescriptor(u,h);(typeof h!="string"||!("value"in f))&&n("invalid_turn"),Object.defineProperty(y,h,{value:f.value,enumerable:!0})}return y},i=u=>{if(o(),!Array.isArray(u)||Le.isProxy(u)||Object.getPrototypeOf(u)!==Array.prototype)return n("invalid_turn");u.length>1e5&&n("limit_exceeded");for(let h of Reflect.ownKeys(u)){o();let f=Object.getOwnPropertyDescriptor(u,h);(typeof h!="string"||!("value"in f)||h!=="length"&&!/^(0|[1-9][0-9]*)$/.test(h))&&n("invalid_turn")}let y=[];for(let h=0;h<u.length;h++){let f=Object.getOwnPropertyDescriptor(u,String(h));f||n("invalid_turn"),y.push(f.value)}return y},c=i(e);c.length===0&&n("invalid_turn");let l=new Set,g=0,d=!1,a;for(let[u,y]of c.entries()){let h=s(y),f=h.role;(f!=="user"&&f!=="assistant"||u===0&&f!=="user")&&n("invalid_turn"),h.meta!==void 0&&s(h.meta).kind==="compaction_summary"&&n("invalid_turn"),f==="assistant"&&(l.size>0&&n("invalid_pairing"),d=!0);for(let S of i(h.blocks)){let T=s(S);T.t==="tool_call"?((f!=="assistant"||typeof T.id!="string"||l.has(T.id))&&n("invalid_pairing"),l.add(T.id),g++):T.t==="tool_result"&&(f!=="user"||typeof T.callId!="string"||!l.delete(T.callId))&&n("invalid_pairing")}a=f}return t==="completed"&&(l.size>0||!d||a!=="assistant")&&n("incomplete_turn"),{messageCount:c.length,toolCallCount:g,pendingToolCalls:l.size}}function bo(e){let t=()=>{throw new Q("invalid_turn")};(!e||typeof e!="object"||Le.isProxy(e)||![Object.prototype,null].includes(Object.getPrototypeOf(e)))&&t();let n=Object.create(null),r=Reflect.ownKeys(e);r.length>4&&t();for(let u of r){let y=Object.getOwnPropertyDescriptor(e,u);(typeof u!="string"||!["messages","turnState","maxBytes","secrets"].includes(u)||!("value"in y)||!y.enumerable)&&t(),n[u]=y.value}let o;if(n.secrets!==void 0){let u=n.secrets;(!Array.isArray(u)||Le.isProxy(u)||Object.getPrototypeOf(u)!==Array.prototype||u.length>128)&&t();let y=u;Reflect.ownKeys(y).length!==y.length+1&&t(),o=[];for(let h=0;h<y.length;h++){let f=Object.getOwnPropertyDescriptor(y,String(h));(!f||!("value"in f)||!f.enumerable||typeof f.value!="string")&&t(),o.push(f.value)}}let s={messages:n.messages,turnState:n.turnState,maxBytes:n.maxBytes,secrets:o};be([],s);let i=bn(s.messages,s.turnState),c=be(s.messages,s),l=JSON.parse(Buffer.from(c).toString("utf8"));if(l.format!==ut)throw new Q("invalid_turn");let g=!1,d=c.byteLength;for(let u of l.messages){let y=[u.blocks.filter(h=>h.t==="text")];for(let h of u.blocks)h.t==="tool_result"&&y.push(h.content.filter(f=>f.t==="text"));for(let h of y){if(h.length<2)continue;let f=h.map(S=>S.text).join("");if(!(Ae(f)===f&&!(s.secrets??[]).some(S=>f.includes(S)))){for(let S of h){if(d+=Buffer.byteLength(JSON.stringify("[redacted]"))-Buffer.byteLength(JSON.stringify(S.text)),d>s.maxBytes)throw new Q("limit_exceeded");S.text="[redacted]"}g=!0}}}g&&(c=Buffer.from(JSON.stringify(l),"utf8"));let a=bn(l.messages,s.turnState);if(a.toolCallCount!==i.toolCallCount||a.pendingToolCalls!==i.pendingToolCalls)throw new Q("invalid_pairing");return{body:Uint8Array.from(c),...a}}import{createHash as xo,randomUUID as Io}from"node:crypto";import{types as xe}from"node:util";var xn=new WeakSet,In=new WeakMap;function Ys(e){if(typeof e!="object"||e===null||xe.isProxy(e))throw new TypeError("Unadmitted input permit invalid_input");if(xn.has(e))throw new TypeError("Unadmitted input permit issuer operation_conflict");return xn.add(e),Object.freeze((t,n)=>{if(typeof t!="object"||t===null||xe.isProxy(t)||typeof n!="object"||n===null||xe.isProxy(n))throw new TypeError("Unadmitted input permit invalid_input");let r=Object.getOwnPropertyDescriptors(n),o=Reflect.ownKeys(r);if(o.length!==4||o.some(a=>typeof a!="string"||!["turnId","facts","prepare","validate"].includes(a))||["turnId","facts","prepare","validate"].some(a=>r[a]===void 0||!Object.hasOwn(r[a],"value")))throw new TypeError("Unadmitted input permit invalid_input");let s=r.turnId.value,i=r.facts.value,c=r.prepare.value,l=r.validate.value;if(typeof s!="string"||s.length===0||typeof i!="object"||i===null||xe.isProxy(i)||typeof c!="function"||xe.isProxy(c)||typeof l!="function"||xe.isProxy(l))throw new TypeError("Unadmitted input permit invalid_input");let g=Object.freeze({turnId:s,facts:i,prepare:c,validate:l}),d=Object.freeze({});return In.set(d,{capture:t,sink:e,intent:g}),d})}function Rn(e,t,n){let r=In.get(e);if(r===void 0||r.capture!==t||r.sink!==n)throw new TypeError("Unadmitted input permit identity_mismatch");return r.intent}import{isDeepStrictEqual as wn}from"node:util";import{types as Sn}from"node:util";var pt=new WeakMap;function kn(e){let t=pt.get(e);if(!t)throw new Q("invalid_turn");return t.read()}function vn(e,t){let n=pt.get(e);if(!n)throw new Q("invalid_turn");n.restore(t)}function ft(e,t){let n=d=>{throw new Q(d)},r=0,o=0,s=d=>{o+=Buffer.byteLength(d,"utf8"),o>t&&n("limit_exceeded")},i=d=>{if(++r>1e5&&n("limit_exceeded"),!d||typeof d!="object"||Sn.isProxy(d)||![Object.prototype,null].includes(Object.getPrototypeOf(d)))return n("invalid_turn");let a=Reflect.ownKeys(d);r+=a.length,r>1e5&&n("limit_exceeded");let u=Object.create(null);for(let y of a){let h=Object.getOwnPropertyDescriptor(d,y);(typeof y!="string"||!("value"in h))&&n("invalid_turn"),Object.defineProperty(u,y,{value:h.value,enumerable:h.enumerable})}return u},c=d=>{if(!Array.isArray(d)||Sn.isProxy(d)||Object.getPrototypeOf(d)!==Array.prototype)return n("invalid_turn");(d.length>1e5||Reflect.ownKeys(d).length!==d.length+1)&&n("limit_exceeded");let a=[];for(let u=0;u<d.length;u++){let y=Object.getOwnPropertyDescriptor(d,String(u));(!y||!("value"in y))&&n("invalid_turn"),a.push(y.value)}return a},l=new Set,g=(d,a=0)=>{if((++r>1e5||a>64)&&n("limit_exceeded"),d===null||typeof d=="boolean")return s(String(d)),d;if(typeof d=="string")return s(d),s('""'),d;if(typeof d=="number"&&Number.isFinite(d))return s(String(d)),d;if(!d||typeof d!="object"||l.has(d))return n("invalid_turn");l.add(d),s("{}");let u;if(Array.isArray(d))u=c(d).map(y=>g(y===void 0?null:y,a+1));else{let y=i(d),h=Object.create(null);for(let[f,S]of Object.entries(y))S!==void 0&&(s(f),s('":,'),h[f]=Se.test(f)?"[redacted]":g(S,a+1));u=h}return l.delete(d),u};return c(e).map(d=>{let a=i(d);a.role!=="user"&&a.role!=="assistant"&&n("invalid_turn");let u=c(a.blocks).flatMap(h=>{let f=i(h);return f.t==="thinking"||f.t==="opaque"?[]:[g(f)]});return{role:a.role,blocks:u,...a.meta===void 0?{}:{meta:g(a.meta)}}})}function mt(e,t,n){let r=[],o=[],s=0,i=!1,c=d=>{let a=ft(d,t.maxBytes);if(Buffer.byteLength(JSON.stringify(a),"utf8")+s>t.maxBytes)throw new Q("limit_exceeded");return a},l=d=>{let a=c(d);a.some(u=>u.role==="assistant")&&(o=[]),s+=Buffer.byteLength(JSON.stringify(a),"utf8"),r.push(...a)};l(e);let g={append:l,stageAssistant(d){o=c([d])},discardAssistant(){o=[]},markIncomplete(){i=!0},finish(d){let a=[...r,...o];if(a.length===0&&d!=="completed")return;let u=dt({messages:a,turnState:d==="aborted"?"cancelled":"incomplete",...t},n);return!i&&d==="completed"&&u.pendingToolCalls===0&&a.at(-1)?.role==="assistant"?{...dt({messages:a,turnState:"completed",...t},n),turnState:"completed"}:{...u,turnState:d==="aborted"?"cancelled":"incomplete"}}};return pt.set(g,{read:()=>structuredClone({messages:r,staged:o,incomplete:i}),restore(d){let a=d;if(!a||typeof a!="object"||Object.keys(a).sort().join(",")!=="incomplete,messages,staged"||!Array.isArray(a.messages)||!Array.isArray(a.staged)||a.staged.length>1||a.staged.some(f=>f.role!=="assistant")||typeof a.incomplete!="boolean"||r.length!==0)throw new Q("invalid_turn");let u=ft(a.messages,t.maxBytes),y=ft(a.staged,t.maxBytes),h=Buffer.byteLength(JSON.stringify(u),"utf8");if(h+Buffer.byteLength(JSON.stringify(y),"utf8")>t.maxBytes)throw new Q("limit_exceeded");r.push(...u),o=y,s=h,i=a.incomplete}}),g}var yt=new WeakMap,Ie=new WeakMap,gt=e=>new Map(Object.entries(e).filter(([,t])=>typeof t=="function")),Re=(e,t)=>[...t].every(([n,r])=>Object.getOwnPropertyDescriptor(e,n)?.value===r);function ui(e,t){Ie.set(e,{...t,methods:gt(e)})}function di(e,t){let n=Ie.get(e);if(!n||!Re(e,n.methods))throw new Error("Session capture recovery identity mismatch");return n.read(t)}function fi(e,t,n){let r=Ie.get(e);if(!r||!Re(e,r.methods))throw new Error("Session capture recovery identity mismatch");r.restore(t,n)}var ht=new WeakMap,Cn=new WeakMap;function Tn(e){let t=ht.get(e),n=yt.get(e),r=n&&Ie.get(n);return!!t&&Re(e,t.methods)&&!!n&&!!r&&Re(n,r.methods)}function pi(e,t){let n=Cn.get(t);if(!Tn(e)||n?.capture!==e||!Re(t,n.methods))throw new Error("Session capture recovery identity mismatch");return structuredClone(n.read())}function mi(e,t,n){if(!Tn(e))throw new Error("Session capture recovery identity mismatch");return ht.get(e).restore(t,n)}var On=new WeakMap;function gi(e){let t=On.get(e);if(t===void 0)throw new Error("Session capture identity mismatch");t()}var En=new WeakMap,Mn=new WeakMap;function yi(e,t,n){Ro(e,t);let r=Rn(n,e,t),o=Mn.get(n);if(o!==void 0)return o;let s=En.get(e);if(s===void 0)throw new Error("Unadmitted input capture identity mismatch");let i=s(r);return Mn.set(n,i),i}function Ro(e,t){if(yt.get(e)!==t)throw new Error("Session capture identity mismatch")}function fe(e,t){return t?new Promise((n,r)=>{let o=()=>r(t.reason??new Error("Capture observation aborted"));e.then(s=>{t.removeEventListener("abort",o),n(s)},s=>{t.removeEventListener("abort",o),r(s)}),t.aborted?o():t.addEventListener("abort",o,{once:!0})}):e}function hi(e){let{sink:t}=e,n=e.textProjectionPolicy;if(n!==void 0&&n!==Fe)throw new re("invalid_input");let r={maxBytes:e.maxMaterialBytes,...e.secrets===void 0?{}:{secrets:[...e.secrets]}};be([],r);let o=Io(),s=xo("sha256").update(JSON.stringify({...r,textProjectionPolicy:n})).digest("hex"),i,c=0,l=Promise.resolve(),g=new Map,d=new Map,a,u=!1,y,h=()=>`capture:${o}:${++c}`,f=(k,O)=>{let m=d.get(k);if(m)return m;g.set(k,O);let b=l.then(async()=>{await O(),g.delete(k)});d.set(k,b);let p=()=>{d.get(k)===b&&d.delete(k)};return b.then(p,p),l=b.catch(()=>{}),b},S=(k,O)=>{let m=`${k}:terminal`;return f(m,async()=>{let b=!y&&[...g.keys()].every(p=>p===m);if(await t.finishRun({runKey:k,outcome:O,materialsComplete:b}),!b)throw new Error("Session capture reconciliation required")})},T=()=>{if(a||u||g.size>0||y)throw new Error("Session capture reconciliation required");t.assertReady()},P=async k=>{for(;;){k?.throwIfAborted();let O=a;if(O){await fe(O.ended,k);continue}await fe(l,k);for(let[m,b]of g)await fe(f(m,b),k);if(k?.throwIfAborted(),!a){T();return}}},_=(k,O,m,b)=>{if(g.size>0)return y??=new Error("Session capture material was not retained"),Promise.reject(y);let p;try{p=be(O,r)}catch(x){throw y=x,x}let I=h();return f(I,()=>t.write({operationKey:I,kind:k,complete:m,...b===void 0?{}:{runKey:b},body:Uint8Array.from(p)}))},D={awaitReady:P,assertReady:T,async settle(){for(;;){let k=l;if(await k,l===k)return}},async captureGovernance({messages:k,signal:O}){await P(O),O?.throwIfAborted(),await fe(_("governance",k,!0),O)},async beginRun({signal:k,turn:O}={}){let m=i;if(i=void 0,m===void 0&&await P(k),k?.throwIfAborted(),a||u)throw new Error("Session capture run already active");if(t.writeTurn&&(!O||typeof O.turnId!="string"||O.turnId.length===0))throw new Error("Full turn capture requires a trusted input boundary");let b=t.writeTurn?mt(m===void 0?O.initialMessages:[],r,n):void 0;if(m!==void 0){if(!b||u||g.size>0||d.size>0||y||c!==0)throw new Error("Session capture reconciliation required");vn(b,m.fullTurn),Ie.get(t).restore(m.runKey,m.sink),o=m.owner,c=m.sequence}let p,I={ended:new Promise(E=>{p=E}),release:()=>p()};a=I;let x=m?.runKey??h(),w=E=>{if(!b||y)return Promise.resolve();try{let N=b.finish(E);if(!N)return Promise.resolve();let L=`${x}:turn`,C={operationKey:L,runKey:x,turnId:O.turnId,outcome:E,...N};return f(L,()=>t.writeTurn({...C,body:Uint8Array.from(C.body)}))}catch(N){return y=N,Promise.resolve()}};u=!0;try{m===void 0&&await fe(f(x,()=>t.prepareRun({runKey:x,...O===void 0?{}:{turnId:O.turnId}})),k)}catch(E){throw w("interrupted").catch(()=>{}),S(x,"interrupted").catch(()=>{}).finally(()=>{a===I&&(a=void 0),I.release()}),E}finally{u=!1}let R,A=()=>{if(R)throw new Error("Session capture run ended")},j=E=>{A();try{E()}catch(N){throw y=N,N}},F={...b===void 0?{}:{appendTurnMessages(E){j(()=>b.append(E))},stageTurnAssistant(E){j(()=>b.stageAssistant(E))},discardTurnAssistant(){A(),b.discardAssistant()},markTurnIncomplete(){j(()=>b.markIncomplete())}},captureGovernance({messages:E,signal:N}){return A(),N?.throwIfAborted(),fe(_("governance",E,!0,x),N)},captureMaterial(E,N,L){return A(),_(E,N,L,x)},captureVisibleText(E,N){A();let L=0;for(let C of E)if(L+=Buffer.byteLength(C,"utf8"),L>r.maxBytes||E.length>1e5)throw y=new re("limit_exceeded"),y;return _("stream.material",[{role:"assistant",blocks:[{t:"text",text:E.join("")}]}],N,x)},finish(E){return R||(w(E).catch(()=>{}),R=S(x,E).finally(()=>{a===I&&(a=void 0),I.release()})),R}};return Cn.set(F,{capture:D,methods:gt(F),read(){if(A(),!b||!O||a!==I||u||g.size>0||d.size>0||y)throw new Error("Session capture reconciliation required");let E=Ie.get(t);if(!E||!Re(t,E.methods))throw new Error("Session capture recovery identity mismatch");return{version:1,configuration:s,owner:o,sequence:c,runKey:x,turnId:O.turnId,fullTurn:kn(b),sink:E.read(x)}}}),F}};return En.set(D,k=>{if(a||u||g.size>0||y)throw new Error("Session capture reconciliation required");if(!t.writeTurn)throw new Error("Unadmitted input finalization requires full turn capture");let m=mt(k.facts.inputMessages,r,n).finish("aborted");if(!m||m.turnState!=="cancelled"||m.toolCallCount!==0||m.pendingToolCalls!==0)throw new Error("Unadmitted input finalization is not a complete input-only turn");let b=h(),p=b+":turn",I=b+":terminal",x={operationKey:p,runKey:b,turnId:k.turnId,outcome:"aborted",...m},w=!1,R=!1,A=!1,j,F=[[b,async()=>{await k.prepare(b),w=!0}],[p,async()=>{if(!w)throw new Error("Session capture reconciliation required");k.validate(b),await t.writeTurn({...x,body:Uint8Array.from(x.body)}),R=!0}],[I,async()=>{if(!R)throw new Error("Session capture reconciliation required");k.validate(b);let C=!y&&[...g.keys()].every(M=>M===I);if(!C)throw new Error("Session capture reconciliation required");await t.finishRun({runKey:b,outcome:"aborted",materialsComplete:C})}]],E=()=>{if(a||u||y)throw new Error("Session capture reconciliation required");let C,M={ended:new Promise(U=>{C=U}),release:()=>C()};return a=M,u=!0,()=>{u=!1,a===M&&(a=void 0),M.release()}},N=E(),L=Promise.allSettled(F.map(([C,M])=>f(C,M))).then(C=>{let M=C.find(U=>U.status==="rejected");if(M?.status==="rejected")throw M.reason}).finally(()=>{A=!0,N()});return Object.freeze({outcome:L,retryOriginal(){if(!A)return L;if(j!==void 0)return j;let C=Promise.resolve().then(async()=>{let M=E();try{k.validate(b);for(let[U]of F){let W=g.get(U);W!==void 0&&await f(U,W)}if(k.validate(b),F.some(([U])=>g.has(U)))throw new Error("Session capture reconciliation required")}finally{M()}});return j=C,C.catch(()=>{j===C&&(j=void 0)}),C}})}),yt.set(D,t),ht.set(D,{methods:gt(D),restore(k,O){O?.throwIfAborted();let m=structuredClone(k);if(!m||m.version!==1||m.configuration!==s||typeof m.owner!="string"||!/^[0-9a-f-]{36}$/.test(m.owner)||!Number.isSafeInteger(m.sequence)||m.sequence<1||typeof m.runKey!="string"||!m.runKey.startsWith(`capture:${m.owner}:`)||!Number.isSafeInteger(Number(m.runKey.slice(m.runKey.lastIndexOf(":")+1)))||Number(m.runKey.slice(m.runKey.lastIndexOf(":")+1))>m.sequence||typeof m.turnId!="string"||!m.turnId||a||u||i||c!==0)throw new Error("Session capture recovery identity mismatch");return i=m,D.beginRun({...O===void 0?{}:{signal:O},turn:{turnId:m.turnId,initialMessages:[]}})}}),On.set(D,()=>{if(a||u||g.size>0||d.size>0||y)throw new Error("Session capture reconciliation required")}),D}async function bi(e){let t=[...e.messages],n=structuredClone(e.messages),r=structuredClone(n),o=()=>{if(e.signal?.throwIfAborted(),!e.isCurrent()||t.length!==e.messages.length||t.some((l,g)=>l!==e.messages[g])||!wn(e.messages,n)||!wn(r,n))throw new Error("Governance capture source changed before publication")};o();let s=e.capture.captureGovernance({messages:r});s.catch(()=>{}),e.onPending?.(s),await fe(s,e.signal),o();let i=!1,c=[];return{assertSourceCurrent:o,defer(l){if(i)throw new Error("Governance publication already accepted");c.push(l)},accept(){if(!i){i=!0;for(let l of c)try{l()}catch{}c.length=0}}}}import{types as Pn}from"node:util";function H(){throw new TypeError("Invalid query settlement snapshot")}function se(e){return(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&H(),e}function Ue(e,t,n=[]){(e===null||typeof e!="object"||Pn.isProxy(e))&&H();let r=Object.getPrototypeOf(e);r!==null&&r!==Object.prototype&&H();let o=Object.create(null);for(let s of Reflect.ownKeys(e)){(typeof s!="string"||!t.includes(s)&&!n.includes(s))&&H();let i=Object.getOwnPropertyDescriptor(e,s);(!i.enumerable||!Object.hasOwn(i,"value"))&&H(),o[s]=i.value}for(let s of t)Object.hasOwn(o,s)||H();return o}function _n(e,t){(e===null||typeof e!="object"||Pn.isProxy(e)||!Array.isArray(e)||Object.getPrototypeOf(e)!==Array.prototype)&&H();let n=se(Object.getOwnPropertyDescriptor(e,"length")?.value);return(n>t||Reflect.ownKeys(e).length!==n+1)&&H(),Array.from({length:n},(r,o)=>{let s=Object.getOwnPropertyDescriptor(e,String(o));return(!s?.enumerable||!Object.hasOwn(s,"value"))&&H(),s.value})}function An(e){return(e===null||typeof e!="object")&&H(),e}function Ri(e){let t=Ue(e,["status","pending","failures","failureCount","omittedFailures"],["sources"]);["completed","failed","timeout","cancelled"].includes(t.status)||H();let n=Ue(t.pending,["execution","modelStreams","toolExecutors"]),r=se(t.failureCount),o=se(t.omittedFailures),s=_n(t.failures,32).map(c=>{let l=Ue(c,["operationId","phase","cause"],["sourceId","scope"]);return l.phase!=="model_stream"&&l.phase!=="tool_executor"&&H(),l.scope!==void 0&&l.scope!=="query"&&l.scope!=="compaction"&&H(),Object.freeze({operationId:se(l.operationId),phase:l.phase,cause:l.cause,...l.sourceId===void 0?{}:{sourceId:An(l.sourceId)},...l.scope===void 0?{}:{scope:l.scope}})});(r<s.length||o!==r-s.length)&&H();let i=t.sources===void 0?void 0:_n(t.sources,65536).map(c=>{let l=Ue(c,["sourceId","failureCount"]);return Object.freeze({sourceId:An(l.sourceId),failureCount:se(l.failureCount)})});if(i?.length){let c=new Set,l=0;for(let g of i)c.has(g.sourceId)&&H(),c.add(g.sourceId),l=se(l+g.failureCount);(l!==r||s.some(g=>g.sourceId!==void 0&&!c.has(g.sourceId)))&&H()}return Object.freeze({status:t.status,pending:Object.freeze({execution:se(n.execution),modelStreams:se(n.modelStreams),toolExecutors:se(n.toolExecutors)}),failures:Object.freeze(s),failureCount:r,omittedFailures:o,...i===void 0?{}:{sources:Object.freeze(i)}})}import{types as jn}from"node:util";var Bn=Promise,So=Promise.prototype.then,ko=Reflect.apply,vo=queueMicrotask,qn=new WeakMap,bt=new WeakMap;function wo(e){let t=e;for(;t!==null;){if(jn.isProxy(t))return{state:"unobservable",phase:"capture",reason:new TypeError("Proxy query handle is not observable")};let n=Object.getOwnPropertyDescriptor(t,"settle");if(n!==void 0)return Object.hasOwn(n,"value")?n.value===void 0?{state:"unavailable"}:typeof n.value!="function"||jn.isProxy(n.value)?{state:"unobservable",phase:"capture",reason:new TypeError("Settlement method is not observable")}:{state:"method",method:n.value}:{state:"unobservable",phase:"capture",reason:new TypeError("Accessor settlement method is not observable")};t=Object.getPrototypeOf(t)}return{state:"unavailable"}}function Mi(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Query handle must be an object");let t=qn.get(e);if(t!==void 0)return t;let n=wo(e);try{qt(e)}catch(a){n={state:"unobservable",phase:"capture",reason:a}}let r,o=new Bn(a=>{r=a}),s,i=new Bn(a=>{s=a});Object.freeze(o),Object.freeze(i);let c=Object.freeze({eventsEnded:o,outcome:i});bt.set(c,e);let l=!1,d=Object.freeze({markEventsEnded:()=>{l||(l=!0,r(),vo(()=>{if(n.state!=="method"){s(Object.freeze(n));return}let a;try{a=ko(n.method,e,[{timeoutMs:1/0}])}catch(u){s(Object.freeze({state:"unobservable",phase:"invoke",reason:u}));return}try{let u=ge(a);So.call(u,y=>{s(Object.freeze({state:"fulfilled",result:y}))},y=>{s(Object.freeze({state:"rejected",reason:y}))})}catch(u){s(Object.freeze({state:"unobservable",phase:"observe",reason:u}))}}))},receipt:c});return qn.set(e,d),d}function Ci(e,t){if(!bt.has(e)||bt.get(e)!==t)throw new TypeError("Original query settlement receipt identity mismatch");return e}export{No as a,Do as b,Fo as c,Lo as d,Uo as e,$o as f,Ko as g,Wn as h,we as i,Qe as j,Vo as k,Nt as l,Dt as m,Bt as n,$t as o,Qn as p,Ze as q,et as r,tr as s,or as t,es as u,ts as v,ns as w,Me as x,zt as y,Ce as z,qe as A,Yt as B,Te as C,ds as D,fs as E,tn as F,rt as G,ms as H,on as I,xs as J,sn as K,Is as L,Tr as M,Or as N,Er as O,ks as P,_r as Q,it as R,Ar as S,Pr as T,vs as U,Br as V,at as W,ws as X,Nr as Y,Dr as Z,Ms as _,G as $,lt as aa,Kr as ba,Hr as ca,Vr as da,Qr as ea,Yr as fa,Ds as ga,Fs as ha,ut as ia,be as ja,Fe as ka,hn as la,bo as ma,ie as na,We as oa,wt as pa,Kn as qa,Gn as ra,zn as sa,At as ta,ne as ua,Mt as va,Hn as wa,Tt as xa,Ot as ya,Ao as za,Po as Aa,Ys as Ba,ui as Ca,di as Da,fi as Ea,Tn as Fa,pi as Ga,mi as Ha,gi as Ia,yi as Ja,Ro as Ka,hi as La,bi as Ma,Ri as Na,Mi as Oa,Ci as Pa};
|
|
37
|
-
//# sourceMappingURL=tansr-chunk-ZQ3ZK7IL.mjs.map
|
package/tansr-main-5V46X7QH.mjs
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
3
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
4
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
5
|
-
import{b as f,d as E}from"./tansr-chunk-PIET7WB3.mjs";import{a as u}from"./tansr-chunk-AMMPDY4V.mjs";import{a as m}from"./tansr-chunk-5T7X32UX.mjs";import{i as v}from"./tansr-chunk-XXBNISJJ.mjs";import"./tansr-chunk-HRKJLVKC.mjs";import"./tansr-chunk-C7GGA5ID.mjs";import"./tansr-chunk-OKAA4BJC.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import{b as l,k as w,m as r,o as d}from"./tansr-chunk-NA22YT73.mjs";import"./tansr-chunk-RRAMVVYF.mjs";l();w(d({env:process.env}));var s="0.10.2";function g(t){return t.some(o=>o==="-p"||o==="--prompt"||o.startsWith("--prompt="))}async function y(t){let o=import("./tansr-src-JAODAP53.mjs").then(i=>({ok:!0,runtime:i}),i=>({ok:!1,error:i})),{runTuiEntry:n}=await import("./tansr-tui-DXGFMSII.mjs");return n(t,o)}var e=process.argv.slice(2);f(process.env);e[0]!=="init"&&v();if(m(e)){let{resolvePortalKeysUrl:t}=await import("./tansr-portal-FWLKNJM2.mjs"),{renderHelpForArgv:o}=await import("./tansr-render-PUEISX75.mjs");console.log(o(e,s,t(process.env)))}else if(e[0]==="serve"){let{runServeEntry:t}=await import("./tansr-run-serve-entry-N5PK7ACI.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="orchestrate"){let{runOrchestrateEntry:t}=await import("./tansr-run-orchestrate-entry-YN3M6BWY.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="approvals"){let{runApprovalsEntry:t}=await import("./tansr-run-approvals-entry-SLLTFTSX.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="policy"){let{runPolicyEntry:t}=await import("./tansr-run-policy-entry-4ENHRAMQ.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="mcp"&&e[1]==="serve"){let{runMcpServeEntry:t}=await import("./tansr-run-mcp-serve-entry-YMQH7WSF.mjs"),o=await t({version:s,trustProjectHooks:e.includes(E)});process.exit(o)}else if(e[0]==="acp"){let{runAcpEntry:t}=await import("./tansr-run-acp-entry-ANNUR7IB.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="doctor"){let{runDoctorEntry:t}=await import("./tansr-run-doctor-RYIQQOOK.mjs"),o=await t(e.slice(1),{version:s});process.exit(o)}else if(e[0]==="update"){let{runUpdateEntry:t}=await import("./tansr-run-update-entry-HYSKHBB6.mjs"),o=await t(e.slice(1),{version:s});process.exit(o)}else if(e[0]==="bg"){let{runBgEntry:t}=await import("./tansr-bg-QY4G2SNZ.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="sessions"){let{runSessionsEntry:t}=await import("./tansr-run-sessions-entry-KIT7PALM.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="init"){let{runInitEntry:t}=await import("./tansr-run-init-entry-USPWKDRI.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="logout"){let{runLogoutEntry:t}=await import("./tansr-run-logout-entry-KO7ZL2M5.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="login"||e[0]==="whoami"){let{runAuthCommand:t}=await import("./tansr-run-auth-entry-X3SXNPOI.mjs"),o=await t(e[0],e.slice(1));process.exit(o)}else if(e[0]==="profile"){let{runProfileEntry:t}=await import("./tansr-run-profile-entry-THJMZ7ZA.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e[0]==="org"){let{runOrgEntry:t}=await import("./tansr-run-org-entry-STRRZVI4.mjs"),o=await t(e.slice(1));process.exit(o)}else if(e.includes("--version")||e.includes("-v"))console.log(r("cli.version",{version:s}));else if(process.env.TANSR_STARTUP_PROBE==="1"){let t=await y(e);process.exit(t)}else if(g(e)||process.stdin.isTTY!==!0){let t=a=>{process.stderr.write(a+`
|
|
6
|
-
`)},{startBackgroundRunnerEndpoint:o,finalizeBackgroundTask:n}=await import("./tansr-bg-QY4G2SNZ.mjs"),{runHeadlessEntry:i}=await import("./tansr-run-headless-entry-I53HJDNX.mjs"),p=await o(process.env,t),c;try{c=await i(e)}catch(a){throw await p.close(),await n(process.env,u.modelError,t),a}await p.close(),await n(process.env,c,t),process.exit(c)}else if(process.stdout.isTTY===!0){let t=await y(e);process.exit(t)}else{let{PROTOCOL_VERSION:t}=await import("./tansr-src-KOEPYVXX.mjs");console.log(r("cli.greeting")),console.log(r("cli.version",{version:s})),console.log(r("cli.protocol_version",{version:t}))}
|
|
7
|
-
//# sourceMappingURL=tansr-main-5V46X7QH.mjs.map
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
|
|
2
|
-
import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
|
|
3
|
-
const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
|
|
4
|
-
import{b as r}from"./tansr-chunk-5T7X32UX.mjs";import"./tansr-chunk-DIT3PBNB.mjs";import{m as l}from"./tansr-chunk-NA22YT73.mjs";import"./tansr-chunk-RRAMVVYF.mjs";var c=[{id:"serve",tokens:["serve"],usages:[{}],flags:[{id:"port",name:"--port",value:"<n>",default:"7433"},{id:"host",name:"--host",value:"<addr>",default:"127.0.0.1"},{id:"token",name:"--token",value:"<token>",default:"$TANSR_SERVE_TOKEN"},{id:"model",name:"--model",value:"<alias>",default:"main"},{id:"lang",name:"--lang",value:"<locale>"},{id:"context_scheme",name:"--context-scheme",value:"<id>"},{id:"sessions_dir",name:"--sessions-dir",value:"<dir>",default:"~/.tansr"},{id:"checkpoints_dir",name:"--checkpoints-dir",value:"<dir>"},{id:"cwd",name:"--cwd",value:"<dir>",default:"."},{id:"v2",name:"--v2",default:"$TANSR_SERVE_V2"},{id:"legacy_v1",name:"--legacy-v1",default:"$TANSR_SERVE_LEGACY_V1"},{id:"host_module",name:"--host-module",value:"<absolute.cjs>"},{id:"host_module_sha256",name:"--host-module-sha256",value:"<sha256>"}]},{id:"orchestrate",tokens:["orchestrate"],usages:[{}],flags:[{id:"port",name:"--port",value:"<n>",default:"7420"},{id:"host",name:"--host",value:"<addr>",default:"127.0.0.1"},{id:"config",name:"--config",value:"<path>"}]},{id:"approvals",tokens:["approvals"],usages:[{args:"list"},{args:"decide <id> --approve|--reject"}],actions:["list","decide"],flags:[{id:"status",name:"--status",value:"pending|history|all",default:"pending"},{id:"approve",name:"--approve"},{id:"reject",name:"--reject"},{id:"comment",name:"--comment",value:"<text>"},{id:"actor",name:"--actor",value:"<name>",default:"$TANSRD_ACTOR"},{id:"server",name:"--server",value:"<url>",default:"$TANSRD_SERVER"},{id:"token",name:"--token",value:"<token>",default:"$TANSRD_TOKEN"}]},{id:"policy",tokens:["policy"],usages:[{args:"pull"}],actions:["pull"],flags:[{id:"server",name:"--server",value:"<url>",default:"$TANSRD_SERVER"},{id:"token",name:"--token",value:"<token>",default:"$TANSRD_TOKEN"},{id:"workspace",name:"--workspace",value:"<name>",default:"default"},{id:"label",name:"--label",value:"<k=v>"},{id:"dir",name:"--dir",value:"<dir>",default:"~/.tansr/policies"}]},{id:"mcp_serve",tokens:["mcp","serve"],usages:[{flags:!1}],flags:[]},{id:"acp",tokens:["acp"],usages:[{}],flags:[{id:"model",name:"--model",value:"<alias>",default:"main"},{id:"lang",name:"--lang",value:"<locale>"},{id:"context_scheme",name:"--context-scheme",value:"<id>"},{id:"allowed_roots",name:"--allowed-roots",value:"<dir[;dir]>"}]},{id:"doctor",tokens:["doctor"],usages:[{}],flags:[{id:"json",name:"--json"},{id:"dump_config",name:"--dump-config"},{id:"connectors",name:"--connectors"},{id:"tansrd_config",name:"--tansrd-config",value:"<path>"},{id:"tansrd_url",name:"--tansrd-url",value:"<url>"}]},{id:"update",tokens:["update"],usages:[{}],flags:[{id:"install",name:"--install"},{id:"allow_unsigned",name:"--allow-unsigned"}]},{id:"bg",tokens:["bg"],usages:[{args:"[list]"},{args:"show <id>"},{args:"kill <id>"},{args:"clean"}],actions:["list","show","kill","clean"],flags:[{id:"json",name:"--json"},{id:"all",name:"--all"}]},{id:"sessions",tokens:["sessions"],usages:[{args:"export <id>"},{args:"prune"}],actions:["export","prune"],flags:[{id:"format",name:"--format",value:"md|json",default:"md"},{id:"out",name:"--out",value:"<path>"},{id:"apply",name:"--apply"},{id:"keep_days",name:"--keep-days",value:"<n>",default:"90"},{id:"keep_last",name:"--keep-last",value:"<n>",default:"500"},{id:"include_broken",name:"--include-broken"}]},{id:"init",tokens:["init"],usages:[{}],flags:[{id:"pat",name:"--pat",value:"<token>",default:"$TANSR_PAT"},{id:"fresh",name:"--fresh"}]},{id:"logout",tokens:["logout"],usages:[{}],flags:[{id:"keep_remote",name:"--keep-remote"}]},{id:"login",tokens:["login"],usages:[{}],flags:[{id:"key_id",name:"--key-id",value:"<id>"},{id:"key",name:"--key",value:"<key>"}]},{id:"whoami",tokens:["whoami"],usages:[{flags:!1}],flags:[]},{id:"profile",tokens:["profile"],usages:[{args:"list",flags:!1},{args:"use <keyId>",flags:!1}],actions:["list","use"],flags:[]},{id:"org",tokens:["org"],usages:[{args:"activate <code>",flags:!1}],actions:["activate"],flags:[]}];function g(n){return c.find(a=>a.tokens.every((s,e)=>n[e]===s))}var u={usageLabel:"cli.help.cmd.usage_label",flagsPlaceholder:"cli.help.cmd.flags_placeholder",flagsHeader:"cli.help.cmd.flags_header",noFlags:"cli.help.cmd.no_flags",actionsHeader:"cli.help.cmd.actions_header",exampleHeader:"cli.help.cmd.example_header",colFlag:"cli.help.cmd.col_flag",colValue:"cli.help.cmd.col_value",colDefault:"cli.help.cmd.col_default",colDescription:"cli.help.cmd.col_description",globalHint:"cli.help.cmd.global_hint"},E=Object.values(u);function p(n){let a=`cli.help.${n.id}`,s={};for(let o of n.flags)s[o.id]=`${a}.flags.${o.id}`;let e={};for(let o of n.actions??[])e[o]=`${a}.actions.${o}`;return{summary:`${a}.summary`,example:`${a}.example`,flags:s,actions:e}}function H(){let n=[];for(let a of c){let s=p(a);n.push(s.summary,s.example,...Object.values(s.flags),...Object.values(s.actions))}return n}function m(n){let a=0;for(let s of n){let e=s.codePointAt(0)??0;a+=e>=4352&&e<=4447||e>=11904&&e<=42191||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65072&&e<=65103||e>=65280&&e<=65376||e>=65504&&e<=65510?2:1}return a}function h(n,a){return n+" ".repeat(Math.max(0,a-m(n)))}function f(n){let a=n.reduce((e,o)=>Math.max(e,o.length),0),s=[];for(let e=0;e<a-1;e++)s[e]=n.reduce((o,t)=>Math.max(o,m(t[e]??"")),0);return n.map(e=>e.map((o,t)=>t<a-1?h(o,s[t]??0):o).join(" ").trimEnd())}function v(n){let a=l(u.flagsPlaceholder);return n.usages.map(s=>{let e=["tansr",...n.tokens];return s.args!==void 0&&e.push(s.args),s.flags!==!1&&e.push(a),e.join(" ")})}function k(n){let a=u,s=p(n),e=l(a.usageLabel),o=v(n),t=[];if(o.forEach((d,i)=>{t.push(i===0?`${e} ${d}`:`${" ".repeat(m(e))} ${d}`)}),t.push("",` ${l(s.summary)}`),n.actions!==void 0&&n.actions.length>0&&(t.push("",l(a.actionsHeader)),t.push(...f(n.actions.map(d=>[` ${d}`,l(s.actions[d]??"")])))),t.push("",l(a.flagsHeader)),n.flags.length===0)t.push(l(a.noFlags));else{let d=[[` ${l(a.colFlag)}`,l(a.colValue),l(a.colDefault),l(a.colDescription)]];for(let i of n.flags)d.push([` ${i.name}`,i.value??"-",i.default??"-",l(s.flags[i.id]??"")]);t.push(...f(d))}return t.push("",l(a.exampleHeader),` ${l(s.example)}`,"",l(a.globalHint)),t.join(`
|
|
5
|
-
`)}function $(n,a,s){let e=g(n);return e!==void 0?k(e):s===void 0?r(a):r(a,s)}export{u as COMMAND_HELP_MESSAGE_KEY,E as COMMAND_HELP_MESSAGE_KEYS,H as allCommandHelpKeys,p as commandHelpKeys,k as renderCommandHelp,$ as renderHelpForArgv};
|
|
6
|
-
//# sourceMappingURL=tansr-render-PUEISX75.mjs.map
|