@pinta-ai/pinta-copilot 0.12.1-pta1010.1 → 0.12.1
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/CHANGELOG.md +7 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to pinta-copilot are documented here.
|
|
4
4
|
|
|
5
|
+
## [0.12.1] - 2026-11-27
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- Stable release of `0.12.1-pta1010.1`. Bundles Core `0.11.1`, which is the same code as
|
|
10
|
+
Core `0.11.1-pta1010.2`. No behavior change from the Stage candidate.
|
|
11
|
+
|
|
5
12
|
## [0.12.1-pta1010.1] - 2026-11-26
|
|
6
13
|
|
|
7
14
|
### Fixed
|
package/dist/index.js
CHANGED
|
@@ -58,6 +58,6 @@ ${o.guidance}
|
|
|
58
58
|
${o.text}`:`${o.notice}
|
|
59
59
|
|
|
60
60
|
${o.guidance}`;return JSON.stringify({modifiedResult:{resultType:"success",textResultForLlm:m}})}return null}var Se=X(Le());function Ds(){let t=process.env.COPILOT_PLUGIN_OPTION_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,n=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,a;return t?a=t.replace(/\/+$/,""):n&&(a=n.replace(/\/+$/,"")+"/v1/traces"),a?{endpoint:a,headers:(0,Se.parseHeadersEnv)(process.env.COPILOT_PLUGIN_OPTION_HEADERS||process.env.OTEL_EXPORTER_OTLP_HEADERS)}:null}var ri=class extends Se.DiskTransport{constructor(n){super({pluginData:n.pluginData,logPrefix:"pinta-copilot",resolveOptions:Ds})}};function Vs(t,n){if(!Ds())return;let a=Buffer.byteLength(JSON.stringify(t),"utf-8");if(a>Se.MAX_POST_BYTES){process.stderr.write(`[pinta-copilot] dropping oversized span payload (${a} > ${Se.MAX_POST_BYTES} bytes) - undeliverable, not queued
|
|
61
|
-
`);return}new Se.DiskRetryQueue(n.pluginData,"pinta-copilot").enqueue(t)}var Us=X(Le()),si=class extends Us.DiskSessionTraceManager{constructor(n){super(n.tracePath)}};var nn=X(require("crypto")),vt=X(require("fs")),tn=X(require("path")),tc=64,Bs=200,ic=6*60*60*1e3;function Fs(t,n){return nn.default.createHash("sha256").update(`${t??""}\0${et(n)}`).digest("hex").slice(0,32)}function et(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(et).join(",")}]`:`{${Object.entries(t).sort(([a],[s])=>a<s?-1:a>s?1:0).map(([a,s])=>`${JSON.stringify(a)}:${et(s)}`).join(",")}}`}var ai=class{filePath;constructor(n){this.filePath=tn.default.join(n.pluginData,"calls.json")}open(n,a,s){let c=nn.default.randomBytes(8).toString("hex"),h=n||"default",o=this.read(),f=Date.now(),d=js(o[h]??[],f);return d.push({k:Fs(a,s),id:c,t:f}),o[h]=d.slice(-tc),this.write(o),c}close(n,a,s){let c=n||"default",h=this.read(),o=js(h[c]??[],Date.now()),f=Fs(a,s),d=nc(o,f);if(d===-1)return o.length!==(h[c]??[]).length&&(h[c]=o,this.write(h)),null;let[m]=o.splice(d,1);return h[c]=o,this.write(h),m.id}read(){try{let n=JSON.parse(vt.default.readFileSync(this.filePath,"utf-8"));if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}write(n){try{vt.default.mkdirSync(tn.default.dirname(this.filePath),{recursive:!0});let a=Object.entries(n).filter(([,c])=>c.length>0),s=a.length>Bs?a.slice(-Bs):a;rc(this.filePath,JSON.stringify(Object.fromEntries(s)))}catch{}}};function js(t,n){return t.filter(a=>n-a.t<ic)}function nc(t,n){for(let a=t.length-1;a>=0;a-=1)if(t[a].k===n)return a;return-1}function rc(t,n){let a=`${t}.${process.pid}.tmp`;vt.default.writeFileSync(a,n),vt.default.renameSync(a,t)}var Xs=X(require("fs")),li=X(require("os")),on=X(require("path"));var oi="0.12.1-pta1010.1";var He=X(Le());var zs=X(require("node:path"));var ge=X(require("node:fs")),rn=X(require("node:path")),sc=new Set(["","unknown","undefined","null","n/a","none","auto","default"]),ac=256*1024,oc=1024*1024,uc=4096;function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function tt(t){let n=ce(t),a=n?"id"in n?n.id:n.name:t;if(typeof a!="string")return;let s=a.trim();if(!(s.startsWith("{")||s.startsWith("[")))return s.length<=512&&!/[\u0000-\u001f\u007f]/.test(s)&&!sc.has(s.toLowerCase())?s:void 0}function qs(t,n){delete t.model,n&&(t.model=n.name,!(n.source==="hook.model"&&t.model_source!==void 0)&&(t.model_source!==void 0&&(t.model_original_source=t.model_source),t.model_source=n.source))}function sn(t){return typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(t)?t:void 0}function _t(t,n){let a=n.filter(s=>t[s]!==void 0).map(s=>sn(t[s]));return a.length>0&&a[0]!==void 0&&a.every(s=>s===a[0])?a[0]:void 0}function Ge(t){let n=typeof t=="number"?t:typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(t)?Date.parse(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0}function Gs(t,n){let a=t.timestamp===void 0?Ge(n):Ge(t.timestamp);return a!==void 0&&a<=n?a:void 0}function Hs(t){if(typeof t!="string"||t.length>4096||/[\u0000-\u001f]/.test(t)||!rn.default.isAbsolute(t)||rn.default.extname(t)!==".jsonl")return;let n;try{n=ge.default.openSync(t,ge.default.constants.O_RDONLY|ge.default.constants.O_NONBLOCK|(ge.default.constants.O_NOFOLLOW??0));let a=ge.default.fstatSync(n);if(!a.isFile()||!Number.isSafeInteger(a.size)||a.size<=0)return;let s=Buffer.alloc(Math.min(a.size,ac));if(ge.default.readSync(n,s,0,s.length,0)!==s.length)return;let c=s.indexOf(10),h;if(c>=0)try{h=ce(JSON.parse(s.toString("utf8",0,c)))}catch{}let o=Math.max(0,a.size-oc),f=a.size<=s.length?s:Buffer.alloc(a.size-o);if(f!==s&&ge.default.readSync(n,f,0,f.length,o)!==f.length)return;let d=ge.default.fstatSync(n);if(d.size<a.size||d.size===a.size&&d.mtimeMs!==a.mtimeMs)return;let m=o>0?f.indexOf(10)+1:0,v=f.lastIndexOf(10);if(o>0&&m===0||v<m)return;let _=[],x=0;for(;v>m&&x<uc;){let b=f.lastIndexOf(10,v-1),E=Math.max(m,b+1),w=f.toString("utf8",E,v).trim();if(w){let C=ce(JSON.parse(w));C&&_.push(C)}v=E-1,x++}return _.reverse(),{first:h,rows:_,complete:o===0&&v<0&&f[f.length-1]===10}}catch{return}finally{if(n!==void 0)try{ge.default.closeSync(n)}catch{}}}function Ws(t){let n=t[0];return n&&t.every(a=>a?.name===n.name)?n:void 0}var cc=new Set(["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest"]),Ks=["agent_id","agentId"],$s=["turn_id","turnId"];function lc(t,n,a){let s=[t.transcript_path,t.transcriptPath].filter(c=>c!==void 0);return s.length?s.every(c=>c===s[0])?s[0]:void 0:a==="cli"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)?zs.default.join(Qi(),"session-state",n,"events.jsonl"):void 0}function ui(t,n){return t.agentId!==void 0&&t.agentId!==null?sn(t.agentId)===n&&n!==void 0:n===void 0&&ce(t.data)?.parentToolCallId==null}function Ys(t,n,a){let s=tt(t.model);if(s)return{name:s,source:"hook.model"};try{return fc(t,n,a)}catch{return}}function fc(t,n,a){let s=ni(t),c=["tool_use_id","toolUseId","tool_call_id","toolCallId"],h=_t(t,c),o=s==="SessionStart"&&t.source==="startup";if(!o&&!cc.has(s)||!o&&!h&&c.some(N=>t[N]!==void 0))return;let f=yt(t),d=hc(t);if(!o&&!h&&(!f||d===void 0))return;let m=_t(t,["session_id","sessionId"]),v=_t(t,Ks),_=_t(t,$s),x=Gs(t,a);if(!m||x===void 0||Ks.some(N=>t[N]!==void 0)&&!v||$s.some(N=>t[N]!==void 0)&&!_||!v&&["agent_name","agentName","agent_type","agentType"].some(N=>t[N]!==void 0))return;let b=Hs(lc(t,m,n)),E=b?.first,w=ce(E?.data),C=Ge(E?.timestamp);if(!b||E?.type!=="session.start"||w?.sessionId!==m||C===void 0||C>x||b.rows.some(N=>N.type==="session.start"&&ce(N.data)?.sessionId!==m))return;if(o){if(v||!b.complete||t.timestamp===void 0)return;let N=tt(w.selectedModel),O=C;for(let l of b.rows){if(l.type!=="session.model_change"||!ui(l,void 0))continue;let j=Ge(l.timestamp);if(j===void 0)return;if(j>x||j<O)continue;let J=tt(ce(l.data)?.newModel);if(j===O&&J!==N)return;N=J,O=j}return N?{name:N,source:"transcript.session.selected"}:void 0}if(!h)return pc(f,d,b.rows,v,_,C,x);let L=[];for(let N of b.rows){let O=ce(N.data),l=Ge(N.timestamp);if(!O||l===void 0||l>x||l<C||!ui(N,v)||_!==void 0&&O.turnId!==_)continue;let j=!1;if(N.type==="assistant.message"?j=Array.isArray(O.toolRequests)&&O.toolRequests.some(ne=>ce(ne)?.toolCallId===h):(N.type==="tool.execution_start"||N.type==="tool.execution_complete")&&(j=O.toolCallId===h),!j)continue;let J=tt(O.model);L.push(J?{name:J,source:`transcript.${N.type}`}:void 0)}return Ws(L)}function hc(t){let n=ii(t);if(typeof n!="string")return n;if(n.trim()==="")return{};try{return JSON.parse(n)}catch{return n}}function pc(t,n,a,s,c,h,o){let f=et(n),d=new Set,m;for(let _ of a){let x=ce(_.data),b=Ge(_.timestamp);if(!(!x||b===void 0||b>o||b<h)){if(_.type==="tool.execution_complete"&&typeof x.toolCallId=="string")d.add(x.toolCallId);else if(_.type==="user.message"||_.type==="abort"||_.type==="session.model_change")m&&(m.open=!1);else if(_.type==="assistant.turn_end")m&&ui(_,s)&&(m.open=!1);else if(_.type==="assistant.message"&&ui(_,s)){if(c!==void 0&&x.turnId!==c)continue;let E=tt(x.model),w=E?{name:E,source:"transcript.assistant.message.unique_call"}:void 0;m={open:!0,calls:new Map};for(let C of Array.isArray(x.toolRequests)?x.toolRequests:[]){let L=ce(C);!L||L.name!==t||typeof L.toolCallId!="string"||et(L.arguments)!==f||m.calls.set(L.toolCallId,w)}}}}if(!m?.open)return;let v=[...m.calls].filter(([_])=>!d.has(_));return v.length===1?v[0][1]:void 0}var ci;function dc(){if(ci===void 0)try{ci=li.default.userInfo().username}catch{ci=process.env.USER??process.env.LOGNAME??(typeof process.getuid=="function"?String(process.getuid()):"unknown")}return ci}var Js=oi,mc=new Set(["","unknown","undefined","null","n/a","none"]);function ye(t){let n=typeof t=="string"?t.trim():void 0;return n&&!mc.has(n.toLowerCase())?n:void 0}var gc=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function yc(t){let n=ye(t);return n&&gc.test(n)?n:void 0}function vc(t){let n=t?ye(t.copilot_version)??ye(t.copilotVersion)??ye(t.cli_version)??ye(t.cliVersion)??ye(t.version):void 0;return n||(an===void 0&&(an=_c()),an??void 0)}var an;function _c(){let t=ye(process.env.COPILOT_CLI_BINARY_VERSION)??ye(process.env.COPILOT_CLI_VERSION);if(t)return t;let n=ye(process.env.COPILOT_CLI_RESOLVED_DIST_DIR);if(n){let a=yc(on.default.basename(n));if(a)return a;let s=xc(n);if(s)return s}return null}function xc(t){try{let n=Xs.default.readFileSync(on.default.join(t,"package.json"),"utf8");return ye(JSON.parse(n).version)}catch{return}}var bc=new Set(["copilot.hook","copilot.tool_name","copilot.toolName","copilot.tool_use_id","copilot.toolUseId","copilot.session_id","copilot.sessionId","copilot.transcript_path","copilot.transcriptPath","copilot.cwd","copilot.permission_mode","copilot.surface","copilot.agent_id","copilot.agent_type","copilot.agent_name","copilot.agent_display_name","copilot.stop_reason","copilot.notification_type"]),Sc=new Set(["copilot.tool_input","copilot.toolInput","copilot.toolArgs","copilot.tool_response","copilot.tool_result","copilot.toolResult"]),Ec={skipRedactKeys:bc,bashContextKeys:Sc,outputForKey:(t,n)=>{if(t==="copilot.tool_response")return n;if(t==="copilot.tool_result"||t==="copilot.toolResult")return en({[t.slice(8)]:n})}},kc=new Set(["hook_event_name","hookEventName","hookName"]);function Ac(t,n,a){let s=Object.fromEntries(Object.entries(t).filter(([c])=>!kc.has(c)));return qs(s,Ys(t,n,a)),[{key:"ingest.type",value:{stringValue:"copilot"}},{key:"copilot.hook",value:{stringValue:gt(t)??"unknown"}},{key:"copilot.surface",value:{stringValue:n}},...(0,He.attrsFromRecord)(s,"copilot",Ec)]}function wc(t){let n=vc(t);return[{key:"service.name",value:{stringValue:"copilot"}},...n?[{key:"service.version",value:{stringValue:n}}]:[],{key:"telemetry.sdk.name",value:{stringValue:"pinta-copilot"}},{key:"telemetry.sdk.language",value:{stringValue:"nodejs"}},{key:"telemetry.sdk.version",value:{stringValue:Js}},{key:"process.pid",value:{intValue:process.pid}},{key:"process.owner",value:{stringValue:dc()}},{key:"host.name",value:{stringValue:li.default.hostname()}},{key:"host.arch",value:{stringValue:li.default.arch()}}]}function Zs(t){let n=t.now??Date.now();return(0,He.buildPayload)({traceId:t.traceId,spanName:`copilot.${(0,He.snakeCase)(gt(t.event)??"unknown")}`,attributes:[...Ac(t.event,t.surface,n),...t.callId?[{key:"pinta.call_id",value:{stringValue:t.callId}}]:[]],resource:wc(t.event),scope:{name:"pinta-copilot",version:Js},now:n})}var Qs=X(Le());function Oc(){return Number(process.env.PINTA_GUARD_TIMEOUT_MS)||100}var Tc=`pinta-copilot/${oi}`;function ea(t,n){return(0,Qs.evaluateGuard)(t,n,{timeoutMs:Oc(),token:process.env.PINTA_RELAY_TOKEN??"",disabled:process.env.PINTA_GUARD_DISABLED==="1",userAgent:Tc})}function Pc(t,n,a,s){try{if(Is(a)||n!=="PreToolUse"&&!Ns(n))return null;let c=new ai(t),h=yt(a),o=ii(a);return n==="PreToolUse"?c.open(s,h,o):c.close(s,h,o)}catch{return null}}async function Cc(){let t=[];for await(let n of process.stdin)t.push(n);return Buffer.concat(t).toString("utf-8")}async function ia(){try{let t=Os(),n=Ts(),a=await Cc(),s=JSON.parse(a),c=ni(s),h=Cs(s),o=new si(t),f=c==="UserPromptSubmit"?o.newTrace(h):o.currentTrace(h),d=Pc(t,c,s,h),m=Zs({event:s,traceId:f,surface:n,callId:d}),v=yt(s),_=null;if(Rs(c)&&!Ls(v)&&(_=await ea(m,process.env.PINTA_GUARD_ENDPOINT)),_?.decision==="DENY"){let b=Ms(c,_,n,s);b&&process.stdout.write(b+`
|
|
61
|
+
`);return}new Se.DiskRetryQueue(n.pluginData,"pinta-copilot").enqueue(t)}var Us=X(Le()),si=class extends Us.DiskSessionTraceManager{constructor(n){super(n.tracePath)}};var nn=X(require("crypto")),vt=X(require("fs")),tn=X(require("path")),tc=64,Bs=200,ic=6*60*60*1e3;function Fs(t,n){return nn.default.createHash("sha256").update(`${t??""}\0${et(n)}`).digest("hex").slice(0,32)}function et(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(et).join(",")}]`:`{${Object.entries(t).sort(([a],[s])=>a<s?-1:a>s?1:0).map(([a,s])=>`${JSON.stringify(a)}:${et(s)}`).join(",")}}`}var ai=class{filePath;constructor(n){this.filePath=tn.default.join(n.pluginData,"calls.json")}open(n,a,s){let c=nn.default.randomBytes(8).toString("hex"),h=n||"default",o=this.read(),f=Date.now(),d=js(o[h]??[],f);return d.push({k:Fs(a,s),id:c,t:f}),o[h]=d.slice(-tc),this.write(o),c}close(n,a,s){let c=n||"default",h=this.read(),o=js(h[c]??[],Date.now()),f=Fs(a,s),d=nc(o,f);if(d===-1)return o.length!==(h[c]??[]).length&&(h[c]=o,this.write(h)),null;let[m]=o.splice(d,1);return h[c]=o,this.write(h),m.id}read(){try{let n=JSON.parse(vt.default.readFileSync(this.filePath,"utf-8"));if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}write(n){try{vt.default.mkdirSync(tn.default.dirname(this.filePath),{recursive:!0});let a=Object.entries(n).filter(([,c])=>c.length>0),s=a.length>Bs?a.slice(-Bs):a;rc(this.filePath,JSON.stringify(Object.fromEntries(s)))}catch{}}};function js(t,n){return t.filter(a=>n-a.t<ic)}function nc(t,n){for(let a=t.length-1;a>=0;a-=1)if(t[a].k===n)return a;return-1}function rc(t,n){let a=`${t}.${process.pid}.tmp`;vt.default.writeFileSync(a,n),vt.default.renameSync(a,t)}var Xs=X(require("fs")),li=X(require("os")),on=X(require("path"));var oi="0.12.1";var He=X(Le());var zs=X(require("node:path"));var ge=X(require("node:fs")),rn=X(require("node:path")),sc=new Set(["","unknown","undefined","null","n/a","none","auto","default"]),ac=256*1024,oc=1024*1024,uc=4096;function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function tt(t){let n=ce(t),a=n?"id"in n?n.id:n.name:t;if(typeof a!="string")return;let s=a.trim();if(!(s.startsWith("{")||s.startsWith("[")))return s.length<=512&&!/[\u0000-\u001f\u007f]/.test(s)&&!sc.has(s.toLowerCase())?s:void 0}function qs(t,n){delete t.model,n&&(t.model=n.name,!(n.source==="hook.model"&&t.model_source!==void 0)&&(t.model_source!==void 0&&(t.model_original_source=t.model_source),t.model_source=n.source))}function sn(t){return typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(t)?t:void 0}function _t(t,n){let a=n.filter(s=>t[s]!==void 0).map(s=>sn(t[s]));return a.length>0&&a[0]!==void 0&&a.every(s=>s===a[0])?a[0]:void 0}function Ge(t){let n=typeof t=="number"?t:typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(t)?Date.parse(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0}function Gs(t,n){let a=t.timestamp===void 0?Ge(n):Ge(t.timestamp);return a!==void 0&&a<=n?a:void 0}function Hs(t){if(typeof t!="string"||t.length>4096||/[\u0000-\u001f]/.test(t)||!rn.default.isAbsolute(t)||rn.default.extname(t)!==".jsonl")return;let n;try{n=ge.default.openSync(t,ge.default.constants.O_RDONLY|ge.default.constants.O_NONBLOCK|(ge.default.constants.O_NOFOLLOW??0));let a=ge.default.fstatSync(n);if(!a.isFile()||!Number.isSafeInteger(a.size)||a.size<=0)return;let s=Buffer.alloc(Math.min(a.size,ac));if(ge.default.readSync(n,s,0,s.length,0)!==s.length)return;let c=s.indexOf(10),h;if(c>=0)try{h=ce(JSON.parse(s.toString("utf8",0,c)))}catch{}let o=Math.max(0,a.size-oc),f=a.size<=s.length?s:Buffer.alloc(a.size-o);if(f!==s&&ge.default.readSync(n,f,0,f.length,o)!==f.length)return;let d=ge.default.fstatSync(n);if(d.size<a.size||d.size===a.size&&d.mtimeMs!==a.mtimeMs)return;let m=o>0?f.indexOf(10)+1:0,v=f.lastIndexOf(10);if(o>0&&m===0||v<m)return;let _=[],x=0;for(;v>m&&x<uc;){let b=f.lastIndexOf(10,v-1),E=Math.max(m,b+1),w=f.toString("utf8",E,v).trim();if(w){let C=ce(JSON.parse(w));C&&_.push(C)}v=E-1,x++}return _.reverse(),{first:h,rows:_,complete:o===0&&v<0&&f[f.length-1]===10}}catch{return}finally{if(n!==void 0)try{ge.default.closeSync(n)}catch{}}}function Ws(t){let n=t[0];return n&&t.every(a=>a?.name===n.name)?n:void 0}var cc=new Set(["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest"]),Ks=["agent_id","agentId"],$s=["turn_id","turnId"];function lc(t,n,a){let s=[t.transcript_path,t.transcriptPath].filter(c=>c!==void 0);return s.length?s.every(c=>c===s[0])?s[0]:void 0:a==="cli"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)?zs.default.join(Qi(),"session-state",n,"events.jsonl"):void 0}function ui(t,n){return t.agentId!==void 0&&t.agentId!==null?sn(t.agentId)===n&&n!==void 0:n===void 0&&ce(t.data)?.parentToolCallId==null}function Ys(t,n,a){let s=tt(t.model);if(s)return{name:s,source:"hook.model"};try{return fc(t,n,a)}catch{return}}function fc(t,n,a){let s=ni(t),c=["tool_use_id","toolUseId","tool_call_id","toolCallId"],h=_t(t,c),o=s==="SessionStart"&&t.source==="startup";if(!o&&!cc.has(s)||!o&&!h&&c.some(N=>t[N]!==void 0))return;let f=yt(t),d=hc(t);if(!o&&!h&&(!f||d===void 0))return;let m=_t(t,["session_id","sessionId"]),v=_t(t,Ks),_=_t(t,$s),x=Gs(t,a);if(!m||x===void 0||Ks.some(N=>t[N]!==void 0)&&!v||$s.some(N=>t[N]!==void 0)&&!_||!v&&["agent_name","agentName","agent_type","agentType"].some(N=>t[N]!==void 0))return;let b=Hs(lc(t,m,n)),E=b?.first,w=ce(E?.data),C=Ge(E?.timestamp);if(!b||E?.type!=="session.start"||w?.sessionId!==m||C===void 0||C>x||b.rows.some(N=>N.type==="session.start"&&ce(N.data)?.sessionId!==m))return;if(o){if(v||!b.complete||t.timestamp===void 0)return;let N=tt(w.selectedModel),O=C;for(let l of b.rows){if(l.type!=="session.model_change"||!ui(l,void 0))continue;let j=Ge(l.timestamp);if(j===void 0)return;if(j>x||j<O)continue;let J=tt(ce(l.data)?.newModel);if(j===O&&J!==N)return;N=J,O=j}return N?{name:N,source:"transcript.session.selected"}:void 0}if(!h)return pc(f,d,b.rows,v,_,C,x);let L=[];for(let N of b.rows){let O=ce(N.data),l=Ge(N.timestamp);if(!O||l===void 0||l>x||l<C||!ui(N,v)||_!==void 0&&O.turnId!==_)continue;let j=!1;if(N.type==="assistant.message"?j=Array.isArray(O.toolRequests)&&O.toolRequests.some(ne=>ce(ne)?.toolCallId===h):(N.type==="tool.execution_start"||N.type==="tool.execution_complete")&&(j=O.toolCallId===h),!j)continue;let J=tt(O.model);L.push(J?{name:J,source:`transcript.${N.type}`}:void 0)}return Ws(L)}function hc(t){let n=ii(t);if(typeof n!="string")return n;if(n.trim()==="")return{};try{return JSON.parse(n)}catch{return n}}function pc(t,n,a,s,c,h,o){let f=et(n),d=new Set,m;for(let _ of a){let x=ce(_.data),b=Ge(_.timestamp);if(!(!x||b===void 0||b>o||b<h)){if(_.type==="tool.execution_complete"&&typeof x.toolCallId=="string")d.add(x.toolCallId);else if(_.type==="user.message"||_.type==="abort"||_.type==="session.model_change")m&&(m.open=!1);else if(_.type==="assistant.turn_end")m&&ui(_,s)&&(m.open=!1);else if(_.type==="assistant.message"&&ui(_,s)){if(c!==void 0&&x.turnId!==c)continue;let E=tt(x.model),w=E?{name:E,source:"transcript.assistant.message.unique_call"}:void 0;m={open:!0,calls:new Map};for(let C of Array.isArray(x.toolRequests)?x.toolRequests:[]){let L=ce(C);!L||L.name!==t||typeof L.toolCallId!="string"||et(L.arguments)!==f||m.calls.set(L.toolCallId,w)}}}}if(!m?.open)return;let v=[...m.calls].filter(([_])=>!d.has(_));return v.length===1?v[0][1]:void 0}var ci;function dc(){if(ci===void 0)try{ci=li.default.userInfo().username}catch{ci=process.env.USER??process.env.LOGNAME??(typeof process.getuid=="function"?String(process.getuid()):"unknown")}return ci}var Js=oi,mc=new Set(["","unknown","undefined","null","n/a","none"]);function ye(t){let n=typeof t=="string"?t.trim():void 0;return n&&!mc.has(n.toLowerCase())?n:void 0}var gc=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function yc(t){let n=ye(t);return n&&gc.test(n)?n:void 0}function vc(t){let n=t?ye(t.copilot_version)??ye(t.copilotVersion)??ye(t.cli_version)??ye(t.cliVersion)??ye(t.version):void 0;return n||(an===void 0&&(an=_c()),an??void 0)}var an;function _c(){let t=ye(process.env.COPILOT_CLI_BINARY_VERSION)??ye(process.env.COPILOT_CLI_VERSION);if(t)return t;let n=ye(process.env.COPILOT_CLI_RESOLVED_DIST_DIR);if(n){let a=yc(on.default.basename(n));if(a)return a;let s=xc(n);if(s)return s}return null}function xc(t){try{let n=Xs.default.readFileSync(on.default.join(t,"package.json"),"utf8");return ye(JSON.parse(n).version)}catch{return}}var bc=new Set(["copilot.hook","copilot.tool_name","copilot.toolName","copilot.tool_use_id","copilot.toolUseId","copilot.session_id","copilot.sessionId","copilot.transcript_path","copilot.transcriptPath","copilot.cwd","copilot.permission_mode","copilot.surface","copilot.agent_id","copilot.agent_type","copilot.agent_name","copilot.agent_display_name","copilot.stop_reason","copilot.notification_type"]),Sc=new Set(["copilot.tool_input","copilot.toolInput","copilot.toolArgs","copilot.tool_response","copilot.tool_result","copilot.toolResult"]),Ec={skipRedactKeys:bc,bashContextKeys:Sc,outputForKey:(t,n)=>{if(t==="copilot.tool_response")return n;if(t==="copilot.tool_result"||t==="copilot.toolResult")return en({[t.slice(8)]:n})}},kc=new Set(["hook_event_name","hookEventName","hookName"]);function Ac(t,n,a){let s=Object.fromEntries(Object.entries(t).filter(([c])=>!kc.has(c)));return qs(s,Ys(t,n,a)),[{key:"ingest.type",value:{stringValue:"copilot"}},{key:"copilot.hook",value:{stringValue:gt(t)??"unknown"}},{key:"copilot.surface",value:{stringValue:n}},...(0,He.attrsFromRecord)(s,"copilot",Ec)]}function wc(t){let n=vc(t);return[{key:"service.name",value:{stringValue:"copilot"}},...n?[{key:"service.version",value:{stringValue:n}}]:[],{key:"telemetry.sdk.name",value:{stringValue:"pinta-copilot"}},{key:"telemetry.sdk.language",value:{stringValue:"nodejs"}},{key:"telemetry.sdk.version",value:{stringValue:Js}},{key:"process.pid",value:{intValue:process.pid}},{key:"process.owner",value:{stringValue:dc()}},{key:"host.name",value:{stringValue:li.default.hostname()}},{key:"host.arch",value:{stringValue:li.default.arch()}}]}function Zs(t){let n=t.now??Date.now();return(0,He.buildPayload)({traceId:t.traceId,spanName:`copilot.${(0,He.snakeCase)(gt(t.event)??"unknown")}`,attributes:[...Ac(t.event,t.surface,n),...t.callId?[{key:"pinta.call_id",value:{stringValue:t.callId}}]:[]],resource:wc(t.event),scope:{name:"pinta-copilot",version:Js},now:n})}var Qs=X(Le());function Oc(){return Number(process.env.PINTA_GUARD_TIMEOUT_MS)||100}var Tc=`pinta-copilot/${oi}`;function ea(t,n){return(0,Qs.evaluateGuard)(t,n,{timeoutMs:Oc(),token:process.env.PINTA_RELAY_TOKEN??"",disabled:process.env.PINTA_GUARD_DISABLED==="1",userAgent:Tc})}function Pc(t,n,a,s){try{if(Is(a)||n!=="PreToolUse"&&!Ns(n))return null;let c=new ai(t),h=yt(a),o=ii(a);return n==="PreToolUse"?c.open(s,h,o):c.close(s,h,o)}catch{return null}}async function Cc(){let t=[];for await(let n of process.stdin)t.push(n);return Buffer.concat(t).toString("utf-8")}async function ia(){try{let t=Os(),n=Ts(),a=await Cc(),s=JSON.parse(a),c=ni(s),h=Cs(s),o=new si(t),f=c==="UserPromptSubmit"?o.newTrace(h):o.currentTrace(h),d=Pc(t,c,s,h),m=Zs({event:s,traceId:f,surface:n,callId:d}),v=yt(s),_=null;if(Rs(c)&&!Ls(v)&&(_=await ea(m,process.env.PINTA_GUARD_ENDPOINT)),_?.decision==="DENY"){let b=Ms(c,_,n,s);b&&process.stdout.write(b+`
|
|
62
62
|
`)}if((0,ta.attachGuard)(m,_),_&&c==="PostToolUse")for(let b of m.resourceSpans)for(let E of b.scopeSpans)for(let w of E.spans)w.attributes.push({key:"pinta.guard.target",value:{stringValue:"tool_output"}});if(_?.decision==="DENY")return Vs(m,t),0;let x=new ri(t);await x.flush(),await x.send(m)}catch(t){process.stderr.write(`[pinta-copilot] error: ${t}
|
|
63
63
|
`)}return 0}As();async function Ic(){let t=await ia();process.exit(t)}Ic();
|
package/dist/index.mjs
CHANGED
|
@@ -59,6 +59,6 @@ ${o.guidance}
|
|
|
59
59
|
${o.text}`:`${o.notice}
|
|
60
60
|
|
|
61
61
|
${o.guidance}`;return JSON.stringify({modifiedResult:{resultType:"success",textResultForLlm:m}})}return null}var be=Ue(Le());function Vs(){let t=process.env.COPILOT_PLUGIN_OPTION_ENDPOINT||process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,n=process.env.OTEL_EXPORTER_OTLP_ENDPOINT,a;return t?a=t.replace(/\/+$/,""):n&&(a=n.replace(/\/+$/,"")+"/v1/traces"),a?{endpoint:a,headers:(0,be.parseHeadersEnv)(process.env.COPILOT_PLUGIN_OPTION_HEADERS||process.env.OTEL_EXPORTER_OTLP_HEADERS)}:null}var ri=class extends be.DiskTransport{constructor(n){super({pluginData:n.pluginData,logPrefix:"pinta-copilot",resolveOptions:Vs})}};function Us(t,n){if(!Vs())return;let a=Buffer.byteLength(JSON.stringify(t),"utf-8");if(a>be.MAX_POST_BYTES){process.stderr.write(`[pinta-copilot] dropping oversized span payload (${a} > ${be.MAX_POST_BYTES} bytes) - undeliverable, not queued
|
|
62
|
-
`);return}new be.DiskRetryQueue(n.pluginData,"pinta-copilot").enqueue(t)}var Bs=Ue(Le()),si=class extends Bs.DiskSessionTraceManager{constructor(n){super(n.tracePath)}};import Hs from"crypto";import ai from"fs";import Fs from"path";var mc=64,js=200,gc=6*60*60*1e3;function qs(t,n){return Hs.createHash("sha256").update(`${t??""}\0${tt(n)}`).digest("hex").slice(0,32)}function tt(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(tt).join(",")}]`:`{${Object.entries(t).sort(([a],[r])=>a<r?-1:a>r?1:0).map(([a,r])=>`${JSON.stringify(a)}:${tt(r)}`).join(",")}}`}var oi=class{filePath;constructor(n){this.filePath=Fs.join(n.pluginData,"calls.json")}open(n,a,r){let c=Hs.randomBytes(8).toString("hex"),h=n||"default",o=this.read(),f=Date.now(),d=Gs(o[h]??[],f);return d.push({k:qs(a,r),id:c,t:f}),o[h]=d.slice(-mc),this.write(o),c}close(n,a,r){let c=n||"default",h=this.read(),o=Gs(h[c]??[],Date.now()),f=qs(a,r),d=yc(o,f);if(d===-1)return o.length!==(h[c]??[]).length&&(h[c]=o,this.write(h)),null;let[m]=o.splice(d,1);return h[c]=o,this.write(h),m.id}read(){try{let n=JSON.parse(ai.readFileSync(this.filePath,"utf-8"));if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}write(n){try{ai.mkdirSync(Fs.dirname(this.filePath),{recursive:!0});let a=Object.entries(n).filter(([,c])=>c.length>0),r=a.length>js?a.slice(-js):a;vc(this.filePath,JSON.stringify(Object.fromEntries(r)))}catch{}}};function Gs(t,n){return t.filter(a=>n-a.t<gc)}function yc(t,n){for(let a=t.length-1;a>=0;a-=1)if(t[a].k===n)return a;return-1}function vc(t,n){let a=`${t}.${process.pid}.tmp`;ai.writeFileSync(a,n),ai.renameSync(a,t)}import Pc from"fs";import sn from"os";import Zs from"path";var ui="0.12.1-pta1010.1";var We=Ue(Le());import Ec from"node:path";import Se from"node:fs";import Ws from"node:path";var _c=new Set(["","unknown","undefined","null","n/a","none","auto","default"]),xc=256*1024,bc=1024*1024,Sc=4096;function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function it(t){let n=ce(t),a=n?"id"in n?n.id:n.name:t;if(typeof a!="string")return;let r=a.trim();if(!(r.startsWith("{")||r.startsWith("[")))return r.length<=512&&!/[\u0000-\u001f\u007f]/.test(r)&&!_c.has(r.toLowerCase())?r:void 0}function $s(t,n){delete t.model,n&&(t.model=n.name,!(n.source==="hook.model"&&t.model_source!==void 0)&&(t.model_source!==void 0&&(t.model_original_source=t.model_source),t.model_source=n.source))}function nn(t){return typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(t)?t:void 0}function xt(t,n){let a=n.filter(r=>t[r]!==void 0).map(r=>nn(t[r]));return a.length>0&&a[0]!==void 0&&a.every(r=>r===a[0])?a[0]:void 0}function He(t){let n=typeof t=="number"?t:typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(t)?Date.parse(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0}function Ks(t,n){let a=t.timestamp===void 0?He(n):He(t.timestamp);return a!==void 0&&a<=n?a:void 0}function zs(t){if(typeof t!="string"||t.length>4096||/[\u0000-\u001f]/.test(t)||!Ws.isAbsolute(t)||Ws.extname(t)!==".jsonl")return;let n;try{n=Se.openSync(t,Se.constants.O_RDONLY|Se.constants.O_NONBLOCK|(Se.constants.O_NOFOLLOW??0));let a=Se.fstatSync(n);if(!a.isFile()||!Number.isSafeInteger(a.size)||a.size<=0)return;let r=Buffer.alloc(Math.min(a.size,xc));if(Se.readSync(n,r,0,r.length,0)!==r.length)return;let c=r.indexOf(10),h;if(c>=0)try{h=ce(JSON.parse(r.toString("utf8",0,c)))}catch{}let o=Math.max(0,a.size-bc),f=a.size<=r.length?r:Buffer.alloc(a.size-o);if(f!==r&&Se.readSync(n,f,0,f.length,o)!==f.length)return;let d=Se.fstatSync(n);if(d.size<a.size||d.size===a.size&&d.mtimeMs!==a.mtimeMs)return;let m=o>0?f.indexOf(10)+1:0,v=f.lastIndexOf(10);if(o>0&&m===0||v<m)return;let _=[],x=0;for(;v>m&&x<Sc;){let b=f.lastIndexOf(10,v-1),E=Math.max(m,b+1),A=f.toString("utf8",E,v).trim();if(A){let C=ce(JSON.parse(A));C&&_.push(C)}v=E-1,x++}return _.reverse(),{first:h,rows:_,complete:o===0&&v<0&&f[f.length-1]===10}}catch{return}finally{if(n!==void 0)try{Se.closeSync(n)}catch{}}}function Ys(t){let n=t[0];return n&&t.every(a=>a?.name===n.name)?n:void 0}var kc=new Set(["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest"]),Xs=["agent_id","agentId"],Js=["turn_id","turnId"];function wc(t,n,a){let r=[t.transcript_path,t.transcriptPath].filter(c=>c!==void 0);return r.length?r.every(c=>c===r[0])?r[0]:void 0:a==="cli"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)?Ec.join(yt(),"session-state",n,"events.jsonl"):void 0}function ci(t,n){return t.agentId!==void 0&&t.agentId!==null?nn(t.agentId)===n&&n!==void 0:n===void 0&&ce(t.data)?.parentToolCallId==null}function Qs(t,n,a){let r=it(t.model);if(r)return{name:r,source:"hook.model"};try{return Ac(t,n,a)}catch{return}}function Ac(t,n,a){let r=ni(t),c=["tool_use_id","toolUseId","tool_call_id","toolCallId"],h=xt(t,c),o=r==="SessionStart"&&t.source==="startup";if(!o&&!kc.has(r)||!o&&!h&&c.some(N=>t[N]!==void 0))return;let f=_t(t),d=Tc(t);if(!o&&!h&&(!f||d===void 0))return;let m=xt(t,["session_id","sessionId"]),v=xt(t,Xs),_=xt(t,Js),x=Ks(t,a);if(!m||x===void 0||Xs.some(N=>t[N]!==void 0)&&!v||Js.some(N=>t[N]!==void 0)&&!_||!v&&["agent_name","agentName","agent_type","agentType"].some(N=>t[N]!==void 0))return;let b=zs(wc(t,m,n)),E=b?.first,A=ce(E?.data),C=He(E?.timestamp);if(!b||E?.type!=="session.start"||A?.sessionId!==m||C===void 0||C>x||b.rows.some(N=>N.type==="session.start"&&ce(N.data)?.sessionId!==m))return;if(o){if(v||!b.complete||t.timestamp===void 0)return;let N=it(A.selectedModel),T=C;for(let l of b.rows){if(l.type!=="session.model_change"||!ci(l,void 0))continue;let j=He(l.timestamp);if(j===void 0)return;if(j>x||j<T)continue;let X=it(ce(l.data)?.newModel);if(j===T&&X!==N)return;N=X,T=j}return N?{name:N,source:"transcript.session.selected"}:void 0}if(!h)return Oc(f,d,b.rows,v,_,C,x);let L=[];for(let N of b.rows){let T=ce(N.data),l=He(N.timestamp);if(!T||l===void 0||l>x||l<C||!ci(N,v)||_!==void 0&&T.turnId!==_)continue;let j=!1;if(N.type==="assistant.message"?j=Array.isArray(T.toolRequests)&&T.toolRequests.some(ie=>ce(ie)?.toolCallId===h):(N.type==="tool.execution_start"||N.type==="tool.execution_complete")&&(j=T.toolCallId===h),!j)continue;let X=it(T.model);L.push(X?{name:X,source:`transcript.${N.type}`}:void 0)}return Ys(L)}function Tc(t){let n=ii(t);if(typeof n!="string")return n;if(n.trim()==="")return{};try{return JSON.parse(n)}catch{return n}}function Oc(t,n,a,r,c,h,o){let f=tt(n),d=new Set,m;for(let _ of a){let x=ce(_.data),b=He(_.timestamp);if(!(!x||b===void 0||b>o||b<h)){if(_.type==="tool.execution_complete"&&typeof x.toolCallId=="string")d.add(x.toolCallId);else if(_.type==="user.message"||_.type==="abort"||_.type==="session.model_change")m&&(m.open=!1);else if(_.type==="assistant.turn_end")m&&ci(_,r)&&(m.open=!1);else if(_.type==="assistant.message"&&ci(_,r)){if(c!==void 0&&x.turnId!==c)continue;let E=it(x.model),A=E?{name:E,source:"transcript.assistant.message.unique_call"}:void 0;m={open:!0,calls:new Map};for(let C of Array.isArray(x.toolRequests)?x.toolRequests:[]){let L=ce(C);!L||L.name!==t||typeof L.toolCallId!="string"||tt(L.arguments)!==f||m.calls.set(L.toolCallId,A)}}}}if(!m?.open)return;let v=[...m.calls].filter(([_])=>!d.has(_));return v.length===1?v[0][1]:void 0}var li;function Cc(){if(li===void 0)try{li=sn.userInfo().username}catch{li=process.env.USER??process.env.LOGNAME??(typeof process.getuid=="function"?String(process.getuid()):"unknown")}return li}var ea=ui,Ic=new Set(["","unknown","undefined","null","n/a","none"]);function ge(t){let n=typeof t=="string"?t.trim():void 0;return n&&!Ic.has(n.toLowerCase())?n:void 0}var Rc=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Nc(t){let n=ge(t);return n&&Rc.test(n)?n:void 0}function Lc(t){let n=t?ge(t.copilot_version)??ge(t.copilotVersion)??ge(t.cli_version)??ge(t.cliVersion)??ge(t.version):void 0;return n||(rn===void 0&&(rn=Mc()),rn??void 0)}var rn;function Mc(){let t=ge(process.env.COPILOT_CLI_BINARY_VERSION)??ge(process.env.COPILOT_CLI_VERSION);if(t)return t;let n=ge(process.env.COPILOT_CLI_RESOLVED_DIST_DIR);if(n){let a=Nc(Zs.basename(n));if(a)return a;let r=Dc(n);if(r)return r}return null}function Dc(t){try{let n=Pc.readFileSync(Zs.join(t,"package.json"),"utf8");return ge(JSON.parse(n).version)}catch{return}}var Vc=new Set(["copilot.hook","copilot.tool_name","copilot.toolName","copilot.tool_use_id","copilot.toolUseId","copilot.session_id","copilot.sessionId","copilot.transcript_path","copilot.transcriptPath","copilot.cwd","copilot.permission_mode","copilot.surface","copilot.agent_id","copilot.agent_type","copilot.agent_name","copilot.agent_display_name","copilot.stop_reason","copilot.notification_type"]),Uc=new Set(["copilot.tool_input","copilot.toolInput","copilot.toolArgs","copilot.tool_response","copilot.tool_result","copilot.toolResult"]),Bc={skipRedactKeys:Vc,bashContextKeys:Uc,outputForKey:(t,n)=>{if(t==="copilot.tool_response")return n;if(t==="copilot.tool_result"||t==="copilot.toolResult")return tn({[t.slice(8)]:n})}},Fc=new Set(["hook_event_name","hookEventName","hookName"]);function jc(t,n,a){let r=Object.fromEntries(Object.entries(t).filter(([c])=>!Fc.has(c)));return $s(r,Qs(t,n,a)),[{key:"ingest.type",value:{stringValue:"copilot"}},{key:"copilot.hook",value:{stringValue:vt(t)??"unknown"}},{key:"copilot.surface",value:{stringValue:n}},...(0,We.attrsFromRecord)(r,"copilot",Bc)]}function qc(t){let n=Lc(t);return[{key:"service.name",value:{stringValue:"copilot"}},...n?[{key:"service.version",value:{stringValue:n}}]:[],{key:"telemetry.sdk.name",value:{stringValue:"pinta-copilot"}},{key:"telemetry.sdk.language",value:{stringValue:"nodejs"}},{key:"telemetry.sdk.version",value:{stringValue:ea}},{key:"process.pid",value:{intValue:process.pid}},{key:"process.owner",value:{stringValue:Cc()}},{key:"host.name",value:{stringValue:sn.hostname()}},{key:"host.arch",value:{stringValue:sn.arch()}}]}function ta(t){let n=t.now??Date.now();return(0,We.buildPayload)({traceId:t.traceId,spanName:`copilot.${(0,We.snakeCase)(vt(t.event)??"unknown")}`,attributes:[...jc(t.event,t.surface,n),...t.callId?[{key:"pinta.call_id",value:{stringValue:t.callId}}]:[]],resource:qc(t.event),scope:{name:"pinta-copilot",version:ea},now:n})}var ia=Ue(Le());function Gc(){return Number(process.env.PINTA_GUARD_TIMEOUT_MS)||100}var Hc=`pinta-copilot/${ui}`;function na(t,n){return(0,ia.evaluateGuard)(t,n,{timeoutMs:Gc(),token:process.env.PINTA_RELAY_TOKEN??"",disabled:process.env.PINTA_GUARD_DISABLED==="1",userAgent:Hc})}function Wc(t,n,a,r){try{if(Rs(a)||n!=="PreToolUse"&&!Ls(n))return null;let c=new oi(t),h=_t(a),o=ii(a);return n==="PreToolUse"?c.open(r,h,o):c.close(r,h,o)}catch{return null}}async function $c(){let t=[];for await(let n of process.stdin)t.push(n);return Buffer.concat(t).toString("utf-8")}async function sa(){try{let t=Os(),n=Ps(),a=await $c(),r=JSON.parse(a),c=ni(r),h=Is(r),o=new si(t),f=c==="UserPromptSubmit"?o.newTrace(h):o.currentTrace(h),d=Wc(t,c,r,h),m=ta({event:r,traceId:f,surface:n,callId:d}),v=_t(r),_=null;if(Ns(c)&&!Ms(v)&&(_=await na(m,process.env.PINTA_GUARD_ENDPOINT)),_?.decision==="DENY"){let b=Ds(c,_,n,r);b&&process.stdout.write(b+`
|
|
62
|
+
`);return}new be.DiskRetryQueue(n.pluginData,"pinta-copilot").enqueue(t)}var Bs=Ue(Le()),si=class extends Bs.DiskSessionTraceManager{constructor(n){super(n.tracePath)}};import Hs from"crypto";import ai from"fs";import Fs from"path";var mc=64,js=200,gc=6*60*60*1e3;function qs(t,n){return Hs.createHash("sha256").update(`${t??""}\0${tt(n)}`).digest("hex").slice(0,32)}function tt(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(tt).join(",")}]`:`{${Object.entries(t).sort(([a],[r])=>a<r?-1:a>r?1:0).map(([a,r])=>`${JSON.stringify(a)}:${tt(r)}`).join(",")}}`}var oi=class{filePath;constructor(n){this.filePath=Fs.join(n.pluginData,"calls.json")}open(n,a,r){let c=Hs.randomBytes(8).toString("hex"),h=n||"default",o=this.read(),f=Date.now(),d=Gs(o[h]??[],f);return d.push({k:qs(a,r),id:c,t:f}),o[h]=d.slice(-mc),this.write(o),c}close(n,a,r){let c=n||"default",h=this.read(),o=Gs(h[c]??[],Date.now()),f=qs(a,r),d=yc(o,f);if(d===-1)return o.length!==(h[c]??[]).length&&(h[c]=o,this.write(h)),null;let[m]=o.splice(d,1);return h[c]=o,this.write(h),m.id}read(){try{let n=JSON.parse(ai.readFileSync(this.filePath,"utf-8"));if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{}return{}}write(n){try{ai.mkdirSync(Fs.dirname(this.filePath),{recursive:!0});let a=Object.entries(n).filter(([,c])=>c.length>0),r=a.length>js?a.slice(-js):a;vc(this.filePath,JSON.stringify(Object.fromEntries(r)))}catch{}}};function Gs(t,n){return t.filter(a=>n-a.t<gc)}function yc(t,n){for(let a=t.length-1;a>=0;a-=1)if(t[a].k===n)return a;return-1}function vc(t,n){let a=`${t}.${process.pid}.tmp`;ai.writeFileSync(a,n),ai.renameSync(a,t)}import Pc from"fs";import sn from"os";import Zs from"path";var ui="0.12.1";var We=Ue(Le());import Ec from"node:path";import Se from"node:fs";import Ws from"node:path";var _c=new Set(["","unknown","undefined","null","n/a","none","auto","default"]),xc=256*1024,bc=1024*1024,Sc=4096;function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}function it(t){let n=ce(t),a=n?"id"in n?n.id:n.name:t;if(typeof a!="string")return;let r=a.trim();if(!(r.startsWith("{")||r.startsWith("[")))return r.length<=512&&!/[\u0000-\u001f\u007f]/.test(r)&&!_c.has(r.toLowerCase())?r:void 0}function $s(t,n){delete t.model,n&&(t.model=n.name,!(n.source==="hook.model"&&t.model_source!==void 0)&&(t.model_source!==void 0&&(t.model_original_source=t.model_source),t.model_source=n.source))}function nn(t){return typeof t=="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}$/.test(t)?t:void 0}function xt(t,n){let a=n.filter(r=>t[r]!==void 0).map(r=>nn(t[r]));return a.length>0&&a[0]!==void 0&&a.every(r=>r===a[0])?a[0]:void 0}function He(t){let n=typeof t=="number"?t:typeof t=="string"&&/^\d{4}-\d{2}-\d{2}T/.test(t)?Date.parse(t):NaN;return Number.isFinite(n)&&n>=0?n:void 0}function Ks(t,n){let a=t.timestamp===void 0?He(n):He(t.timestamp);return a!==void 0&&a<=n?a:void 0}function zs(t){if(typeof t!="string"||t.length>4096||/[\u0000-\u001f]/.test(t)||!Ws.isAbsolute(t)||Ws.extname(t)!==".jsonl")return;let n;try{n=Se.openSync(t,Se.constants.O_RDONLY|Se.constants.O_NONBLOCK|(Se.constants.O_NOFOLLOW??0));let a=Se.fstatSync(n);if(!a.isFile()||!Number.isSafeInteger(a.size)||a.size<=0)return;let r=Buffer.alloc(Math.min(a.size,xc));if(Se.readSync(n,r,0,r.length,0)!==r.length)return;let c=r.indexOf(10),h;if(c>=0)try{h=ce(JSON.parse(r.toString("utf8",0,c)))}catch{}let o=Math.max(0,a.size-bc),f=a.size<=r.length?r:Buffer.alloc(a.size-o);if(f!==r&&Se.readSync(n,f,0,f.length,o)!==f.length)return;let d=Se.fstatSync(n);if(d.size<a.size||d.size===a.size&&d.mtimeMs!==a.mtimeMs)return;let m=o>0?f.indexOf(10)+1:0,v=f.lastIndexOf(10);if(o>0&&m===0||v<m)return;let _=[],x=0;for(;v>m&&x<Sc;){let b=f.lastIndexOf(10,v-1),E=Math.max(m,b+1),A=f.toString("utf8",E,v).trim();if(A){let C=ce(JSON.parse(A));C&&_.push(C)}v=E-1,x++}return _.reverse(),{first:h,rows:_,complete:o===0&&v<0&&f[f.length-1]===10}}catch{return}finally{if(n!==void 0)try{Se.closeSync(n)}catch{}}}function Ys(t){let n=t[0];return n&&t.every(a=>a?.name===n.name)?n:void 0}var kc=new Set(["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest"]),Xs=["agent_id","agentId"],Js=["turn_id","turnId"];function wc(t,n,a){let r=[t.transcript_path,t.transcriptPath].filter(c=>c!==void 0);return r.length?r.every(c=>c===r[0])?r[0]:void 0:a==="cli"&&/^[A-Za-z0-9_-]{1,128}$/.test(n)?Ec.join(yt(),"session-state",n,"events.jsonl"):void 0}function ci(t,n){return t.agentId!==void 0&&t.agentId!==null?nn(t.agentId)===n&&n!==void 0:n===void 0&&ce(t.data)?.parentToolCallId==null}function Qs(t,n,a){let r=it(t.model);if(r)return{name:r,source:"hook.model"};try{return Ac(t,n,a)}catch{return}}function Ac(t,n,a){let r=ni(t),c=["tool_use_id","toolUseId","tool_call_id","toolCallId"],h=xt(t,c),o=r==="SessionStart"&&t.source==="startup";if(!o&&!kc.has(r)||!o&&!h&&c.some(N=>t[N]!==void 0))return;let f=_t(t),d=Tc(t);if(!o&&!h&&(!f||d===void 0))return;let m=xt(t,["session_id","sessionId"]),v=xt(t,Xs),_=xt(t,Js),x=Ks(t,a);if(!m||x===void 0||Xs.some(N=>t[N]!==void 0)&&!v||Js.some(N=>t[N]!==void 0)&&!_||!v&&["agent_name","agentName","agent_type","agentType"].some(N=>t[N]!==void 0))return;let b=zs(wc(t,m,n)),E=b?.first,A=ce(E?.data),C=He(E?.timestamp);if(!b||E?.type!=="session.start"||A?.sessionId!==m||C===void 0||C>x||b.rows.some(N=>N.type==="session.start"&&ce(N.data)?.sessionId!==m))return;if(o){if(v||!b.complete||t.timestamp===void 0)return;let N=it(A.selectedModel),T=C;for(let l of b.rows){if(l.type!=="session.model_change"||!ci(l,void 0))continue;let j=He(l.timestamp);if(j===void 0)return;if(j>x||j<T)continue;let X=it(ce(l.data)?.newModel);if(j===T&&X!==N)return;N=X,T=j}return N?{name:N,source:"transcript.session.selected"}:void 0}if(!h)return Oc(f,d,b.rows,v,_,C,x);let L=[];for(let N of b.rows){let T=ce(N.data),l=He(N.timestamp);if(!T||l===void 0||l>x||l<C||!ci(N,v)||_!==void 0&&T.turnId!==_)continue;let j=!1;if(N.type==="assistant.message"?j=Array.isArray(T.toolRequests)&&T.toolRequests.some(ie=>ce(ie)?.toolCallId===h):(N.type==="tool.execution_start"||N.type==="tool.execution_complete")&&(j=T.toolCallId===h),!j)continue;let X=it(T.model);L.push(X?{name:X,source:`transcript.${N.type}`}:void 0)}return Ys(L)}function Tc(t){let n=ii(t);if(typeof n!="string")return n;if(n.trim()==="")return{};try{return JSON.parse(n)}catch{return n}}function Oc(t,n,a,r,c,h,o){let f=tt(n),d=new Set,m;for(let _ of a){let x=ce(_.data),b=He(_.timestamp);if(!(!x||b===void 0||b>o||b<h)){if(_.type==="tool.execution_complete"&&typeof x.toolCallId=="string")d.add(x.toolCallId);else if(_.type==="user.message"||_.type==="abort"||_.type==="session.model_change")m&&(m.open=!1);else if(_.type==="assistant.turn_end")m&&ci(_,r)&&(m.open=!1);else if(_.type==="assistant.message"&&ci(_,r)){if(c!==void 0&&x.turnId!==c)continue;let E=it(x.model),A=E?{name:E,source:"transcript.assistant.message.unique_call"}:void 0;m={open:!0,calls:new Map};for(let C of Array.isArray(x.toolRequests)?x.toolRequests:[]){let L=ce(C);!L||L.name!==t||typeof L.toolCallId!="string"||tt(L.arguments)!==f||m.calls.set(L.toolCallId,A)}}}}if(!m?.open)return;let v=[...m.calls].filter(([_])=>!d.has(_));return v.length===1?v[0][1]:void 0}var li;function Cc(){if(li===void 0)try{li=sn.userInfo().username}catch{li=process.env.USER??process.env.LOGNAME??(typeof process.getuid=="function"?String(process.getuid()):"unknown")}return li}var ea=ui,Ic=new Set(["","unknown","undefined","null","n/a","none"]);function ge(t){let n=typeof t=="string"?t.trim():void 0;return n&&!Ic.has(n.toLowerCase())?n:void 0}var Rc=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Nc(t){let n=ge(t);return n&&Rc.test(n)?n:void 0}function Lc(t){let n=t?ge(t.copilot_version)??ge(t.copilotVersion)??ge(t.cli_version)??ge(t.cliVersion)??ge(t.version):void 0;return n||(rn===void 0&&(rn=Mc()),rn??void 0)}var rn;function Mc(){let t=ge(process.env.COPILOT_CLI_BINARY_VERSION)??ge(process.env.COPILOT_CLI_VERSION);if(t)return t;let n=ge(process.env.COPILOT_CLI_RESOLVED_DIST_DIR);if(n){let a=Nc(Zs.basename(n));if(a)return a;let r=Dc(n);if(r)return r}return null}function Dc(t){try{let n=Pc.readFileSync(Zs.join(t,"package.json"),"utf8");return ge(JSON.parse(n).version)}catch{return}}var Vc=new Set(["copilot.hook","copilot.tool_name","copilot.toolName","copilot.tool_use_id","copilot.toolUseId","copilot.session_id","copilot.sessionId","copilot.transcript_path","copilot.transcriptPath","copilot.cwd","copilot.permission_mode","copilot.surface","copilot.agent_id","copilot.agent_type","copilot.agent_name","copilot.agent_display_name","copilot.stop_reason","copilot.notification_type"]),Uc=new Set(["copilot.tool_input","copilot.toolInput","copilot.toolArgs","copilot.tool_response","copilot.tool_result","copilot.toolResult"]),Bc={skipRedactKeys:Vc,bashContextKeys:Uc,outputForKey:(t,n)=>{if(t==="copilot.tool_response")return n;if(t==="copilot.tool_result"||t==="copilot.toolResult")return tn({[t.slice(8)]:n})}},Fc=new Set(["hook_event_name","hookEventName","hookName"]);function jc(t,n,a){let r=Object.fromEntries(Object.entries(t).filter(([c])=>!Fc.has(c)));return $s(r,Qs(t,n,a)),[{key:"ingest.type",value:{stringValue:"copilot"}},{key:"copilot.hook",value:{stringValue:vt(t)??"unknown"}},{key:"copilot.surface",value:{stringValue:n}},...(0,We.attrsFromRecord)(r,"copilot",Bc)]}function qc(t){let n=Lc(t);return[{key:"service.name",value:{stringValue:"copilot"}},...n?[{key:"service.version",value:{stringValue:n}}]:[],{key:"telemetry.sdk.name",value:{stringValue:"pinta-copilot"}},{key:"telemetry.sdk.language",value:{stringValue:"nodejs"}},{key:"telemetry.sdk.version",value:{stringValue:ea}},{key:"process.pid",value:{intValue:process.pid}},{key:"process.owner",value:{stringValue:Cc()}},{key:"host.name",value:{stringValue:sn.hostname()}},{key:"host.arch",value:{stringValue:sn.arch()}}]}function ta(t){let n=t.now??Date.now();return(0,We.buildPayload)({traceId:t.traceId,spanName:`copilot.${(0,We.snakeCase)(vt(t.event)??"unknown")}`,attributes:[...jc(t.event,t.surface,n),...t.callId?[{key:"pinta.call_id",value:{stringValue:t.callId}}]:[]],resource:qc(t.event),scope:{name:"pinta-copilot",version:ea},now:n})}var ia=Ue(Le());function Gc(){return Number(process.env.PINTA_GUARD_TIMEOUT_MS)||100}var Hc=`pinta-copilot/${ui}`;function na(t,n){return(0,ia.evaluateGuard)(t,n,{timeoutMs:Gc(),token:process.env.PINTA_RELAY_TOKEN??"",disabled:process.env.PINTA_GUARD_DISABLED==="1",userAgent:Hc})}function Wc(t,n,a,r){try{if(Rs(a)||n!=="PreToolUse"&&!Ls(n))return null;let c=new oi(t),h=_t(a),o=ii(a);return n==="PreToolUse"?c.open(r,h,o):c.close(r,h,o)}catch{return null}}async function $c(){let t=[];for await(let n of process.stdin)t.push(n);return Buffer.concat(t).toString("utf-8")}async function sa(){try{let t=Os(),n=Ps(),a=await $c(),r=JSON.parse(a),c=ni(r),h=Is(r),o=new si(t),f=c==="UserPromptSubmit"?o.newTrace(h):o.currentTrace(h),d=Wc(t,c,r,h),m=ta({event:r,traceId:f,surface:n,callId:d}),v=_t(r),_=null;if(Ns(c)&&!Ms(v)&&(_=await na(m,process.env.PINTA_GUARD_ENDPOINT)),_?.decision==="DENY"){let b=Ds(c,_,n,r);b&&process.stdout.write(b+`
|
|
63
63
|
`)}if((0,ra.attachGuard)(m,_),_&&c==="PostToolUse")for(let b of m.resourceSpans)for(let E of b.scopeSpans)for(let A of E.spans)A.attributes.push({key:"pinta.guard.target",value:{stringValue:"tool_output"}});if(_?.decision==="DENY")return Us(m,t),0;let x=new ri(t);await x.flush(),await x.send(m)}catch(t){process.stderr.write(`[pinta-copilot] error: ${t}
|
|
64
64
|
`)}return 0}import{opendir as al,stat as ol}from"node:fs/promises";import fi from"node:path";import{spawn as ua}from"node:child_process";import{copyFile as an,mkdtemp as Kc,rm as zc,stat as Yc}from"node:fs/promises";import Xc from"node:os";import on from"node:path";var Jc=2e3,Qc=250,aa=3,oa=3e4,Zc=3e4,un;function el(){return un||(un=new Promise(t=>{let n=ua("sqlite3",["-version"],{stdio:"ignore"});n.once("error",()=>t(!1)),n.once("exit",a=>t(a===0))})),un}function tl(t){return`'${t.replace(/'/g,"''")}'`}async function il(t,n){let a=`.backup ${tl(n)}`;await new Promise((r,c)=>{let h=ua("sqlite3",[t,a],{stdio:["ignore","ignore","pipe"],timeout:Zc,killSignal:"SIGKILL"}),o="";h.stderr?.on("data",f=>{o+=f.toString()}),h.once("error",c),h.once("exit",f=>{f===0?r():c(new Error(`sqlite3 .backup exited ${f}: ${o.trim()}`))})})}async function cn(t){try{return await Yc(t)}catch{return}}function ca(t,n){return t===void 0||n===void 0?t===void 0&&n===void 0:t.size===n.size&&t.mtimeMs===n.mtimeMs}function la(t){return{wal:`${t}-wal`,shm:`${t}-shm`}}async function nl(t){let{wal:n,shm:a}=la(t),r=[t,n,a],c=Date.now(),h=c,o=await Promise.all(r.map(async f=>({path:f,st:await cn(f)})));for(;;){if(Date.now()-h>=Jc)return o;if(Date.now()-c>=oa)throw new Error(`snapshot: ${t} never quiesced within ${oa}ms (actively written?)`);await new Promise(m=>setTimeout(m,Qc));let f=await Promise.all(r.map(async m=>({path:m,st:await cn(m)})));f.every((m,v)=>ca(m.st,o[v].st))||(h=Date.now()),o=f}}async function rl(t,n){let{wal:a,shm:r}=la(t),c=await nl(t);if(await an(t,n),c.find(f=>f.path===a)?.st!==void 0&&await an(a,`${n}-wal`),c.find(f=>f.path===r)?.st!==void 0&&await an(r,`${n}-shm`),!(await Promise.all([t,a,r].map(async f=>({path:f,st:await cn(f)})))).every((f,d)=>ca(f.st,c[d].st)))throw new Error(`snapshot: ${t} changed during quiesce-copy (torn-read guard)`)}async function sl(t,n){let a;for(let r=1;r<=aa;r++)try{await rl(t,n);return}catch(c){a=c}throw new Error(`snapshot: quiesce-copy of ${t} failed after ${aa} attempts: ${String(a)}`)}async function fa(t,n={}){let a=n.tmpDirBase??Xc.tmpdir(),r=await Kc(on.join(a,"pinta-copilot-snapshot-")),c=on.join(r,on.basename(t.absPath));try{if(await el())try{return await il(t.absPath,c),c}catch{}return await sl(t.absPath,c),c}catch(h){throw await zc(r,{recursive:!0,force:!0}).catch(()=>{}),h}}var ul="pinta-copilot",ha="events.jsonl",pa="session.db",cl="rewind-snapshots/backups/";function ll(){return fi.join(yt(),"session-state")}function fl(t,n){return fi.relative(t,n).split(fi.sep).join("/")}function hl(t){return t.endsWith(".db-wal")||t.endsWith(".db-shm")}function pl(t){let[n]=t.split("/");return!n||n===t?{}:{sessionId:n}}function dl(t,n){let a=t.split("/").length===2;return a&&n===ha?"append-log":a&&n===pa?"database":"rewritten-doc"}function ml(t){let n=t.split("/"),a=n[n.length-1]??"";return n.length===2&&(a===ha||a===pa)?"session-log":t.includes(cl)?"other":"meta"}async function da(){return[ll()]}async function*ma(t,n){let a;try{a=await al(n)}catch{return}try{for await(let r of a){let c=fi.join(n,r.name);r.isDirectory()?yield*ma(t,c):r.isFile()&&(yield{absPath:c,relPath:fl(t,c)})}}catch{return}}async function*gl(t){let[n]=await da(),a=t.since?.getTime();for await(let{absPath:r,relPath:c}of ma(n,n)){let h=c.split("/"),o=h[h.length-1]??"";if(hl(o))continue;let f;try{f=await ol(r)}catch{continue}a!==void 0&&f.mtime.getTime()<=a||(yield{relPath:c,absPath:r,size:f.size,mtime:f.mtime,...pl(c),semantics:dl(c,o)})}}async function yl(t){return fa(t)}var vl={id:ul,roots:da,scan:gl,classify:ml,snapshot:yl};Ts();function bl(){let t=process.argv[1];if(!t)return!1;try{return import.meta.url===xl(_l(t)).href}catch{return!1}}async function Sl(){let t=await sa();process.exit(t)}bl()&&Sl();export{vl as lifecycle};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pinta-ai/pinta-copilot",
|
|
3
|
-
"version": "0.12.1
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"description": "Generic OTLP forwarder + guard for GitHub Copilot hook events (CLI + VS Code extension)",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"exports": {
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"prepublishOnly": "npm run build"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@pinta-ai/core": "0.11.1
|
|
45
|
+
"@pinta-ai/core": "0.11.1",
|
|
46
46
|
"@types/node": "^22.0.0",
|
|
47
47
|
"esbuild": "^0.24.0",
|
|
48
48
|
"tsx": "^4.0.0",
|