@tocca-systems/twp-cli 0.21.0 → 0.23.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.
Files changed (47) hide show
  1. package/CHANGELOG.public.md +10 -0
  2. package/README.md +30 -5
  3. package/command-model/user-management.json +1137 -2
  4. package/dist/{ai-dispatch-36HRDRLF.js → ai-dispatch-VSCKUY6J.js} +1 -1
  5. package/dist/{api-command-2OPQMSTE.js → api-command-CLARDKAL.js} +5 -17
  6. package/dist/{app-CPMS4ICA.js → app-X3IKIAKB.js} +27 -26
  7. package/dist/{auto-update-CV2MM32C.js → auto-update-FBZGOQFI.js} +1 -1
  8. package/dist/{auto-update-worker-ML7EBNQW.js → auto-update-worker-SI7TVSCN.js} +2 -2
  9. package/dist/{backlog-NV7Z76R3.js → backlog-X2MQTA6F.js} +2 -2
  10. package/dist/chunk-7LTTKKQA.js +56 -0
  11. package/dist/{chunk-YV2TFD7D.js → chunk-7PRQ7JW2.js} +55 -27
  12. package/dist/chunk-APYYF7H6.js +3 -0
  13. package/dist/{chunk-ILKQDXI5.js → chunk-DSDVIU6A.js} +1 -1
  14. package/dist/chunk-E4H22AO5.js +3 -0
  15. package/dist/chunk-EQWW2F5V.js +12 -0
  16. package/dist/chunk-JB27KNCX.js +52 -0
  17. package/dist/chunk-K2ONOH3L.js +9 -0
  18. package/dist/{chunk-WH65FZJV.js → chunk-LD3AKGH6.js} +8 -8
  19. package/dist/chunk-NAUH75MM.js +10 -0
  20. package/dist/chunk-NZ7WI4RZ.js +18 -0
  21. package/dist/chunk-PEGUHUTD.js +3 -0
  22. package/dist/{chunk-GTABFTZP.js → chunk-SJRK4AVE.js} +1 -1
  23. package/dist/{chunk-FOFV2MNL.js → chunk-WOUKWOAR.js} +2 -2
  24. package/dist/{chunk-5QCAIKFE.js → chunk-X4RS5VBH.js} +1 -1
  25. package/dist/{chunk-G2QYUQJE.js → chunk-XLE4HW6B.js} +1 -1
  26. package/dist/{chunk-RCDOQ6TT.js → chunk-Y2QAP6SU.js} +1 -1
  27. package/dist/cli.js +18 -13
  28. package/dist/{commands-R4KQCXXA.js → commands-BE67IDNQ.js} +12 -7
  29. package/dist/{commands-XF5G3GIE.js → commands-JNG5TZ77.js} +16 -16
  30. package/dist/format-NMW6Y2E5.js +3 -0
  31. package/dist/{logout-guard-JMGI6NPB.js → logout-guard-CMZZBRUL.js} +1 -1
  32. package/dist/{oneshot-QLIXOLN2.js → oneshot-NA756EBO.js} +5 -5
  33. package/dist/{project-BATJQR3F.js → project-2LJZW747.js} +1 -1
  34. package/dist/query-NJMVSQR6.js +3 -0
  35. package/dist/render-ICZOK3HV.js +3 -0
  36. package/dist/run-XCAJDHFU.js +4 -0
  37. package/dist/{server-settings-ROZUOMC2.js → server-settings-CG3EM7R7.js} +1 -1
  38. package/dist/{setup-3UEZTO4T.js → setup-UI6V2Q3V.js} +1 -1
  39. package/dist/{task-6QUH5OXF.js → task-GKNM3G4K.js} +2 -2
  40. package/dist/{update-EXFIHTMW.js → update-TVVBJNN7.js} +1 -1
  41. package/dist/user-EU7Z3DAO.js +24 -0
  42. package/package.json +1 -1
  43. package/dist/chunk-BOBSH3QN.js +0 -9
  44. package/dist/chunk-MIMDLO52.js +0 -43
  45. package/dist/chunk-SPZO6C5N.js +0 -69
  46. package/dist/chunk-ZGG7TRAM.js +0 -3
  47. package/dist/run-2OQQAOHL.js +0 -4
@@ -1,6 +1,7 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-BOBSH3QN.js";import{DEFAULT_MAX_TOKENS,emptyUsage}from"./chunk-FOFV2MNL.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{configReadDirs,ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs2 from"fs";import path3 from"path";import os2 from"os";import{realpathSync}from"fs";import{homedir}from"os";import{dirname,isAbsolute,relative,resolve,sep}from"path";var PathDeniedError=class extends Error{constructor(message){super(message);this.name="PathDeniedError"}};function resolveToolPath(input,cwd,home=homedir()){if(typeof input!=="string"||input.trim()===""){throw new PathDeniedError("path must be a non-empty string")}const expanded=expandHome(input,home);const abs=isAbsolute(expanded)?resolve(expanded):resolve(cwd,expanded);const root=realOrSelf(resolve(cwd));assertInside(abs,resolve(cwd),abs);assertNotSecret(abs,home);const real=realOrSelf(abs);if(real!==
3
+ import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelIndex,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{redactSecretValues,redactSecrets}from"./chunk-EQWW2F5V.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-JKSXUBND.js";import{isSafePathSegment}from"./chunk-X4RS5VBH.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-NAUH75MM.js";
4
+ import{DEFAULT_MAX_TOKENS,emptyUsage}from"./chunk-WOUKWOAR.js";import{AuthSession}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{configReadDirs,ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import fs2 from"fs";import path3 from"path";import os2 from"os";import{realpathSync}from"fs";import{homedir}from"os";import{dirname,isAbsolute,relative,resolve,sep}from"path";var PathDeniedError=class extends Error{constructor(message){super(message);this.name="PathDeniedError"}};function resolveToolPath(input,cwd,home=homedir()){if(typeof input!=="string"||input.trim()===""){throw new PathDeniedError("path must be a non-empty string")}const expanded=expandHome(input,home);const abs=isAbsolute(expanded)?resolve(expanded):resolve(cwd,expanded);const root=realOrSelf(resolve(cwd));assertInside(abs,resolve(cwd),abs);assertNotSecret(abs,home);const real=realOrSelf(abs);if(real!==
4
5
  abs){assertInside(real,root,abs);assertNotSecret(real,home)}return abs}function realToolPath(input,cwd,home=homedir()){return realOrSelf(resolveToolPath(input,cwd,home))}function assertInside(target,root,reported){const rel=relative(root,target);const outside=rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel);if(outside){throw new PathDeniedError(`path escapes the working directory (${reported}). Only paths under ${root} can be accessed.`)}}function realOrSelf(target){let current=target;const rest=[];
5
6
  for(;;){try{const real=realpathSync(current);return rest.length===0?real:resolve(real,...rest.reverse())}catch{const parent=dirname(current);if(parent===current)return target;rest.push(current.slice(parent.length+1));current=parent}}}function assertNotSecret(absPath,home=homedir(),env=process.env){const reason=secretReason(absPath,home,env);if(reason!==null)throw new PathDeniedError(`refusing to access ${absPath}: ${reason}`)}function secretReason(absPath,_home=homedir(),env=process.env){const lower=absPath.
6
7
  toLowerCase();const segments=lower.split(sep);const base=segments[segments.length-1]??"";const parent=segments[segments.length-2]??"";if(base===".env"||base.startsWith(".env."))return".env files are denied (design \xA77)";if(segments.includes(".ssh"))return"SSH key material is denied (design \xA77)";if(parent===".git"&&base==="config"){return".git/config is denied (it can hold a GitHub token in the remote URL)"}if(base===".netrc"||base==="_netrc"||base===".npmrc")return"credential files are deni\
@@ -76,13 +77,13 @@ return third!==void 0&&SCRIPT_NAME.test(third)?`${pair} ${third}`:null}function
76
77
  for(const[key,sub]of Object.entries(props)){if(value[key]===void 0){if(sub.default!==void 0)value[key]=sub.default;continue}checkValue(`${key}`,sub,value[key],errors)}return{ok:errors.length===0,errors,value}}function checkValue(path8,schema,value,errors){switch(schema.type){case"string":if(typeof value!=="string")errors.push(`${path8} must be a string`);break;case"boolean":if(typeof value!=="boolean")errors.push(`${path8} must be a boolean`);break;case"integer":if(typeof value!=="number"||!Number.
77
78
  isInteger(value))errors.push(`${path8} must be an integer`);break;case"number":if(typeof value!=="number"||!Number.isFinite(value))errors.push(`${path8} must be a number`);break;case"array":if(!Array.isArray(value)){errors.push(`${path8} must be an array`);break}if(schema.items){value.forEach((item,i)=>checkValue(`${path8}[${i}]`,schema.items,item,errors))}break;case"object":if(typeof value!=="object"||value===null||Array.isArray(value)){errors.push(`${path8} must be an object`)}break;default:break}
78
79
  if(schema.enum&&!schema.enum.some(v=>v===value)){errors.push(`${path8} must be one of: ${schema.enum.join(", ")}`)}if(typeof value==="number"){if(schema.minimum!==void 0&&value<schema.minimum)errors.push(`${path8} must be >= ${schema.minimum}`);if(schema.maximum!==void 0&&value>schema.maximum)errors.push(`${path8} must be <= ${schema.maximum}`)}}async function executeTool(tool,rawInput,deps,callId){const validated=validateInput(tool.inputSchema,rawInput);if(!validated.ok){const content=`Invalid input for ${tool.name}:
79
- - ${validated.errors.join("\n- ")}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"error",bytes:Buffer.byteLength(content),mode:deps.mode.id,reasonCode:"invalid_input",callId});return{content,isError:true,summary:`${tool.name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}const input=validated.value;let judged={tool};const verdictTarget=()=>judged;const recordDecision=(decision,reasonCode,reason)=>{deps.audit.record({event:"decision",tool:verdictTarget().tool.name,risk:verdictTarget().
80
- tool.risk,decision,reasonCode,reason,mode:deps.mode.id,rawInput:input,callId})};const verdict=checkToolPermission({tool,input},{mode:deps.mode,cwd:deps.ctx.cwd,sessionAllow:deps.sessionAllow,...deps.sessionRules?{sessionRules:deps.sessionRules}:{},...deps.permissionLayers?{layers:deps.permissionLayers}:{},...deps.permissionMode!==void 0?{permissionMode:deps.permissionMode}:{},...deps.resolveTool?{resolveTool:deps.resolveTool}:{}});const policy=verdict.decision;judged=verdict.target;const target=verdict.
81
- target;if(policy==="deny"){recordDecision("deny",reasonCodeOf(verdict),verdict.reason);return{content:denyMessage(tool.name,verdict,deps),isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08${denySummary(verdict,deps)}\uFF09`}}const preview=safePreview(tool,input);const noAlwaysReason=neverAutoAllowReason(target.tool,target.input)??autoApproveExemptReason(target.tool,target.input,deps.ctx.cwd)??verdict.noAlwaysReason??null;const needsAsk=policy==="ask"||noAlwaysReason!==null;if(needsAsk){
82
- {if(!deps.askPermission){recordDecision("deny",noAlwaysReason===null?"non_interactive":"guard",noAlwaysReason??"\u975E\u5BFE\u8A71\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u627F\u8A8D\u304C\u5FC5\u8981\uFF08deny-and-continue\uFF09");return{content:`permission denied: ${tool.name} requires approval, and this session is non-interactive. `+(noAlwaysReason===null?"":`Reason: ${noAlwaysReason} `)+"Explain what you would run instead of running it.",isError:true,denied:true,summary:`${tool.name} \xB7 \u975E\u5BFE\u8A71\u306E\u305F\u3081\u62D2\u5426`}}
83
- let diff;try{diff=await tool.prepare?.(input,deps.ctx)??void 0}catch(err){diff=void 0;if(err instanceof PathDeniedError){recordDecision("deny","path_denied","\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF08paths.ts\uFF09");return{content:err.message,isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF09`}}}const persistOptions=deps.persistAllow?persistOptionsFor(target,noAlwaysReason,deps.ctx.cwd):[];const answer=await deps.askPermission({tool,
84
- input,preview,...diff?{diff}:{},noAlwaysReason,target,persistOptions});if(answer==="no"||typeof answer==="object"&&answer.kind==="instead"){const instead=typeof answer==="object"?answer.text.trim():"";recordDecision("deny","user_declined",instead===""?"\u5229\u7528\u8005\u304C\u62D2\u5426":"\u5229\u7528\u8005\u304C\u62D2\u5426\uFF08\u4EE3\u308F\u308A\u306E\u6307\u793A\u3042\u308A\uFF09");return{content:instead===""?`permission denied: the user declined to run ${tool.name}.`:`permission denied: t\
85
- he user declined to run ${tool.name} and asked you to do this instead:
80
+ - ${validated.errors.join("\n- ")}`;deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:"error",bytes:Buffer.byteLength(content),mode:deps.mode.id,reasonCode:"invalid_input",callId});return{content,isError:true,summary:`${tool.name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}const input=validated.value;if(tool.name===INDIRECT_TOOL&&deps.prepareIndirect){await deps.prepareIndirect(input).catch(()=>void 0)}let judged={tool};const verdictTarget=()=>judged;const recordDecision=(decision,reasonCode,reason)=>{
81
+ deps.audit.record({event:"decision",tool:verdictTarget().tool.name,risk:verdictTarget().tool.risk,decision,reasonCode,reason,mode:deps.mode.id,rawInput:input,callId})};const verdict=checkToolPermission({tool,input},{mode:deps.mode,cwd:deps.ctx.cwd,sessionAllow:deps.sessionAllow,...deps.sessionRules?{sessionRules:deps.sessionRules}:{},...deps.permissionLayers?{layers:deps.permissionLayers}:{},...deps.permissionMode!==void 0?{permissionMode:deps.permissionMode}:{},...deps.resolveTool?{resolveTool:deps.
82
+ resolveTool}:{}});const policy=verdict.decision;judged=verdict.target;const target=verdict.target;if(policy==="deny"){recordDecision("deny",reasonCodeOf(verdict),verdict.reason);return{content:denyMessage(tool.name,verdict,deps),isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08${denySummary(verdict,deps)}\uFF09`}}const preview=safePreview(tool,input);const noAlwaysReason=neverAutoAllowReason(target.tool,target.input)??autoApproveExemptReason(target.tool,target.input,deps.ctx.cwd)??verdict.
83
+ noAlwaysReason??null;const needsAsk=policy==="ask"||noAlwaysReason!==null;if(needsAsk){{if(!deps.askPermission){recordDecision("deny",noAlwaysReason===null?"non_interactive":"guard",noAlwaysReason??"\u975E\u5BFE\u8A71\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u627F\u8A8D\u304C\u5FC5\u8981\uFF08deny-and-continue\uFF09");return{content:`permission denied: ${tool.name} requires approval, and this session is non-interactive. `+(noAlwaysReason===null?"":`Reason: ${noAlwaysReason} `)+"Explain what you would\
84
+ run instead of running it.",isError:true,denied:true,summary:`${tool.name} \xB7 \u975E\u5BFE\u8A71\u306E\u305F\u3081\u62D2\u5426`}}let diff;try{diff=await tool.prepare?.(input,deps.ctx)??void 0}catch(err){diff=void 0;if(err instanceof PathDeniedError){recordDecision("deny","path_denied","\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF08paths.ts\uFF09");return{content:err.message,isError:true,denied:true,summary:`${tool.name} \xB7 deny\uFF08\u4FDD\u8B77\u3055\u308C\u305F\u30D1\u30B9\uFF09`}}}const persistOptions=deps.
85
+ persistAllow?persistOptionsFor(target,noAlwaysReason,deps.ctx.cwd):[];const answer=await deps.askPermission({tool,input,preview,...diff?{diff}:{},noAlwaysReason,target,persistOptions});if(answer==="no"||typeof answer==="object"&&answer.kind==="instead"){const instead=typeof answer==="object"?answer.text.trim():"";recordDecision("deny","user_declined",instead===""?"\u5229\u7528\u8005\u304C\u62D2\u5426":"\u5229\u7528\u8005\u304C\u62D2\u5426\uFF08\u4EE3\u308F\u308A\u306E\u6307\u793A\u3042\u308A\uFF09");
86
+ return{content:instead===""?`permission denied: the user declined to run ${tool.name}.`:`permission denied: the user declined to run ${tool.name} and asked you to do this instead:
86
87
  ${instead}`,isError:true,denied:true,summary:instead===""?`${tool.name} \xB7 \u5229\u7528\u8005\u304C\u62D2\u5426`:`${tool.name} \xB7 \u5229\u7528\u8005\u304C\u62D2\u5426\uFF08\u4EE3\u308F\u308A\u306E\u6307\u793A\u3042\u308A\uFF09`}}if(answer==="always"&&noAlwaysReason===null&&target.tool.name!==INDIRECT_TOOL){deps.sessionAllow.add(target.tool.name)}let persisted=false;if(typeof answer==="object"&&answer.kind==="persist"&&noAlwaysReason===null&&persistOptions.some(o=>o.rule===answer.rule)&&deps.
87
88
  persistAllow){persisted=await deps.persistAllow(answer.rule);if(persisted)deps.sessionRules?.push(answer.rule)}const how=answer==="always"?"\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u4ECA\u5F8C\u805E\u304B\u306A\u3044\uFF09":typeof answer==="object"&&answer.kind==="persist"?persisted?`\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u306F\u4ECA\u5F8C\u805E\u304B\u306A\u3044: ${answer.rule}\uFF09`:"\u5229\u7528\u8005\u304C\u627F\u8A8D\uFF08\u4ECA\u5F8C\u805E\u304B\u306A\u3044\u306E\u4FDD\u5B58\u306F\u884C\u308F\u306A\u304B\u3063\u305F\uFF09":
88
89
  "\u5229\u7528\u8005\u304C\u627F\u8A8D";recordDecision("allow","user_approved",`${how}\uFF08\u78BA\u8A8D\u306E\u7406\u7531: ${verdict.reason}\uFF09`)}}else{recordDecision("allow",reasonCodeOf(verdict),verdict.reason)}deps.onStart?.(tool,preview);try{const result=await tool.run(input,deps.ctx);deps.audit.record({event:"result",tool:tool.name,risk:tool.risk,outcome:result.isError===true?"error":"ok",bytes:Buffer.byteLength(result.content),mode:deps.mode.id,callId});return{summary:preview,...result}}catch(err){
@@ -141,13 +142,14 @@ while(offset<buf.length){const n=fs4.writeSync(handle,buf,offset,buf.length-offs
141
142
  `}if(Buffer.byteLength(line)>MAX_LINE_BYTES){line=`${JSON.stringify({ts:now(),v:1,session:sessionId,event:payload["event"],tool:clamp(String(payload["tool"]??""),40),_dropped:"line_too_long"})}
142
143
  `}if(written+Buffer.byteLength(line)>MAX_FILE_BYTES){stopped=true;writeAll(fd,`${JSON.stringify({ts:now(),v:1,session:sessionId,event:"truncated"})}
143
144
  `);return}writeAll(fd,line)}catch{stopped=true}};const common={v:1,session:sessionId,permission_mode:ctx.permissionMode??null};let wroteHeader=false;const header=()=>{if(wroteHeader)return;writeLine({ts:now(),...common,event:"session_start",mode:ctx.mode,model:ctx.model,cwd:ctx.cwd,cli_version:ctx.cliVersion,interactive:ctx.interactive,pid:process.pid});if(fd!==null&&!stopped)wroteHeader=true};const reportSaturation=()=>{if(!registry.saturated||reportedSaturation)return;reportedSaturation=true;writeLine(
144
- {ts:now(),...common,event:"registry_saturated"})};return{path:file,sessionId,get opened(){return everOpened},record(event){header();const safe=sanitizeEvent(event,registry);const tool=clamp(safe.tool,MAX_TOOL_NAME_BYTES);const callId=safe.callId===void 0?{}:{call_id:clamp(safe.callId,MAX_CALL_ID_BYTES)};if(safe.event==="decision"){writeLine({ts:now(),...common,event:"decision",tool,...callId,risk:safe.risk,decision:safe.decision,reason_code:safe.reasonCode,reason:safe.reason,mode:safe.mode,input:safe.
145
- input});reportSaturation();return}writeLine({ts:now(),...common,event:"result",tool,...callId,risk:safe.risk,outcome:safe.outcome,bytes:safe.bytes,mode:safe.mode,...safe.reasonCode!==void 0?{reason_code:safe.reasonCode}:{}})},close(){stopped=true;if(fd===null)return;try{fs4.closeSync(fd)}catch{}fd=null}}}function now(){return new Date().toISOString()}function lstatOrNull2(target){try{return fs4.lstatSync(target)}catch{return null}}function clamp(value,maxBytes){const total=Buffer.byteLength(value);
146
- if(total<=maxBytes)return value;let out=value;while(out.length>0&&Buffer.byteLength(out)>maxBytes)out=out.slice(0,-1);return`${out}\u2026(+${total-Buffer.byteLength(out)})`}function sanitizeInput(rawInput,registry){learnSecrets(rawInput,0,registry);return sanitizeObject(rawInput,0,registry)}function learnSecrets(value,depth,registry){if(depth>8||value===null||typeof value!=="object")return;if(Array.isArray(value)){for(const item of value)learnSecrets(item,depth+1,registry);return}for(const[key,child]of Object.
147
- entries(value)){if(REDACT_KEYS.has(key.toLowerCase()))registry.learn(child);else learnSecrets(child,depth+1,registry)}}function sanitizeObject(obj,depth,registry){const out={};let keys=0;for(const[key,value]of Object.entries(obj)){if(keys>=20){out["_twp_more_keys"]=true;break}keys++;if(REDACT_KEYS.has(key.toLowerCase())){out[key]=`<redacted ${byteLengthOf(value)} bytes>`;continue}out[key]=sanitizeValue(value,depth+1,registry)}return out}function sanitizeValue(value,depth,registry){if(value===null||
148
- typeof value==="number"||typeof value==="boolean")return value;if(typeof value==="string"){return clamp(registry.scrub(scrubSecrets(value)),MAX_STRING_BYTES)}if(depth>=3)return"<depth>";if(Array.isArray(value)){const head=value.slice(0,10).map(v=>sanitizeValue(v,depth+1,registry));return value.length>10?[...head,`\u2026(+${value.length-10})`]:head}if(typeof value==="object")return sanitizeObject(value,depth,registry);return`<${typeof value}>`}function byteLengthOf(value){if(typeof value==="strin\
149
- g")return Buffer.byteLength(value);try{return Buffer.byteLength(JSON.stringify(value)??"")}catch{return 0}}function prune(dir,nowMs=Date.now()){let entries;try{entries=fs4.readdirSync(dir).filter(n=>/^session-.*\.jsonl$/.test(n))}catch{return}const stats=[];for(const name of entries){try{stats.push({name,mtime:fs4.statSync(path5.join(dir,name)).mtimeMs})}catch{}}stats.sort((a,b)=>b.mtime-a.mtime);const cutoff=nowMs-MAX_AGE_DAYS*24*60*60*1e3;stats.forEach((entry,index)=>{const overCount=index>=MAX_FILES-
150
- 1;const tooOld=entry.mtime<cutoff;if(!tooOld&&!overCount)return;if(!tooOld&&nowMs-entry.mtime<PRUNE_GRACE_MS)return;try{fs4.unlinkSync(path5.join(dir,entry.name))}catch{}})}var CROCKFORD="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function newSessionId(nowMs=Date.now()){let time="";let remaining=nowMs;for(let i=0;i<10;i++){time=`${CROCKFORD[remaining%32]??"0"}${time}`;remaining=Math.floor(remaining/32)}const bytes=crypto.randomBytes(16);let rand="";for(const byte of bytes)rand+=CROCKFORD[byte%32]??"0";return`${time}${rand}`}import{readFileSync}from"fs";import{dirname as dirname2,join,resolve as resolve2,sep as sep3}from"path";function currentBranch(cwd=process.cwd()){let dir=cwd;for(;;){const gitPath=join(dir,".git");const head=readHead(gitPath);if(head!==null)return head;const parent=dirname2(dir);if(parent===dir)return null;dir=parent}}function readHead(gitPath){let headFile=join(gitPath,"HEAD");try{const stat2=readFileSync(gitPath,"utf8");const m=/^gitdir:\s*(.+)$/m.exec(stat2);if(m?.[1])headFile=join(resolve2(dirname2(
145
+ {ts:now(),...common,event:"registry_saturated"})};return{path:file,sessionId,get opened(){return everOpened},record(event){header();const safe2=sanitizeEvent(event,registry);const tool=clamp(safe2.tool,MAX_TOOL_NAME_BYTES);const callId=safe2.callId===void 0?{}:{call_id:clamp(safe2.callId,MAX_CALL_ID_BYTES)};if(safe2.event==="decision"){writeLine({ts:now(),...common,event:"decision",tool,...callId,risk:safe2.risk,decision:safe2.decision,reason_code:safe2.reasonCode,reason:safe2.reason,mode:safe2.
146
+ mode,input:safe2.input});reportSaturation();return}writeLine({ts:now(),...common,event:"result",tool,...callId,risk:safe2.risk,outcome:safe2.outcome,bytes:safe2.bytes,mode:safe2.mode,...safe2.reasonCode!==void 0?{reason_code:safe2.reasonCode}:{}})},close(){stopped=true;if(fd===null)return;try{fs4.closeSync(fd)}catch{}fd=null}}}function now(){return new Date().toISOString()}function lstatOrNull2(target){try{return fs4.lstatSync(target)}catch{return null}}function clamp(value,maxBytes){const total=Buffer.
147
+ byteLength(value);if(total<=maxBytes)return value;let out=value;while(out.length>0&&Buffer.byteLength(out)>maxBytes)out=out.slice(0,-1);return`${out}\u2026(+${total-Buffer.byteLength(out)})`}function sanitizeInput(rawInput,registry){learnSecrets(rawInput,0,registry);return sanitizeObject(rawInput,0,registry)}function learnSecrets(value,depth,registry){if(depth>8||value===null||typeof value!=="object")return;if(Array.isArray(value)){for(const item of value)learnSecrets(item,depth+1,registry);return}
148
+ for(const[key,child]of Object.entries(value)){if(REDACT_KEYS.has(key.toLowerCase()))registry.learn(child);else learnSecrets(child,depth+1,registry)}}function sanitizeObject(obj,depth,registry){const out={};let keys=0;for(const[key,value]of Object.entries(obj)){if(keys>=20){out["_twp_more_keys"]=true;break}keys++;if(REDACT_KEYS.has(key.toLowerCase())){out[key]=`<redacted ${byteLengthOf(value)} bytes>`;continue}out[key]=sanitizeValue(value,depth+1,registry)}return out}function sanitizeValue(value,depth,registry){
149
+ if(value===null||typeof value==="number"||typeof value==="boolean")return value;if(typeof value==="string"){return clamp(registry.scrub(scrubSecrets(value)),MAX_STRING_BYTES)}if(depth>=3)return"<depth>";if(Array.isArray(value)){const head=value.slice(0,10).map(v=>sanitizeValue(v,depth+1,registry));return value.length>10?[...head,`\u2026(+${value.length-10})`]:head}if(typeof value==="object")return sanitizeObject(value,depth,registry);return`<${typeof value}>`}function byteLengthOf(value){if(typeof value===
150
+ "string")return Buffer.byteLength(value);try{return Buffer.byteLength(JSON.stringify(value)??"")}catch{return 0}}function prune(dir,nowMs=Date.now()){let entries;try{entries=fs4.readdirSync(dir).filter(n=>/^session-.*\.jsonl$/.test(n))}catch{return}const stats=[];for(const name of entries){try{stats.push({name,mtime:fs4.statSync(path5.join(dir,name)).mtimeMs})}catch{}}stats.sort((a,b)=>b.mtime-a.mtime);const cutoff=nowMs-MAX_AGE_DAYS*24*60*60*1e3;stats.forEach((entry,index)=>{const overCount=index>=
151
+ MAX_FILES-1;const tooOld=entry.mtime<cutoff;if(!tooOld&&!overCount)return;if(!tooOld&&nowMs-entry.mtime<PRUNE_GRACE_MS)return;try{fs4.unlinkSync(path5.join(dir,entry.name))}catch{}})}var CROCKFORD="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function newSessionId(nowMs=Date.now()){let time="";let remaining=nowMs;for(let i=0;i<10;i++){time=`${CROCKFORD[remaining%32]??"0"}${time}`;remaining=Math.floor(remaining/32)}const bytes=crypto.randomBytes(16);let rand="";for(const byte of bytes)rand+=CROCKFORD[byte%32]??
152
+ "0";return`${time}${rand}`}import{readFileSync}from"fs";import{dirname as dirname2,join,resolve as resolve2,sep as sep3}from"path";function currentBranch(cwd=process.cwd()){let dir=cwd;for(;;){const gitPath=join(dir,".git");const head=readHead(gitPath);if(head!==null)return head;const parent=dirname2(dir);if(parent===dir)return null;dir=parent}}function readHead(gitPath){let headFile=join(gitPath,"HEAD");try{const stat2=readFileSync(gitPath,"utf8");const m=/^gitdir:\s*(.+)$/m.exec(stat2);if(m?.[1])headFile=join(resolve2(dirname2(
151
153
  gitPath),m[1].trim()),"HEAD")}catch{}try{const head=readFileSync(headFile,"utf8").trim();const ref=/^ref:\s*refs\/heads\/(.+)$/.exec(head);if(ref?.[1])return ref[1];return head.slice(0,7)}catch{return null}}function displayCwd(cwd=process.cwd(),home=process.env["HOME"]??process.env["USERPROFILE"]??""){if(!home)return cwd;const stripped=home.replace(new RegExp(`${escapeSep()}+$`),"");if(stripped==="")return cwd;const normalize=p=>process.platform==="win32"?p.toLowerCase():p;const h=normalize(stripped);
152
154
  const c=normalize(cwd);if(c===h)return"~";if(c.startsWith(h+sep3))return`~${cwd.slice(stripped.length)}`;return cwd}function escapeSep(){return sep3==="\\"?"\\\\":sep3}import{spawn}from"child_process";function keepTailBytes(buf,maxBytes){if(buf.length<=maxBytes)return{text:buf.toString("utf8"),droppedBytes:0};const start=buf.length-maxBytes;let cut=start;while(cut<buf.length&&(buf[cut]&192)===128)cut++;return{text:buf.subarray(cut).toString("utf8"),droppedBytes:cut}}function keepHeadBytes(text,maxBytes){const buf=Buffer.from(text,"utf8");if(buf.length<=maxBytes)return{text,truncated:false};let cut=maxBytes;while(cut>0&&(buf[cut]&192)===128)cut--;return{text:buf.subarray(0,cut).toString("utf8"),
153
155
  truncated:true}}import{existsSync}from"fs";import path6 from"path";var GIT_BASH_CANDIDATES=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe"];function system32Path(env,...rest){return system32(env,...rest)??path6.win32.join("C:\\Windows\\System32",...rest)}function defaultProbe(filePath){try{return existsSync(filePath)}catch{return false}}function selectShell(platform=process.platform,probe=defaultProbe,env=process.env){if(platform!=="win32"){return{toolName:"bash",command:"/bin/b\
@@ -169,15 +171,16 @@ String(input["path"]),ctx.cwd);const before=await readFile(abs,"utf8").catch(()=
169
171
  ok)return{content:applied.error,isError:true};await writeFile(abs,applied.after,"utf8");const rel=toolRelative(ctx.cwd,abs);return{content:`Edited ${rel} (${applied.count} replacement${applied.count===1?"":"s"}).`,summary:`edit_file \xB7 ${rel}`,diff:{path:rel,before,after:applied.after}}}};function apply(before,input){const eol=detectEol(before);const oldRaw=String(input["old_string"]);const newRaw=String(input["new_string"]);const replaceAll=input["replace_all"]===true;if(oldRaw==="")return{ok:false,
170
172
  error:"old_string must not be empty"};if(oldRaw===newRaw)return{ok:false,error:"old_string and new_string are identical"};const candidates=eol==="\r\n"?[applyEol(oldRaw,eol),oldRaw]:[oldRaw];for(const needle of candidates){const count=countOccurrences(before,needle);if(count===0)continue;if(count>1&&!replaceAll){return{ok:false,error:`old_string occurs ${count} times. Provide more surrounding context to make it unique, or set replace_all: true.`}}const replacement=applyEol(newRaw,eol);const after=replaceAll?
171
173
  before.split(needle).join(replacement):replaceOnce(before,needle,replacement);return{ok:true,after,count}}return{ok:false,error:"old_string not found in the file. Read the file again \u2014 whitespace and indentation must match exactly."}}function countOccurrences(haystack,needle){let count=0;let from=0;for(;;){const at=haystack.indexOf(needle,from);if(at===-1)return count;count+=1;from=at+needle.length}}function replaceOnce(haystack,needle,replacement){const at=haystack.indexOf(needle);return haystack.
172
- slice(0,at)+replacement+haystack.slice(at+needle.length)}import{spawn as spawn2}from"child_process";import path7 from"path";var GIT_TIMEOUT_MS=6e4;var MAX_GIT_OUTPUT_BYTES=1e5;var READ_ONLY_SUBCOMMANDS=["blame","branch","describe","diff","log","ls-files","rev-parse","shortlog","show","status","tag"];var DENIED_ARGS=new Set(["--no-index","-c","--config-env","--upload-pack","--receive-pack","--exec","--output"]);var LIST_ONLY_SUBCOMMANDS=new Set(["branch","tag"]);var gitTool={name:"git",domain:"local",risk:"exec",description:`Run a read-only git command. Allowed subcommands: ${READ_ONLY_SUBCOMMANDS.join(", ")}. Writing\
173
- operations (commit, push, checkout, add, ...) are not available here \u2014 use bash for those, which goes through the permission prompt.`,inputSchema:{type:"object",additionalProperties:false,properties:{subcommand:{type:"string",description:'The git subcommand, e.g. "log"',enum:[...READ_ONLY_SUBCOMMANDS]},args:{type:"array",description:'Arguments, e.g. ["--oneline", "-20"]. Each element is passed as a separate argv entry.',items:{type:"string"}}},required:["subcommand"]},execCommands(input){const sub=String(
174
- input["subcommand"]??"");const args=Array.isArray(input["args"])?input["args"].map(String):[];return{argv:[["git",...LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list"]:[sub],...args]]}},preview(input){const args=Array.isArray(input["args"])?input["args"].map(String):[];return`git \xB7 ${String(input["subcommand"]??"")} ${args.join(" ")}`.trim()},async run(input,ctx){const sub=String(input["subcommand"]);if(!READ_ONLY_SUBCOMMANDS.includes(sub)){return{content:`git ${sub} is not available (read-only su\
175
- bcommands only: ${READ_ONLY_SUBCOMMANDS.join(", ")}). Use bash for write operations.`,isError:true}}const args=Array.isArray(input["args"])?input["args"].map(String):[];for(const arg of args){const head=arg.split("=")[0]??arg;if(DENIED_ARGS.has(head)){return{content:`Argument ${arg} is not allowed for the git tool.`,isError:true}}}const argv=LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list",...args]:[sub,...args];const env=ctx.env??process.env;const exe=resolveGitExecutable({env});if(exe===null){return{
176
- content:'git executable was not found on PATH. On Windows the git tool resolves the executable to an absolute path from PATH (it never runs a bare "git", because Windows searches the current directory before PATH). Install Git for Windows or add its bin directory to PATH.',isError:true,summary:"git \xB7 \u5B9F\u884C\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"}}return runGit(exe,argv,ctx.cwd,env,ctx.signal)}};function resolveGitExecutable(deps={}){const platform=deps.
177
- platform??process.platform;if(platform!=="win32")return"git";const env=deps.env??process.env;const common={platform,...deps.isExecutableFile!==void 0?{isExecutableFile:deps.isExecutableFile}:{}};const spawnable=findExecutable("git",{...common,env:{...env,PATHEXT:".EXE;.COM"}});return spawnable??findExecutable("git",{...common,env})}function runGit(exe,argv,cwd,baseEnv,signal){return new Promise(resolve5=>{let child;try{child=spawn2(exe,["--no-pager",...argv],{cwd,shell:false,env:{...baseEnv,GIT_PAGER:"\
178
- cat",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true"},detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch(e){const err=e;const name=path7.basename(exe);resolve5({content:err.code==="EINVAL"?`Failed to start git: the resolved executable (${name}) is a .cmd/.bat shim, which Node refuses to spawn without a shell. Install Git for Windows (which provides git.exe) or put its bin directory earlier on PATH.`:`Failed to start git (${name}): ${err.code??"unknown \
179
- error"}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_GIT_OUTPUT_BYTES*2&&chunks.length>1){const dropped=chunks.shift();if(!dropped)break;bytes-=dropped.length}};child.stdout?.on("data",collect);child.stderr?.on("data",collect);let timedOut=false;const timer=setTimeout(()=>{timedOut=true;killProcessTree(child,"SIGKILL")},GIT_TIMEOUT_MS);
180
- const onAbort=()=>{killProcessTree(child,"SIGKILL")};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(code,err)=>{clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const kept=keepTailBytes(Buffer.concat(chunks),MAX_GIT_OUTPUT_BYTES);const body=kept.text;const note=kept.droppedBytes>0?`
174
+ slice(0,at)+replacement+haystack.slice(at+needle.length)}import{spawn as spawn2}from"child_process";import path7 from"path";var GIT_TIMEOUT_MS=6e4;var MAX_GIT_OUTPUT_BYTES=1e5;var READ_ONLY_SUBCOMMANDS=["blame","branch","describe","diff","log","ls-files","rev-parse","shortlog","show","status","tag"];var DENIED_ARGS=new Set(["--no-index","-c","--config-env","--upload-pack","--receive-pack","--exec","--output","--ext-diff","--textconv"]);var FORCED_ARGS={diff:["--no-ext-diff","--no-textconv"],log:["--no-ext-diff","--no-textconv"],show:["--no-ext-diff","--no-textconv"],blame:["--no-textconv"]};function isStatusVerbose(arg){
175
+ if(arg.startsWith("--")){const head=arg.split("=")[0]??arg;return head.length>2&&"--verbose".startsWith(head)}return/^-[A-Za-z]*v/.test(arg)}function buildGitArgv(sub,args){const head=LIST_ONLY_SUBCOMMANDS.has(sub)?[sub,"--list"]:[sub];return[...head,...FORCED_ARGS[sub]??[],...args]}var LIST_ONLY_SUBCOMMANDS=new Set(["branch","tag"]);var gitTool={name:"git",domain:"local",risk:"exec",description:`Run a read-only git command. Allowed subcommands: ${READ_ONLY_SUBCOMMANDS.join(", ")}. Writing opera\
176
+ tions (commit, push, checkout, add, ...) are not available here \u2014 use bash for those, which goes through the permission prompt.`,inputSchema:{type:"object",additionalProperties:false,properties:{subcommand:{type:"string",description:'The git subcommand, e.g. "log"',enum:[...READ_ONLY_SUBCOMMANDS]},args:{type:"array",description:'Arguments, e.g. ["--oneline", "-20"]. Each element is passed as a separate argv entry.',items:{type:"string"}}},required:["subcommand"]},execCommands(input){const sub=String(
177
+ input["subcommand"]??"");const args=Array.isArray(input["args"])?input["args"].map(String):[];return{argv:[["git",...buildGitArgv(sub,args)]]}},preview(input){const args=Array.isArray(input["args"])?input["args"].map(String):[];return`git \xB7 ${String(input["subcommand"]??"")} ${args.join(" ")}`.trim()},async run(input,ctx){const sub=String(input["subcommand"]);if(!READ_ONLY_SUBCOMMANDS.includes(sub)){return{content:`git ${sub} is not available (read-only subcommands only: ${READ_ONLY_SUBCOMMANDS.
178
+ join(", ")}). Use bash for write operations.`,isError:true}}const args=Array.isArray(input["args"])?input["args"].map(String):[];for(const arg of args){const head=arg.split("=")[0]??arg;if(DENIED_ARGS.has(head)){return{content:`Argument ${arg} is not allowed for the git tool.`,isError:true}}if(sub==="status"&&isStatusVerbose(arg)){return{content:`Argument ${arg} is not allowed for git status (it renders diffs through the repository's textconv drivers). Use the git tool's diff subcommand with --c\
179
+ ached instead.`,isError:true}}}const argv=buildGitArgv(sub,args);const env=ctx.env??process.env;const exe=resolveGitExecutable({env});if(exe===null){return{content:'git executable was not found on PATH. On Windows the git tool resolves the executable to an absolute path from PATH (it never runs a bare "git", because Windows searches the current directory before PATH). Install Git for Windows or add its bin directory to PATH.',isError:true,summary:"git \xB7 \u5B9F\u884C\u30D5\u30A1\u30A4\u30EB\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093"}}
180
+ return runGit(exe,argv,ctx.cwd,env,ctx.signal)}};function resolveGitExecutable(deps={}){const platform=deps.platform??process.platform;if(platform!=="win32")return"git";const env=deps.env??process.env;const common={platform,...deps.isExecutableFile!==void 0?{isExecutableFile:deps.isExecutableFile}:{}};const spawnable=findExecutable("git",{...common,env:{...env,PATHEXT:".EXE;.COM"}});return spawnable??findExecutable("git",{...common,env})}function runGit(exe,argv,cwd,baseEnv,signal){return new Promise(
181
+ resolve5=>{let child;try{child=spawn2(exe,["--no-pager",...argv],{cwd,shell:false,env:{...baseEnv,GIT_PAGER:"cat",PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true"},detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"]})}catch(e){const err=e;const name=path7.basename(exe);resolve5({content:err.code==="EINVAL"?`Failed to start git: the resolved executable (${name}) is a .cmd/.bat shim, which Node refuses to spawn without a shell. Install Git for Windows (which provi\
182
+ des git.exe) or put its bin directory earlier on PATH.`:`Failed to start git (${name}): ${err.code??"unknown error"}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}const chunks=[];let bytes=0;const collect=buf=>{chunks.push(buf);bytes+=buf.length;while(bytes-(chunks[0]?.length??0)>MAX_GIT_OUTPUT_BYTES*2&&chunks.length>1){const dropped=chunks.shift();if(!dropped)break;bytes-=dropped.length}};child.stdout?.on("data",collect);child.stderr?.on("data",collect);let timedOut=false;
183
+ const timer=setTimeout(()=>{timedOut=true;killProcessTree(child,"SIGKILL")},GIT_TIMEOUT_MS);const onAbort=()=>{killProcessTree(child,"SIGKILL")};if(signal){if(signal.aborted)onAbort();else signal.addEventListener("abort",onAbort,{once:true})}const finish=(code,err)=>{clearTimeout(timer);signal?.removeEventListener("abort",onAbort);const kept=keepTailBytes(Buffer.concat(chunks),MAX_GIT_OUTPUT_BYTES);const body=kept.text;const note=kept.droppedBytes>0?`
181
184
  [output truncated: dropped the first ${kept.droppedBytes} bytes]`:"";if(err){resolve5({content:`Failed to run git (${path7.basename(exe)}): ${err.code??err.message}`,isError:true,summary:"git \xB7 \u8D77\u52D5\u3067\u304D\u307E\u305B\u3093"});return}if(timedOut){resolve5({content:`${body}${note}
182
185
  [timed out after ${GIT_TIMEOUT_MS}ms]`,isError:true,summary:"git \xB7 \u30BF\u30A4\u30E0\u30A2\u30A6\u30C8"});return}resolve5({content:body===""?`(no output, exit code ${code??0})`:`${body}${note}`,...code!==0?{isError:true}:{},summary:`git ${argv[0]??""} \xB7 exit ${code??0}`})};child.on("error",e=>finish(null,e));child.on("close",code=>finish(code))})}import{glob}from"fs/promises";import{resolve as resolve3}from"path";var MAX_GLOB_RESULTS=500;var DEFAULT_EXCLUDES=["**/node_modules/**","**/.git/**","**/dist/**","**/.next/**","**/vendor/**"];var globTool={name:"glob",domain:"local",risk:"read",description:'Find files by glob pattern (e.g. "src/**/*.ts"). Returns paths relative to the working directory, sorted. node_modules, .git, dist, .next and vendor are excluded by default.',inputSchema:{type:"object",additionalProperties:false,properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.test.ts"'},
183
186
  path:{type:"string",description:"Directory to search in (default: the working directory)"},include_ignored:{type:"boolean",description:"Include node_modules / dist / vendor etc.",default:false}},required:["pattern"]},preview(input){return`glob \xB7 ${String(input["pattern"]??"")}`},async run(input,ctx){const root=input["path"]===void 0?resolve3(ctx.cwd):resolveToolPath(String(input["path"]),ctx.cwd);const pattern=String(input["pattern"]);const exclude=input["include_ignored"]===true?[]:DEFAULT_EXCLUDES;
@@ -199,6 +202,31 @@ limit"]:DEFAULT_LIMIT_LINES;const slice=lines.slice(offset-1,offset-1+limit);let
199
202
 
200
203
  [truncated: file has ${lines.length} lines; re-read with offset/limit for the rest]`:"";if(body===""){const reason=lines.length===0?"(empty file)":`(no lines at offset ${offset}; the file has ${lines.length} lines)`;return{content:reason,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (0 \u884C)`}}return{content:body+note,summary:`read_file \xB7 ${toolRelative(ctx.cwd,abs)} (${slice.length} \u884C${eol==="\r\n"?" \xB7 CRLF":""})`}}};import{mkdir,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{dirname as dirname3}from"path";var writeFileTool={name:"write_file",domain:"local",risk:"write",description:"Write the full content of a file, creating it (and parent directories) if needed. Overwrites the whole file \u2014 prefer edit_file for partial changes. The existing line ending style (LF/CRLF) is preserved.",inputSchema:{type:"object",additionalProperties:false,properties:{path:{type:"string",description:"File path, relative to the working directory"},content:{type:"string",description:"Full new content. Use \\n for li\
201
204
  ne breaks."}},required:["path","content"]},preview(input){const content=typeof input["content"]==="string"?input["content"]:"";return`write_file \xB7 ${String(input["path"]??"")} (${content.split("\n").length} \u884C)`},async prepare(input,ctx){const abs=resolveToolPath(String(input["path"]),ctx.cwd);const before=await readFile4(abs,"utf8").catch(()=>"");return{path:toolRelative(ctx.cwd,abs),before,after:String(input["content"]??"")}},async run(input,ctx){const abs=resolveToolPath(String(input["\
202
- path"]),ctx.cwd);const existing=await readFile4(abs,"utf8").catch(()=>null);const eol=existing===null?"\n":detectEol(existing);const body=applyEol(String(input["content"]),eol);await mkdir(dirname3(abs),{recursive:true});await writeFile2(abs,body,"utf8");const rel=toolRelative(ctx.cwd,abs);return{content:`Wrote ${rel} (${body.split(eol).length} lines${eol==="\r\n"?", CRLF preserved":""}).`,summary:`write_file \xB7 ${rel}`,diff:{path:rel,before:existing??"",after:String(input["content"])}}}};var RESIDENT_TOKEN_CAP=8e3;function localTools(choice=selectShell()){return[readFileTool,writeFileTool,editFileTool,createBashTool(choice),globTool,grepTool,gitTool]}function buildResidentSet(mode,opts={}){const all=opts.tools??localTools();const cap=opts.cap??RESIDENT_TOKEN_CAP;const eligible=all.filter(tool=>matchesAnyGlob(tool.name,mode.tools)&&applyPermissionMode(checkPermission(tool.name,mode),tool.risk,opts.permissionMode).decision!=="deny"&&!isWholeToolDenied(tool.name,opts.permissionLayers??[]));const tools=[];const dropped=[];
203
- let tokens=0;for(const tool of eligible){const cost=estimateToolTokens(tool);if(tokens+cost>cap){dropped.push(tool.name);continue}tools.push(tool);tokens+=cost}return{tools,wire:tools.map(toWireTool),tokens,dropped}}function estimateToolTokens(tool){return Math.ceil(JSON.stringify(toWireTool(tool)).length/4)}function matchesAnyGlob(name,patterns){return patterns.some(pattern=>globToRegExp(pattern).test(name))}function globToRegExp(pattern){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").
204
- replace(/\*/g,".*");return new RegExp(`^${escaped}$`)}export{secretReason,parseRule,projectPermissionsPath,projectRootFor,persistProjectAllow,activatePermissionSettings,executeTool,buildSystemPrompt,runTurn,parseFrontMatter,lstatOrNull,findProjectTwpSubdir,activateModeFiles,describeAuditLog,createAuditLogger,currentBranch,displayCwd,resolveGitExecutable,readFileTool,RESIDENT_TOKEN_CAP,localTools,buildResidentSet};
205
+ path"]),ctx.cwd);const existing=await readFile4(abs,"utf8").catch(()=>null);const eol=existing===null?"\n":detectEol(existing);const body=applyEol(String(input["content"]),eol);await mkdir(dirname3(abs),{recursive:true});await writeFile2(abs,body,"utf8");const rel=toolRelative(ctx.cwd,abs);return{content:`Wrote ${rel} (${body.split(eol).length} lines${eol==="\r\n"?", CRLF preserved":""}).`,summary:`write_file \xB7 ${rel}`,diff:{path:rel,before:existing??"",after:String(input["content"])}}}};var RESIDENT_TOKEN_CAP=8e3;function localTools(choice=selectShell()){return[readFileTool,writeFileTool,editFileTool,createBashTool(choice),globTool,grepTool,gitTool]}function buildResidentSet(mode,opts={}){const all=opts.tools??localTools();const cap=opts.cap??RESIDENT_TOKEN_CAP;const eligible=all.filter(tool=>matchesAnyGlob(tool.name,mode.tools)&&applyPermissionMode(checkPermission(tool.name,mode),tool.risk,opts.permissionMode).decision!=="deny"&&!isWholeToolDenied(tool.name,opts.permissionLayers??[]));const usage=opts.usage;
206
+ const pinned=opts.pinned;const ordered=usage===void 0&&pinned===void 0?eligible:eligible.map((tool,i)=>({tool,i,pin:pinned?.has(tool.name)===true,uses:usage?.get(tool.name)??0})).sort((a,b)=>Number(b.pin)-Number(a.pin)||b.uses-a.uses||a.i-b.i).map(entry=>entry.tool);const tools=[];const dropped=[];let tokens=0;for(const tool of ordered){const cost=estimateToolTokens(tool);if(tokens+cost>cap){dropped.push(tool.name);continue}tools.push(tool);tokens+=cost}return{tools,wire:tools.map(toWireTool),tokens,
207
+ dropped}}function estimateToolTokens(tool){return Math.ceil(JSON.stringify(toWireTool(tool)).length/4)}function matchesAnyGlob(name,patterns){return patterns.some(pattern=>globToRegExp(pattern).test(name))}function globToRegExp(pattern){const escaped=pattern.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${escaped}$`)}var CATALOG_TOOL_PREFIX="twp_";var WIRE_NAME_RE=/^[A-Za-z0-9_-]{1,64}$/;var MAX_RESULT_CHARS=4e4;function catalogToolName(op){if(op.name.includes("_")||op.domain.includes("_"))return null;const name=`${CATALOG_TOOL_PREFIX}${op.name.replace(/\./g,"-")}_${op.domain}`;return WIRE_NAME_RE.test(name)?name:null}function parseCatalogToolName(name){if(!name.startsWith(CATALOG_TOOL_PREFIX))return null;const rest=name.slice(CATALOG_TOOL_PREFIX.length);const sep4=rest.indexOf("_");if(sep4<=0||sep4===rest.length-
208
+ 1)return null;const domain=rest.slice(sep4+1);return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(domain)?{domain}:null}function toolRiskOf(risk){switch(risk){case"read":return"read";case"write":return"write";default:return"exec"}}var SIMPLE_TYPES=new Set(["string","integer","number","boolean","array","object"]);function paramSchema(param){const declared=param.type;const schema={};if(typeof declared==="string"&&SIMPLE_TYPES.has(declared)&&declared!=="integer"&&declared!=="number"){schema.type=declared}if(param.
209
+ description!==void 0&&param.description!=="")schema.description=param.description;return schema}function inputSchemaOf(op){const properties={};const required=[];for(const param of op.pathParams){properties[param.name]={description:param.description||`path parameter ${param.name}`};required.push(param.name)}for(const param of op.queryParams){if(Object.hasOwn(properties,param.name))continue;properties[param.name]=paramSchema(param);if(param.required)required.push(param.name)}if(op.body!==null&&op.
210
+ method!=="GET"){properties["body"]={type:"object",description:"JSON request body (see twp_describe_tools for its schema)"}}return{type:"object",properties,...required.length>0?{required}:{},additionalProperties:false}}function catalogTool(op,deps){const name=catalogToolName(op);if(name===null)return null;const summary=op.summary!==""?op.summary:`${op.method} ${op.path}`;const risk=toolRiskOf(op.risk);return{name,domain:op.domain,risk,description:`${summary} (${op.method} ${op.path})`,inputSchema:inputSchemaOf(
211
+ op),preview:input=>previewOf(op,input),run:async input=>runOperation(op,name,input,deps)}}function previewOf(op,input){let path8=op.path;for(const param of op.pathParams){const value=input[param.name];path8=path8.split(`{${param.name}}`).join(typeof value==="string"||typeof value==="number"?String(value):`{${param.name}}`)}return`${op.method} ${path8}`}function buildRequest(op,input){const errors=[];let path8=op.path;const pathNames=new Set;for(const param of op.pathParams){pathNames.add(param.name);
212
+ const raw=input[param.name];const value=typeof raw==="number"?String(raw):raw;if(!isSafePathSegment(value)){errors.push(`${param.name}: \u30D1\u30B9\u8981\u7D20\u3068\u3057\u3066\u4F7F\u3048\u306A\u3044\u5024\u3067\u3059`);continue}path8=path8.split(`{${param.name}}`).join(value)}const query={};for(const[key,value]of Object.entries(input)){if(pathNames.has(key)||key==="body")continue;query[key]=value}const body=input["body"];errors.push(...validateQuery(op.queryParams,query));if(op.body!==null&&
213
+ op.method!=="GET")errors.push(...validateBody(op.body.schema,body??{}));if(errors.length>0)return{ok:false,errors};return{ok:true,path:path8.toLowerCase().startsWith("/api/")?path8:`/api${path8}`,query,body}}async function runOperation(op,name,input,deps){const built=buildRequest(op,input);if(!built.ok){const shown=built.errors.slice(0,MAX_REPORTED_VIOLATIONS);return{content:`Invalid input for ${name}:
214
+ - ${shown.join("\n- ")}`,isError:true,summary:`${name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}let response;try{response=await deps.client().request(op.method,appendQuery(built.path,built.query),built.body)}catch(err){if(err instanceof ApiError){return{content:`${name} failed: ${err.message}`,isError:true,summary:`${name} \xB7 HTTP ${err.status}`}}throw err}return{content:truncate(redactSecrets(JSON.stringify(redactSecretValues(response??null),null,1))),summary:previewOf(op,input)}}function truncate(text,limit=MAX_RESULT_CHARS){
215
+ if(text.length<=limit)return text;return`${text.slice(0,limit)}
216
+ \u2026(truncated: ${text.length-limit} more characters. Narrow the request with query parameters such as limit / keyword.)`}var SEARCH_LIMIT=20;var DESCRIBE_LIMIT=10;var MOUNT_LIMIT=12;var bundledSource={index:loadCommandModelIndex,domain:loadCommandModelDomain};var TwpToolkit=class{source;client;tools=new Map;operations=new Map;loadedDomains=new Set;mountedNames=[];usage=new Map;meta;constructor(opts){this.source=opts.source??bundledSource;this.client=opts.client;this.meta=[this.domainsTool(),this.searchTool(),this.describeTool(),this.callTool(),this.mountTool()]}metaTools(){return[...this.meta]}mountedTools(){return this.
217
+ mountedNames.flatMap(name=>{const tool=this.tools.get(name);return tool?[tool]:[]})}resolveTool=name=>this.tools.get(name);prepareIndirect=async input=>{const name=input["name"]??input["tool"];if(typeof name!=="string")return;await this.ensureLoaded(name).catch(()=>void 0)};recordUse(name){this.usage.set(name,(this.usage.get(name)??0)+1)}async ensureLoaded(name){const parsed=parseCatalogToolName(name);if(parsed===null)return void 0;await this.loadDomain(parsed.domain);return this.tools.get(name)}async loadDomain(domain){
218
+ const file=await this.source.domain(domain);if(!this.loadedDomains.has(domain)){for(const op of file.operations){const tool=catalogTool(op,{client:this.client});if(tool===null||this.tools.has(tool.name))continue;const run=tool.run;this.tools.set(tool.name,{...tool,run:async(input,ctx)=>{this.recordUse(tool.name);return run(input,ctx)}});this.operations.set(tool.name,op)}this.loadedDomains.add(domain)}return file.operations}async loadAll(){const index=await this.source.index();await Promise.all(index.
219
+ domains.map(d=>this.loadDomain(d.domain).catch(()=>[])))}domainsTool(){return{name:"twp_domains",domain:"meta",risk:"read",description:"List TWP API domains (tasks, projects, attendance, sales, ...) with operation counts. Use twp_search_tools to find a specific operation.",inputSchema:{type:"object",properties:{},additionalProperties:false},preview:()=>"twp_domains",run:async()=>guarded(async()=>{const index=await this.source.index();const lines=index.domains.map(d=>`${d.domain} (${d.operationCount}\
220
+ )${d.summary!==""?`: ${d.summary}`:""}`);return{content:`${index.totals.domains} domains / ${index.totals.operations} operations
221
+ ${lines.join("\n")}`}})}}searchTool(){return{name:"twp_search_tools",domain:"meta",risk:"read",description:"Search the TWP API tool catalog. Returns tool names with a one-line summary only (no schema). Query words match tool name, domain, path and summary (Japanese summaries are common, so Japanese keywords work). Then call twp_describe_tools for the schema and twp_call to run it.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Space separated keywords"},domain:{type:"s\
222
+ tring",description:"Limit the search to one domain (see twp_domains)"}},required:["query"],additionalProperties:false},preview:input=>`twp_search_tools ${String(input["query"]??"")}`,run:async input=>guarded(async()=>{const domain=typeof input["domain"]==="string"&&input["domain"]!==""?input["domain"]:null;if(domain!==null)await this.loadDomain(domain);else await this.loadAll();const all=searchCatalog([...this.operations.entries()],String(input["query"]??""),domain,Number.POSITIVE_INFINITY);if(all.
223
+ length===0)return{content:"No matching tools. Try other keywords or twp_domains."};const hits=all.slice(0,SEARCH_LIMIT);const lines=hits.map(({name,op})=>`${name} [${op.risk}] ${op.summary||`${op.method} ${op.path}`}`);if(all.length>hits.length)lines.push(`(${all.length-hits.length} more matches; narrow the query or pass domain)`);return{content:lines.join("\n")}})}}describeTool(){return{name:"twp_describe_tools",domain:"meta",risk:"read",description:`Return the full JSON Schema of the named TWP\
224
+ tools (max ${DESCRIBE_LIMIT}). Names come from twp_search_tools.`,inputSchema:{type:"object",properties:{names:{type:"array",items:{type:"string"}}},required:["names"],additionalProperties:false},preview:input=>`twp_describe_tools ${Array.isArray(input["names"])?input["names"].join(", "):""}`,run:async input=>guarded(async()=>{const requested=input["names"].filter(n=>typeof n==="string");const names=requested.slice(0,DESCRIBE_LIMIT);const out=[];for(const name of names){const tool=await this.ensureLoaded(
225
+ name).catch(()=>void 0);const op=this.operations.get(name);if(!tool||!op){out.push({name,error:"unknown tool"});continue}out.push({name,risk:op.risk,method:op.method,path:op.path,description:tool.description,input_schema:tool.inputSchema,...op.body!==null&&op.method!=="GET"?{body_schema:op.body.schema}:{},...op.resultPath!==null?{result_path:op.resultPath}:{}})}const rest=requested.length-names.length;const note=rest>0?`
226
+ (${rest} more names were not described; call again with them)`:"";return{content:truncate(JSON.stringify(out,null,1))+note}})}}callTool(){return{name:INDIRECT_TOOL,domain:"meta",risk:"read",description:"Run a TWP catalog tool by name. input is validated against the tool schema at call time. Permission is checked against the real tool name, not twp_call.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Tool name from twp_search_tools (e.g. twp_list_project-task)"},input:{type:"\
227
+ object",description:"Arguments for the tool (see twp_describe_tools)"}},required:["name"],additionalProperties:false},preview:input=>{const tool=typeof input["name"]==="string"?this.tools.get(input["name"]):void 0;const inner=input["input"]??{};return tool?`${INDIRECT_TOOL} \u2192 ${safe(()=>tool.preview(inner),tool.name)}`:`${INDIRECT_TOOL} ${String(input["name"]??"")}`},run:async(input,ctx)=>guarded(async()=>{const name=String(input["name"]);const tool=this.tools.get(name)??await this.ensureLoaded(
228
+ name);if(!tool)return{content:`Unknown tool: ${name}. Use twp_search_tools.`,isError:true};const validated=validateInput(tool.inputSchema,input["input"]??{});if(!validated.ok){return{content:`Invalid input for ${name}:
229
+ - ${validated.errors.join("\n- ")}`,isError:true,summary:`${name} \xB7 \u5165\u529B\u304C\u4E0D\u6B63`}}return tool.run(validated.value,ctx)})}}mountTool(){return{name:"twp_mount",domain:"meta",risk:"read",description:`Add up to ${MOUNT_LIMIT} main tools of a TWP domain to your tool list from the next turn on (sticky for this session). Use it when you will call the same domain repeatedly; otherwise twp_call is enough.`,inputSchema:{type:"object",properties:{domain:{type:"string"}},required:["dom\
230
+ ain"],additionalProperties:false},preview:input=>`twp_mount ${String(input["domain"]??"")}`,run:async input=>guarded(async()=>{const domain=String(input["domain"]);const ops=await this.loadDomain(domain);const picked=pickMainOperations(ops).map(op=>catalogToolName(op)).filter(name=>name!==null&&this.tools.has(name));for(const name of picked)if(!this.mountedNames.includes(name))this.mountedNames.push(name);return{content:`Mounted from the next turn: ${picked.join(", ")||"(none)"}`}})}}};function pickMainOperations(ops){
231
+ const order={read:0,write:1,destructive:2};return[...ops].sort((a,b)=>order[a.risk]-order[b.risk]).slice(0,MOUNT_LIMIT)}function searchCatalog(entries,query,domain,limit=SEARCH_LIMIT){const words=query.toLowerCase().split(/\s+/).filter(w=>w!=="");if(words.length===0)return[];const hits=[];for(const[name,op]of entries){if(domain!==null&&op.domain!==domain)continue;const haystack=`${name} ${op.domain} ${op.path} ${op.summary} ${op.aliases.join(" ")}`.toLowerCase();let score=0;for(const word of words)
232
+ if(haystack.includes(word))score+=op.summary.toLowerCase().includes(word)?2:1;if(score>0)hits.push({name,op,score})}return hits.sort((a,b)=>b.score-a.score||a.name.localeCompare(b.name)).slice(0,limit)}async function guarded(fn){try{return await fn()}catch(err){if(err instanceof CommandModelMissingError)return{content:err.message,isError:true};throw err}}function safe(fn,fallback){try{return fn()}catch{return fallback}}function createTwpToolkit(runtime,cliVersion){let client=null;return new TwpToolkit({client:()=>{client??=new TwpApiClient(runtime.apiUrl,runtime.session??new AuthSession(runtime.profileName,runtime.apiUrl),httpFetch,cliVersion);return client}})}function residentInputs(toolkit,local=localTools()){const meta=toolkit.metaTools();return{tools:[...local,...meta,...toolkit.mountedTools()],usage:toolkit.usage,pinned:new Set([...local,...meta].map(t=>t.name))}}export{secretReason,parseRule,projectPermissionsPath,projectRootFor,persistProjectAllow,activatePermissionSettings,executeTool,buildSystemPrompt,runTurn,parseFrontMatter,lstatOrNull,findProjectTwpSubdir,activateModeFiles,describeAuditLog,createAuditLogger,currentBranch,displayCwd,resolveGitExecutable,readFileTool,RESIDENT_TOKEN_CAP,localTools,buildResidentSet,createTwpToolkit,residentInputs};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{redactSecretValues,redactSecrets}from"./chunk-EQWW2F5V.js";import{formatOutput}from"./chunk-K2ONOH3L.js";function renderOutput(value,format,noRedact=false){if(noRedact)return formatOutput(value,format);return redactSecrets(formatOutput(redactSecretValues(value),format))}export{renderOutput};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{PACKAGE_NAME,UPDATE_COMMAND,compareVersionCores,parseVersionCore}from"./chunk-DXXFUNYN.js";import{isBoolishTrue}from"./chunk-5WGOHFAS.js";import{loadUserConfig}from"./chunk-NERYSBA4.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{spawn}from"child_process";import fs from"fs";import path from"path";var CHECK_INTERVAL_MS=24*60*60*1e3;var DISABLE_ENV="TWP_NO_AUTO_UPDATE";var WORKER_ENV="TWP_AUTO_UPDATE_WORKER";var PARENT_PID_ENV="TWP_AUTO_UPDATE_PARENT_PID";function stateFilePath(env=process.env){return path.join(twpHomeDir(env),"update-state.json")}function lockFilePath(env=process.env){return path.join(twpHomeDir(env),"update.lock")}function runDirPath(env=process.env){return path.join(twpHomeDir(env),"run")}function registerRunning(env=process.env){try{const dir=runDirPath(env);fs.mkdirSync(
3
+ import{PACKAGE_NAME,UPDATE_COMMAND,compareVersionCores,parseVersionCore}from"./chunk-DXXFUNYN.js";import{loadUserConfig}from"./chunk-NERYSBA4.js";import{isBoolishTrue}from"./chunk-5WGOHFAS.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{spawn}from"child_process";import fs from"fs";import path from"path";var CHECK_INTERVAL_MS=24*60*60*1e3;var DISABLE_ENV="TWP_NO_AUTO_UPDATE";var WORKER_ENV="TWP_AUTO_UPDATE_WORKER";var PARENT_PID_ENV="TWP_AUTO_UPDATE_PARENT_PID";function stateFilePath(env=process.env){return path.join(twpHomeDir(env),"update-state.json")}function lockFilePath(env=process.env){return path.join(twpHomeDir(env),"update.lock")}function runDirPath(env=process.env){return path.join(twpHomeDir(env),"run")}function registerRunning(env=process.env){try{const dir=runDirPath(env);fs.mkdirSync(
4
4
  dir,{recursive:true,mode:448});const file=path.join(dir,String(process.pid));fs.writeFileSync(file,"",{mode:384});process.once("exit",()=>{try{fs.rmSync(file,{force:true})}catch{}})}catch{}}function listRegisteredPids(env=process.env){try{return fs.readdirSync(runDirPath(env)).filter(name=>/^\d+$/.test(name)).map(Number)}catch{return[]}}function readUpdateState(env=process.env){try{const parsed=JSON.parse(fs.readFileSync(stateFilePath(env),"utf8"));return parsed!==null&&typeof parsed==="object"&&
5
5
  !Array.isArray(parsed)?parsed:{}}catch{return{}}}function writeUpdateState(state,env=process.env){const file=stateFilePath(env);const tmp=`${file}.${process.pid}.tmp`;try{fs.mkdirSync(path.dirname(file),{recursive:true,mode:448});fs.rmSync(tmp,{force:true});fs.writeFileSync(tmp,`${JSON.stringify(state,null,2)}
6
6
  `,{mode:384,flag:"wx"});fs.renameSync(tmp,file)}catch{try{fs.rmSync(tmp,{force:true})}catch{}}}function autoUpdateDisabledReason(env=process.env){if(isBoolishTrue(env[DISABLE_ENV]))return`${DISABLE_ENV} \u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059`;if(isBoolishTrue(env["CI"]))return"CI \u74B0\u5883\uFF08CI \u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059\uFF09";if(process.getuid?.()===0&&(env["SUDO_UID"]??"")!=="")return"sudo \u3067\u5B9F\u884C\u3055\u308C\u3066\u3044\u307E\u3059";
@@ -0,0 +1,3 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{UsageError}from"./chunk-M3GWY6NT.js";async function evaluateQuery(expression,value){if(expression.trim()===""){throw new UsageError("--query \u306B\u7A7A\u306E\u5F0F\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093")}const{search}=await import("./dist-HZIZTJ4O.js");try{return search(value??null,expression)}catch(err){throw new UsageError(`--query \u306E\u5F0F\u3092\u8A55\u4FA1\u3067\u304D\u307E\u305B\u3093: ${err.message}`)}}export{evaluateQuery};
@@ -0,0 +1,12 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{stripTerminalControls}from"./chunk-NHYMHCAT.js";var SENSITIVE_HEADERS=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-vercel-protection-bypass"]);var REDACTED="***\uFF08\u4F0F\u5B57\uFF09";var SECRET_KEY_PATTERN="[A-Za-z0-9_-]*(?:token|secret|password|passwd|api[_-]?key|credential|signature)[A-Za-z0-9_-]*";var NOT_SECRET_FLAGS="(?:starting-token)";function redactSecrets(text){return text.replace(/\bBearer\s+[^\s"'`,;)\]}]+/gi,`Bearer ${REDACTED}`).replace(new RegExp(`("${SECRET_KEY_PATTERN}"\\\
4
+ s*:\\s*)"(?:[^"\\\\]|\\\\.)*"`,"gi"),`$1"${REDACTED}"`).replace(new RegExp(`([?&]${SECRET_KEY_PATTERN}=)[^&\\s"'\`,;)\\]}]+`,"gi"),`$1${REDACTED}`).replace(new RegExp(`(--(?!${NOT_SECRET_FLAGS}(?:=|\\s))${SECRET_KEY_PATTERN}(?:=|\\s+))('[^']*'|"[^"]*"|[A-Za-z0-9_.~+/=|:%-]+)`,"gi"),`$1${REDACTED}`)}var SECRET_KEY_NAME=new RegExp(`^${SECRET_KEY_PATTERN}$`,"i");function redactSecretValues(value){if(Array.isArray(value))return value.map(item=>redactSecretValues(item));if(value!==null&&typeof value===
5
+ "object"){const out={};for(const[key,item]of Object.entries(value)){out[key]=SECRET_KEY_NAME.test(key)?REDACTED:redactSecretValues(item)}return out}return value}function formatHeaders(headers){if(!headers)return[];const entries=headers instanceof Headers?[...headers.entries()]:Array.isArray(headers)?headers:Object.entries(headers);return entries.map(([name,value])=>{const shown=SENSITIVE_HEADERS.has(name.toLowerCase())?REDACTED:redactSecrets(String(value));return` ${name.toLowerCase()}: ${shown}`})}
6
+ var BODY_LIMIT=4e3;function formatBody(raw){const safe=redactSecrets(stripTerminalControls(raw));return safe.length>BODY_LIMIT?`${safe.slice(0,BODY_LIMIT)}
7
+ \u2026\uFF08\u4EE5\u964D ${safe.length-BODY_LIMIT} \u6587\u5B57\u3092\u7701\u7565\uFF09`:safe}function isTextualContentType(contentType){if(contentType===null)return false;return/^\s*(text\/|application\/(json|xml|javascript|x-www-form-urlencoded)|application\/[\w.+-]*\+(json|xml))/i.test(contentType)}function withDebug(inner,options={}){const write=options.write??(text=>void process.stderr.write(text));const now=options.now??(()=>Date.now());return async(input,init)=>{const method=init?.method??
8
+ "GET";const lines=[`[debug] \u2192 ${method} ${redactSecrets(input)}`,...formatHeaders(init?.headers)];if(typeof init?.body==="string")lines.push(` ${formatBody(init.body)}`);write(`${lines.join("\n")}
9
+ `);const started=now();let res;try{res=await inner(input,init)}catch(err){write(`[debug] \u2717 \u901A\u4FE1\u306B\u5931\u6557\u3057\u307E\u3057\u305F (${now()-started}ms): ${redactSecrets(err.message)}
10
+ `);throw err}const out=[`[debug] \u2190 ${res.status} ${res.statusText} (${now()-started}ms)`,...formatHeaders(res.headers)];const contentType=res.headers.get("content-type");if(isTextualContentType(contentType)){const raw=await res.clone().text().catch(()=>"\uFF08\u672C\u6587\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F\uFF09");if(raw!=="")out.push(` ${formatBody(raw)}`)}else{const length=res.headers.get("content-length");out.push(` \uFF08\u672C\u6587\u306F ${contentType??"content-ty\
11
+ pe \u4E0D\u660E"}\u30FB${length===null?"\u30B5\u30A4\u30BA\u4E0D\u660E":`${length} \u30D0\u30A4\u30C8`}\u3002\u30C6\u30AD\u30B9\u30C8\u3067\u306A\u3044\u305F\u3081\u51FA\u529B\u3057\u306A\u3044\uFF09`)}write(`${out.join("\n")}
12
+ `);return res}}export{redactSecrets,redactSecretValues,withDebug};
@@ -0,0 +1,52 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{ApiError}from"./chunk-JKSXUBND.js";import{isTaskKey}from"./chunk-II5RVJQN.js";import{ResolveError,UUID_RE,isSafePathSegment,resolveProjectRef,safeProjectIdPolicy}from"./chunk-X4RS5VBH.js";import{loadProjectConfig,loadUserConfig}from"./chunk-NERYSBA4.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{UsageError}from"./chunk-M3GWY6NT.js";var BACKLOG_BASE_PATH="/api/v2/integrations/backlog";function assertBacklogPathSegment(value,label){if(!isSafePathSegment(value)){throw new ResolveError(`${label}\u3068\u3057\u3066 URL \u306B\u5165\u308C\u3089\u308C\u306A\u3044\u5024\u304C\u30B5\u30FC\u30D0\u304B\u3089\u8FD4\u308A\u307E\u3057\u305F: ${JSON.stringify(value)}\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return value}function backlogSpacePath(spaceId,suffix=""){assertBacklogPathSegment(spaceId,
4
+ "Backlog \u30B9\u30DA\u30FC\u30B9 ID");return`${BACKLOG_BASE_PATH}/${encodeURIComponent(spaceId)}${suffix}`}function idString(value){if(typeof value==="number"&&Number.isFinite(value))return String(value);if(typeof value==="string"&&value.trim()!=="")return value.trim();return null}function text(value){return typeof value==="string"&&value.trim()!==""?value.trim():null}function backlogSpaceAliases(spaceUrl){const aliases=[];const trimmed=spaceUrl.trim().replace(/\/+$/,"");if(trimmed==="")return aliases;
5
+ let host;try{host=new URL(trimmed).host}catch{host=trimmed.replace(/^\/+/,"").split("/")[0]??""}if(host==="")return aliases;aliases.push(host);const label=host.split(".")[0];if(label!==void 0&&label!==""&&label!==host)aliases.push(label);return aliases}function backlogSpaceRow(row){const url=text(row["space_url"]);return{id:idString(row["id"]),name:url,code:null,aliases:url!==null?backlogSpaceAliases(url):[]}}function backlogProjectRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:text(
6
+ row["projectKey"])}}function backlogStatusRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:null}}function backlogUserRow(row){return{id:idString(row["id"]),name:text(row["name"]),code:null,aliases:[text(row["userId"]),text(row["mailAddress"])].filter(v=>v!==null)}}var DEFAULT_LOOKUP_SCOPE="\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8";function fold(value){return value.trim().toLowerCase()}function keysOf(ref){return[ref.id,ref.code,ref.name,...ref.aliases??[]].filter(v=>typeof v==="string"&&v.trim()!=="").map(fold)}function describe(ref){return ref.code!==void 0&&ref.code!==null&&ref.code!==""&&ref.code!==ref.name?`${ref.name}\uFF08${ref.code}\uFF09`:ref.name}async function suggest(input,candidates){try{const{default:fuzzysort}=await import("./fuzzysort-DFVKV4B4.js");
7
+ const indexed=candidates.map(ref=>({hay:keysOf(ref).join(" "),ref}));const hits=fuzzysort.go(input.trim(),indexed,{key:"hay",limit:5,threshold:-1e4});return hits.map(hit=>hit.obj.ref)}catch{return[]}}function listCandidates(candidates,limit=10){const shown=candidates.slice(0,limit).map(describe).join(" / ");return candidates.length>limit?`${shown} \u2026\uFF08\u5168 ${candidates.length} \u4EF6\uFF09`:shown}async function resolveNamed(input,candidates,ctx){const needle=fold(input);if(needle===""){
8
+ throw new UsageError(`${ctx.flag} \u306B\u7A7A\u306E\u5024\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`)}if(candidates.length===0){throw new UsageError(`${ctx.scope??DEFAULT_LOOKUP_SCOPE}\u306B\u306F${ctx.label}\u304C1\u4EF6\u3082\u5B9A\u7FA9\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF08${ctx.flag} ${input}\uFF09`)}const hits=candidates.filter(ref=>keysOf(ref).includes(needle));const distinct=[...new Map(hits.map(ref=>[ref.id,ref])).values()];if(distinct.length===1)return distinct[0];if(distinct.
9
+ length>1){throw new UsageError(`${ctx.flag} \u306E\u300C${input}\u300D\u304C${ctx.label}${distinct.length}\u4EF6\u306B\u4E00\u81F4\u3057\u307E\u3059: ${listCandidates(distinct)}`,`\u3069\u308C\u304B1\u3064\u306B\u6C7A\u307E\u308B\u5024\uFF08ID \u304B\u30B3\u30FC\u30C9\uFF09\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}const near=await suggest(input,candidates);throw new UsageError(`${ctx.flag} \u306E\u300C${input}\u300D\u306B\u4E00\u81F4\u3059\u308B${ctx.label}\u304C\u3042\u308A\u307E\u305B\u3093`,
10
+ near.length>0?`\u3082\u3057\u304B\u3057\u3066: ${listCandidates(near,5)}\uFF08\u5168 ${candidates.length} \u4EF6\uFF09`:`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${listCandidates(candidates)}`)}function usable(value){return typeof value==="string"&&value.trim()!==""?value.trim():null}function resolveDefaultProject(explicit,profileName,env=process.env,cwd=process.cwd()){const fromFlag=usable(explicit);if(fromFlag!==null)return{ref:fromFlag,source:"flag"};const fromEnv=usable(env.TWP_PROJECT);if(fromEnv!==null)return{ref:fromEnv,source:"env"};const fromProjectConfig=usable(loadProjectConfig(cwd).project);if(fromProjectConfig!==null)return{ref:fromProjectConfig,source:"project-config"};const user=loadUserConfig(
11
+ env);const fromProfile=usable(user.profiles?.[profileName]?.project);if(fromProfile!==null)return{ref:fromProfile,source:"user-config"};const fromUser=usable(user.project);if(fromUser!==null)return{ref:fromUser,source:"user-config"};return null}function requireDefaultProject(explicit,profileName,env=process.env,cwd=process.cwd()){const resolved=resolveDefaultProject(explicit,profileName,env,cwd);if(resolved!==null)return resolved;throw new UsageError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u304C\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
12
+ '--project <\u30B3\u30FC\u30C9|ID> \u3092\u4ED8\u3051\u308B\u304B\u3001TWP_PROJECT / .twp/config.json / ~/.twp/config.json \u306E "project" \u306B\u65E2\u5B9A\u3092\u8A2D\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002')}import crypto from"crypto";import fs from"fs";import path from"path";var DEFAULT_TTL_MS=10*60*1e3;var CACHE_VERSION=3;function cacheDir(env=process.env){return path.join(twpHomeDir(env),"cache")}function cacheFilePath(key,env=process.env){const digest=crypto.createHash("sha256").update(JSON.stringify([key.profile,key.scope,key.project??""])).digest("hex").slice(0,12);const label=key.scope.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,40);return path.join(cacheDir(env),`${label}-${digest}.json`)}function sameKey(a,b){return a.profile===b.profile&&a.scope===b.scope&&(a.project??
13
+ "")===(b.project??"")}function isOursAndPrivate(target,check){if(process.platform==="win32")return true;try{const st=fs.lstatSync(target);if(st.isSymbolicLink())return false;const uid=process.getuid?.();if(uid!==void 0&&st.uid!==uid)return false;const forbidden=check==="file"?54:18;return(st.mode&forbidden)===0}catch{return false}}function isCacheLocationTrusted(env){const home=twpHomeDir(env);const dir=cacheDir(env);for(const target of[home,dir]){if(fs.existsSync(target)&&!isOursAndPrivate(target,
14
+ "dir"))return false}return true}function readCache(key,options={}){if(options.refresh===true)return null;const env=options.env??process.env;const file=cacheFilePath(key,env);if(!isCacheLocationTrusted(env)||!isOursAndPrivate(file,"file"))return null;let parsed;try{parsed=JSON.parse(fs.readFileSync(file,"utf8"))}catch{return null}if(parsed?.version!==CACHE_VERSION||!parsed.key||!sameKey(parsed.key,key))return null;const fetchedAt=Date.parse(parsed.fetched_at);if(!Number.isFinite(fetchedAt))return null;
15
+ const ttl=options.ttlMs??DEFAULT_TTL_MS;const now=(options.now??Date.now)();if(Math.abs(now-fetchedAt)>ttl)return null;return parsed.value}function writeCache(key,value,options={}){const env=options.env??process.env;const dir=cacheDir(env);const file=cacheFilePath(key,env);const body={version:CACHE_VERSION,key:{profile:key.profile,scope:key.scope,...key.project!==void 0?{project:key.project}:{}},fetched_at:new Date((options.now??Date.now)()).toISOString(),value};if(!isCacheLocationTrusted(env))return;
16
+ const tmp=`${file}.${process.pid}.tmp`;try{fs.mkdirSync(dir,{recursive:true,mode:448});fs.writeFileSync(tmp,`${JSON.stringify(body)}
17
+ `,{mode:384});fs.renameSync(tmp,file)}catch{try{fs.rmSync(tmp,{force:true})}catch{}}}var SELF_REF="me";var PRIVATE_TASKS_PATH="/api/v2/tasks/private";var PRIVATE_MASTERS_CACHE_KEY="__private__";var BACKLOG_SPACES_CACHE_KEY="__backlog__";var BACKLOG_SCOPE_LABEL="\u3053\u306E\u63A5\u7D9A\u5148";var BACKLOG_PROJECT_SCOPE_LABEL="\u3053\u306E Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8";var PRIVATE_SCOPE_LABEL="\u500B\u4EBA\u30BF\u30B9\u30AF";var TENANT_CACHE_KEY="__tenant__";var TENANT_SCOPE_LABEL="\u3053\u306E\u30C6\u30CA\u30F3\u30C8";var ADMIN_USERS_LIST_PATH="/api/v2/admin/users\
18
+ /list";var DEPARTMENTS_PATH="/api/v2/organization/departments";var POSITIONS_PATH="/api/v2/organization/positions";var ORG_MASTER_LIMIT=1e3;var USER_LIST_MAX_PAGES=100;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function str(value){return typeof value==="string"&&value.trim()!==""?value:null}function truthyFlag(value){return value===true||value===1}function rawGetVia(client){return async path2=>{try{return{ok:true,status:200,json:await client.request(
19
+ "GET",path2),error:null}}catch(err){if(err instanceof ApiError){return{ok:false,status:err.status,json:err.body,error:err.message}}throw err}}}var TASK_MASTERS={status:{path:"task-statuses",envelope:"data",scope:"task-statuses",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"},type:{path:"task-types",envelope:"data",scope:"task-types",label:"\u7A2E\u5225"},category:{path:"task-categories",envelope:"data",scope:"task-categories",label:"\u30AB\u30C6\u30B4\u30EA"},milestone:{path:"task-milestones",envelope:"\
20
+ data",scope:"task-milestones",label:"\u30DE\u30A4\u30EB\u30B9\u30C8\u30FC\u30F3"},label:{path:"task-labels",envelope:"items",scope:"task-labels",label:"\u30E9\u30D9\u30EB"}};var Resolver=class{constructor(client,options){this.client=client;this.options=options;this.get=rawGetVia(client)}client;options;get;privateMastersInFlight=null;async project(ref){const trimmed=ref.trim();if(trimmed==="")throw new UsageError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30B3\u30FC\u30C9\u304B ID \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044");
21
+ return resolveProjectRef(trimmed,this.get,safeProjectIdPolicy)}async taskByKey(key){const trimmed=key.trim();if(!isTaskKey(trimmed)){throw new UsageError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u306E\u5F62\u5F0F\u3067\u306F\u3042\u308A\u307E\u305B\u3093: ${key}`,"\u30AD\u30FC\u306F\u300C\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30FC\u30C9-\u756A\u53F7\u300D\u306E\u5F62\u3067\u3059\uFF08\u4F8B: ABC-123\uFF09\u3002")}const res=await this.get(`/api/v2/tasks/resolve-by-key/${encodeURIComponent(trimmed)}`);
22
+ if(res.status===404){throw new ResolveError(`\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${trimmed}\uFF08\u5B58\u5728\u3057\u306A\u3044\u304B\u3001\u95B2\u89A7\u3067\u304D\u308B\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306B\u3042\u308A\u307E\u305B\u3093\uFF09`,404)}if(!res.ok){throw new ResolveError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u3092\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: ${trimmed}\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,
23
+ res.status)}const body=isRecord(res.json)?res.json:{};const projectId=str(body["project_id"]);const task=body["task"];if(projectId===null||!isRecord(task)){throw new ResolveError("\u30BF\u30B9\u30AF\u30AD\u30FC\u89E3\u6C7A\u306E\u5FDC\u7B54\u306B project_id / task \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",res.status)}safeProjectIdPolicy.assertId(projectId);return{projectId,task}}async currentUser(){const res=await this.
24
+ get("/api/v2/user");if(!res.ok){throw new ResolveError(`\u30ED\u30B0\u30A4\u30F3\u4E2D\u306E\u30E6\u30FC\u30B6\u30FC\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}\uFF09\u3002twp login \u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const user=isRecord(res.json)?res.json["user"]:void 0;if(!isRecord(user)||str(user["id"])===null){throw new ResolveError("\u30E6\u30FC\u30B6\u30FC\u53D6\u5F97\u306E\u5FDC\u7B54\u306B user.id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
25
+ res.status)}return{id:user["id"],name:str(user["name"])??user["id"],email:str(user["email"])}}async status(projectId,input){return resolveNamed(this.applyAlias("status",input),await this.statuses(projectId),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"})}async taskType(projectId,input){return resolveNamed(this.applyAlias("type",input),await this.taskTypes(projectId),{flag:"--type",label:"\u7A2E\u5225"})}async assignee(projectId,input,flag="--assignee"){if(input.trim().toLowerCase()===SELF_REF)
26
+ return this.self();const value=this.applyAlias("assignee",input);if(value.trim().toLowerCase()===SELF_REF)return this.self();return resolveNamed(value,await this.members(projectId),{flag,label:"\u30E1\u30F3\u30D0\u30FC"})}async self(){const me=await this.currentUser();return{id:me.id,name:me.name,...me.email!==null?{aliases:[me.email]}:{}}}async defaultStatus(projectId){return requireDefault(await this.statuses(projectId),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9"})}async defaultTaskType(projectId){
27
+ return requireDefault(await this.taskTypes(projectId),{flag:"--type",label:"\u7A2E\u5225"})}async statuses(projectId){return namedFromRows(await this.taskMasterRows("status",projectId),"\u30B9\u30C6\u30FC\u30BF\u30B9",codedMasterRow)}async taskTypes(projectId){return namedFromRows(await this.taskMasterRows("type",projectId),"\u7A2E\u5225",codedMasterRow)}async taskMaster(kind,projectId,input,flag){const spec=TASK_MASTERS[kind];return resolveNamed(input,await this.taskMasterRefs(kind,projectId),{
28
+ flag,label:spec.label})}async taskMasterRefs(kind,projectId){const spec=TASK_MASTERS[kind];return namedFromRows(await this.taskMasterRows(kind,projectId),spec.label,codedMasterRow)}async privateTaskMaster(envelope,input,flag,label){return resolveNamed(input,await this.privateMasters(envelope,label),{flag,label,scope:PRIVATE_SCOPE_LABEL})}async taskMasterRows(kind,projectId){const spec=TASK_MASTERS[kind];return this.cached(spec.scope,projectId,async()=>rawListFrom(await this.get(`/api/v2/projects\
29
+ /${encodeURIComponent(projectId)}/${spec.path}`),spec.envelope,spec.label))}async privateStatuses(){return this.privateMasters("statuses","\u30B9\u30C6\u30FC\u30BF\u30B9")}async privateTaskTypes(){return this.privateMasters("types","\u7A2E\u5225")}async privateStatus(input){return resolveNamed(this.applyAlias("status",input),await this.privateStatuses(),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateTaskType(input){return resolveNamed(this.applyAlias(
30
+ "type",input),await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultStatus(){return requireDefault(await this.privateStatuses(),{flag:"--status",label:"\u30B9\u30C6\u30FC\u30BF\u30B9",scope:PRIVATE_SCOPE_LABEL})}async privateDefaultTaskType(){return requireDefault(await this.privateTaskTypes(),{flag:"--type",label:"\u7A2E\u5225",scope:PRIVATE_SCOPE_LABEL})}async privateTask(ref){const trimmed=ref.trim();const res=await this.get(`${PRIVATE_TASKS_PATH}\
31
+ /${encodeURIComponent(trimmed)}`);if(res.status===404){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${trimmed}`,404)}if(!res.ok){throw new ResolveError(`\u500B\u4EBA\u30BF\u30B9\u30AF\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: ${trimmed}\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}const task=isRecord(
32
+ res.json)?res.json["task"]:void 0;if(!isRecord(task)){throw new ResolveError("\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u5FDC\u7B54\u306B task \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",res.status)}return task}async privateMasters(envelope,label){return namedFromRows(await this.privateMasterRows(envelope,label),label,codedMasterRow)}async privateMasterRows(envelope,label){return this.cached(`private-${envelope}`,PRIVATE_MASTERS_CACHE_KEY,
33
+ async()=>rawListFrom(await this.privateMastersResponse(),envelope,label))}privateMastersResponse(){this.privateMastersInFlight??=this.get(`${PRIVATE_TASKS_PATH}/masters`);return this.privateMastersInFlight}async members(projectId){return this.cached("members",projectId,()=>this.namedList(`/api/v2/projects/${encodeURIComponent(projectId)}/members`,"list","\u30E1\u30F3\u30D0\u30FC",row=>({id:str(row["user_id"]),name:str(row["user_name"]),code:null,aliases:[str(row["alias"]),str(row["user_email"])].
34
+ filter(v=>v!==null)})))}async user(input,flag="<\u30E6\u30FC\u30B6\u30FC>"){const trimmed=input.trim();if(trimmed==="")throw new UsageError(`${flag} \u306B\u7A7A\u306E\u5024\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`);if(trimmed.toLowerCase()===SELF_REF)return this.self();if(UUID_RE.test(trimmed))return{id:trimmed,name:trimmed};const searched=await this.searchUsers(trimmed);if(searched.refs!==null){const needle=trimmed.toLowerCase();const hits=searched.refs.filter(ref=>[ref.id,ref.code,ref.
35
+ name,...ref.aliases??[]].some(key=>typeof key==="string"&&key.trim().toLowerCase()===needle));if(hits.length>0)return resolveNamed(trimmed,hits,{flag,label:"\u30E6\u30FC\u30B6\u30FC",scope:TENANT_SCOPE_LABEL})}try{return await resolveNamed(trimmed,await this.visibleUsers(),{flag,label:"\u30E6\u30FC\u30B6\u30FC",scope:TENANT_SCOPE_LABEL})}catch(err){if(err instanceof UsageError&&searched.failure!==null){throw new UsageError(`${err.message}\uFF08\u30AD\u30FC\u30EF\u30FC\u30C9\u691C\u7D22\u304C ${searched.
36
+ failure} \u3067\u5931\u6557\u3057\u305F\u305F\u3081\u3001\u8868\u793A\u5BFE\u8C61\u306E\u30E6\u30FC\u30B6\u30FC\u3060\u3051\u3067\u7167\u5408\u3057\u307E\u3057\u305F\uFF09`,err.hint)}throw err}}async searchUsers(keyword){const query=new URLSearchParams({keyword,include_hidden:"true",limit:"100"});const res=await this.get(`${ADMIN_USERS_LIST_PATH}?${query.toString()}`);if(!res.ok)return{refs:null,failure:`HTTP ${res.status}`};return{refs:namedFromRows(rawListFrom(res,"items","\u30E6\u30FC\u30B6\u30FC"),
37
+ "\u30E6\u30FC\u30B6\u30FC",userRow),failure:null}}async visibleUsers(){return this.cached("admin-users-visible",TENANT_CACHE_KEY,async()=>{const rows=[];let cursor=null;for(let page=0;;page++){if(page>=USER_LIST_MAX_PAGES){throw new ResolveError(`\u30E6\u30FC\u30B6\u30FC\u4E00\u89A7\u304C ${USER_LIST_MAX_PAGES} \u30DA\u30FC\u30B8\u3092\u8D85\u3048\u305F\u305F\u3081\u3001\u540D\u524D\u3067\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\u3002ID \u304B\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}
38
+ const query=new URLSearchParams({limit:"100"});if(cursor!==null)query.set("cursor",cursor);const res=await this.get(`${ADMIN_USERS_LIST_PATH}?${query.toString()}`);rows.push(...rawListFrom(res,"items","\u30E6\u30FC\u30B6\u30FC"));const body=isRecord(res.json)?res.json:{};if(body["has_more"]===false)break;const next=str(body["next_cursor"]);if(body["has_more"]!==true||next===null){throw new ResolveError("\u30E6\u30FC\u30B6\u30FC\u4E00\u89A7\u306E\u5FDC\u7B54\u306B has_more / next_cursor \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
39
+ res.status)}cursor=next}return namedFromRows(rows,"\u30E6\u30FC\u30B6\u30FC",userRow)})}async department(input,flag="--department"){return resolveNamed(input,await this.departments(),{flag,label:"\u90E8\u7F72",scope:TENANT_SCOPE_LABEL})}async position(input,flag="--position"){return resolveNamed(input,await this.positions(),{flag,label:"\u5F79\u8077",scope:TENANT_SCOPE_LABEL})}async departments(){return this.cached("departments",TENANT_CACHE_KEY,async()=>namedFromRows(masterList(await this.get(`${DEPARTMENTS_PATH}\
40
+ ?limit=${ORG_MASTER_LIMIT}`),"\u90E8\u7F72"),"\u90E8\u7F72",codedMasterRow))}async positions(){return this.cached("positions",TENANT_CACHE_KEY,async()=>namedFromRows(masterList(await this.get(`${POSITIONS_PATH}?limit=${ORG_MASTER_LIMIT}`),"\u5F79\u8077"),"\u5F79\u8077",codedMasterRow))}async namedList(path2,envelope,label,map){return namedListFrom(await this.get(path2),envelope,label,map)}async cached(scope,projectId,load){const key={profile:this.options.profile,scope,project:projectId};const options={
41
+ ...this.options.env!==void 0?{env:this.options.env}:{},refresh:this.options.refresh,...this.options.ttlMs!==void 0?{ttlMs:this.options.ttlMs}:{},...this.options.now!==void 0?{now:this.options.now}:{}};const hit=readCache(key,options);if(hit!==null&&Array.isArray(hit))return hit;const fresh=await load();writeCache(key,fresh,options);return fresh}applyAlias(kind,input){const table=this.options.aliases?.[kind];if(table===void 0)return input;const needle=input.trim().toLowerCase();for(const[from,to]of Object.
42
+ entries(table)){if(from.trim().toLowerCase()===needle&&typeof to==="string"&&to.trim()!=="")return to}return input}async backlogSpaces(){return this.cached("backlog-spaces",BACKLOG_SPACES_CACHE_KEY,()=>this.namedList(`${BACKLOG_BASE_PATH}/spaces`,"spaces","Backlog \u30B9\u30DA\u30FC\u30B9",backlogSpaceRow))}async backlogSpace(ref){return resolveNamed(ref,await this.backlogSpaces(),{flag:"--space",label:"Backlog \u30B9\u30DA\u30FC\u30B9",scope:BACKLOG_SCOPE_LABEL})}async backlogDefaultSpace(){const spaces=await this.
43
+ backlogSpaces();if(spaces.length===1)return spaces[0];if(spaces.length===0){throw new UsageError("Backlog \u30B9\u30DA\u30FC\u30B9\u304C1\u4EF6\u3082\u767B\u9332\u3055\u308C\u3066\u3044\u307E\u305B\u3093","TWP \u306E\u5916\u90E8\u9023\u643A\u8A2D\u5B9A\u3067 Backlog \u30B9\u30DA\u30FC\u30B9\u3092\u767B\u9332\u3057\u3066\u304F\u3060\u3055\u3044\uFF08twp backlog space list \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059\uFF09\u3002")}throw new UsageError(`Backlog \u30B9\u30DA\u30FC\u30B9\u304C ${spaces.
44
+ length} \u4EF6\u767B\u9332\u3055\u308C\u3066\u3044\u308B\u305F\u3081\u3001--space \u30671\u3064\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,`twp backlog space list \u3067 ID \u3068\u30B9\u30DA\u30FC\u30B9URL\u3092\u78BA\u8A8D\u3067\u304D\u307E\u3059\u3002`)}async backlogProjects(spaceId){return this.cached("backlog-projects",spaceId,()=>this.namedList(backlogSpacePath(spaceId,"/projects"),"projects","Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",backlogProjectRow))}async backlogStatuses(spaceId,projectId){
45
+ return this.cached("backlog-statuses",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/statuses`),"statuses","Backlog \u30B9\u30C6\u30FC\u30BF\u30B9",backlogStatusRow))}async backlogUsers(spaceId,projectId){return this.cached("backlog-users",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(
46
+ projectId,"Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8 ID"))}/users`),"users","Backlog \u30E6\u30FC\u30B6\u30FC",backlogUserRow))}get apiClient(){return this.client}};function rawListFrom(res,envelope,label){if(!res.ok){throw new ResolveError(`${label}\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}\uFF09\u3002\u63A5\u7D9A\u5148\u3068\u30ED\u30B0\u30A4\u30F3\u72B6\u614B\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}
47
+ const list=isRecord(res.json)?res.json[envelope]:void 0;if(!Array.isArray(list)){throw new ResolveError(`${label}\u4E00\u89A7\u306E\u5FDC\u7B54\u306B ${envelope} \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return list.map((row,index)=>{if(!isRecord(row)){throw new ResolveError(`${label}\u4E00\u89A7\u306E ${index+1} \u4EF6\u76EE\u304C\u60F3\u5B9A\u306E\u5F62\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,
48
+ res.status)}return row})}function userRow(row){const email=str(row["email"]);const employeeCode=str(row["employee_code"]);return{id:str(row["user_id"]),name:str(row["user_name"]),code:employeeCode??email,aliases:[email,employeeCode].filter(v=>v!==null)}}function masterList(res,label){const rows=rawListFrom(res,"list",label);const count=isRecord(res.json)?res.json["count"]:void 0;if(typeof count==="number"&&count>rows.length){throw new ResolveError(`${label}\u4E00\u89A7\u304C ${count} \u4EF6\u4E2D ${rows.
49
+ length} \u4EF6\u3067\u5207\u308A\u8A70\u3081\u3089\u308C\u305F\u305F\u3081\u3001\u540D\u524D\u3067\u89E3\u6C7A\u3067\u304D\u307E\u305B\u3093\u3002ID \u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,res.status)}return rows}function codedMasterRow(row){return{id:str(row["id"]),name:str(row["name"]),code:str(row["code"]),isDefault:truthyFlag(row["is_default"])}}function namedListFrom(res,envelope,label,map){return namedFromRows(rawListFrom(res,envelope,label),label,map,res.status??void 0)}
50
+ function namedFromRows(rows,label,map,status=200){return rows.map((row,index)=>{const mapped=map(row);if(mapped.id===null||mapped.name===null){throw new ResolveError(`${label}\u4E00\u89A7\u306E ${index+1} \u4EF6\u76EE\u306B id / \u540D\u524D\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`,status)}return{id:mapped.id,name:mapped.name,...mapped.code!==void 0?{code:mapped.code}:{},...mapped.aliases!==void 0&&mapped.aliases.length>
51
+ 0?{aliases:mapped.aliases}:{},...mapped.isDefault!==void 0?{isDefault:mapped.isDefault}:{}}})}function requireDefault(candidates,ctx){const hit=candidates.find(ref=>ref.isDefault===true);if(hit!==void 0)return hit;throw new UsageError(`${ctx.flag} \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${ctx.scope??DEFAULT_LOOKUP_SCOPE}\u306B\u306F\u65E2\u5B9A\u306E${ctx.label}\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF09`,`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${candidates.
52
+ map(ref=>ref.name).join(" / ")}\uFF08\u53E4\u3044\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u6B8B\u3063\u3066\u3044\u308B\u5834\u5408\u306F --refresh \u3067\u53D6\u308A\u76F4\u305B\u307E\u3059\uFF09`)}export{BACKLOG_BASE_PATH,backlogSpacePath,resolveNamed,requireDefaultProject,PRIVATE_TASKS_PATH,BACKLOG_SCOPE_LABEL,BACKLOG_PROJECT_SCOPE_LABEL,DEPARTMENTS_PATH,POSITIONS_PATH,ORG_MASTER_LIMIT,TASK_MASTERS,Resolver};
@@ -0,0 +1,9 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{stringWidth}from"./chunk-WVS4W5FY.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";var OUTPUT_FORMATS=["json","table","text","tsv"];function isOutputFormat(value){return typeof value==="string"&&OUTPUT_FORMATS.includes(value)}function resolveOutputFormat(input){if(input.flag!==void 0){return isOutputFormat(input.flag)?input.flag:null}if(isOutputFormat(input.configured))return input.configured;return input.isTty?"table":"json"}function formatOutput(value,format){switch(format){case"json":return formatJson(value);case"table":return formatTable(value);case"text":return formatDelimited(
4
+ value," ");case"tsv":return formatDelimited(value," ")}}var JSON_UNSAFE_CONTROLS=/[\u007f-\u009f]/gu;function formatJson(value){const text=JSON.stringify(value===void 0?null:value,null,2);return text.replace(JSON_UNSAFE_CONTROLS,ch=>`\\u${ch.codePointAt(0)?.toString(16).padStart(4,"0")??""}`)}function cell(value){if(value===null||value===void 0)return"";if(typeof value==="string")return stripTerminalControls(value);if(typeof value==="number"||typeof value==="boolean"||typeof value==="bigint"){return String(
5
+ value)}return stripTerminalControls(JSON.stringify(value)??"")}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function collectColumns(rows){const columns=[];const seen=new Set;for(const row of rows){for(const key of Object.keys(row)){if(!seen.has(key)){seen.add(key);columns.push(key)}}}return columns}function renderRow(cells,widths){return cells.map((text,i)=>{if(i===cells.length-1)return text;const pad=Math.max(0,(widths[i]??0)-stringWidth(text));
6
+ return text+" ".repeat(pad)}).join(" ").trimEnd()}function singleLine(text){return stripTerminalControls(text).replace(/\t/g,"\\t").replace(/\n/g,"\\n")}function renderGrid(header,rows){const normalizedHeader=header?header.map(singleLine):null;const normalizedRows=rows.map(row=>row.map(singleLine));return renderGridNormalized(normalizedHeader,normalizedRows)}function renderGridNormalized(header,rows){const all=header?[header,...rows]:rows;const columnCount=all.reduce((max,row)=>Math.max(max,row.
7
+ length),0);const widths=[];for(let i=0;i<columnCount;i+=1){widths.push(all.reduce((max,row)=>Math.max(max,stringWidth(row[i]??"")),0))}const lines=[];if(header){lines.push(renderRow(header,widths));lines.push(widths.map(w=>"-".repeat(Math.max(1,w))).join(" ").trimEnd())}for(const row of rows)lines.push(renderRow(row,widths));return lines.join("\n")}function formatTable(value){if(Array.isArray(value)){if(value.length===0)return"";const records=value.filter(isPlainRecord);if(records.length!==value.
8
+ length){return renderGrid(null,value.map(v=>[cell(v)]))}const columns=collectColumns(records);if(columns.length===0)return"";return renderGrid(columns,records.map(row=>columns.map(c=>cell(row[c]))))}if(isPlainRecord(value)){const entries=Object.entries(value);if(entries.length===0)return"";return renderGrid(null,entries.map(([k,v])=>[k,cell(v)]))}return cell(value)}function escapeDelimited(text){return text.replace(/\\/g,"\\\\").replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/\n/g,"\\n")}function formatDelimited(value,separator){
9
+ const rows=[];if(Array.isArray(value)){const records=value.filter(isPlainRecord);if(value.length>0&&records.length===value.length){const columns=collectColumns(records);for(const row of records)rows.push(columns.map(c=>cell(row[c])))}else{for(const v of value)rows.push([cell(v)])}}else if(isPlainRecord(value)){rows.push(Object.values(value).map(cell))}else{rows.push([cell(value)])}return rows.map(row=>row.map(escapeDelimited).join(separator)).join("\n")}export{OUTPUT_FORMATS,isOutputFormat,resolveOutputFormat,formatOutput};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{isModeId,isPermissionModeId}from"./chunk-BOBSH3QN.js";import{API_TOKEN,HELP_TOKEN,isDomainName}from"./chunk-ZGG7TRAM.js";import{splitFlagToken}from"./chunk-QQRJLH6B.js";var BUILTIN_COMMANDS=["login","logout","whoami","update","task-loop"];var TASK_LOOP_ACTIONS=["run","status","stop","schedule","setup","charter"];var VALUE_FLAGS=new Set(["-p","--print","--profile","--tenant","--mode","--permission-mode","--model","--allowed-tools","--disallowed-tools","--project","--engine","--interval","--max-cycles","--ai","--workspace","--ai-config-file","--now","--counts","--gate","--file","--out","--revision","--output","--query"]);var BOOLEAN_FLAGS=new Set(["-h","--help","\
3
+ import{isModeId,isPermissionModeId}from"./chunk-NAUH75MM.js";import{API_TOKEN,HELP_TOKEN,isDomainName}from"./chunk-PEGUHUTD.js";import{splitFlagToken}from"./chunk-QQRJLH6B.js";var BUILTIN_COMMANDS=["login","logout","whoami","update","task-loop"];var TASK_LOOP_ACTIONS=["run","status","stop","schedule","setup","charter"];var VALUE_FLAGS=new Set(["-p","--print","--profile","--tenant","--mode","--permission-mode","--model","--allowed-tools","--disallowed-tools","--project","--engine","--interval","--max-cycles","--ai","--workspace","--ai-config-file","--now","--counts","--gate","--file","--out","--revision","--output","--query"]);var BOOLEAN_FLAGS=new Set(["-h","--help","\
4
4
  -v","--version","--no-tui","--doctor","--password","--token","--no-browser","--safe","--daemon","--force-runner","--force","--drain","--yes","-y","--no-ai-config-file","--verbose","--dry-run","--debug","--refresh"]);function dispatch(argv,limit=2){const tokens=[];const indexes=[];let truncated=false;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg===void 0)continue;if(arg.startsWith("-")&&arg!=="-"){const{name,value:inline}=splitFlagToken(arg);if(BOOLEAN_FLAGS.has(name)){if(inline!==void 0){
5
5
  truncated=true;break}continue}if(VALUE_FLAGS.has(name)){if(inline!==void 0)continue;const next=argv[i+1];if(next!==void 0&&(!next.startsWith("-")||next==="-"))i++;continue}truncated=true;break}if(arg===""||arg==="-")continue;if(tokens.length>=limit)break;tokens.push(arg);indexes.push(i)}return{tokens,indexes,truncated}}function isBuiltin(token){return token!==void 0&&BUILTIN_COMMANDS.includes(token)}function isTaskLoopAction(token){return token!==void 0&&TASK_LOOP_ACTIONS.includes(token)}function resolveRoute(result){
6
6
  const{tokens,indexes}=result;const[first,second]=tokens;const firstIndex=indexes[0];if(first===void 0||firstIndex===void 0)return{kind:"none",consumed:[]};const consumed=[firstIndex];const secondIndex=indexes[1];if(isBuiltin(first)){if(first==="task-loop"&&isTaskLoopAction(second)){if(secondIndex!==void 0)consumed.push(secondIndex);return{kind:"builtin",command:first,action:second,consumed}}return{kind:"builtin",command:first,...first==="task-loop"?{action:"run"}:{},consumed}}if(second!==void 0&&
@@ -21,10 +21,10 @@ inline);if(v!==void 0){out.scheduleNow=v;i+=step}break}case"--counts":{const{val
21
21
  "print"){out.unknown.push("--permission-mode");delete out.permissionMode}if(out.command!=="tui"&&out.command!=="print"){if(out.allowedTools.length>0)out.unknown.push("--allowed-tools");if(out.disallowedTools.length>0)out.unknown.push("--disallowed-tools");out.allowedTools=[];out.disallowedTools=[]}if(out.loginNoBrowser&&!(out.command==="login"&&out.loginMethod==="browser")){out.unknown.push("--no-browser");out.loginNoBrowser=false}if(out.command==="logout"&&out.stopForce){out.logoutForce=true;out.
22
22
  stopForce=false}if(out.command!=="task-loop"){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.stopForce)out.unknown.push("--force");if(out.stopDrain)out.unknown.push("--drain");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles");if(out.project!==void 0)out.unknown.push("--project");if(out.
23
23
  verbose)out.unknown.push("--verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate");if(out.ais!==void 0)out.unknown.push("--ai");if(out.workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file");if(out.charterFile!==void 0)out.unknown.push("--file");if(out.
24
- charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision")}if(out.yes&&out.command!=="task-loop"&&!isDomainRoute)out.unknown.push("--yes");if(!isDomainRoute){if(out.output!==void 0)out.unknown.push("--output");if(out.query!==void 0)out.unknown.push("--query");if(out.dryRun)out.unknown.push("--dry-run");if(out.debug)out.unknown.push("--debug");if(out.refresh)out.unknown.push("--refresh")}if(out.command==="api"&&out.refresh){out.unknown.push("--ref\
25
- resh");out.refresh=false}if(out.command==="task-loop"&&out.taskLoopAction!=="schedule"){if(out.verbose)out.unknown.push("--verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopForce){out.unknown.push("--force")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopDrain){out.unknown.push("--d\
26
- rain")}if(out.command==="task-loop"&&out.taskLoopAction==="stop"&&out.stopForce&&out.stopDrain){out.unknown.push("--force \u3068 --drain \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");out.stopForce=false;out.stopDrain=false}if(out.command==="task-loop"&&out.taskLoopAction!=="setup"){if(out.yes&&out.taskLoopAction!=="charter")out.unknown.push("--yes");if(out.ais!==void 0)out.unknown.push("--ai");if(out.workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==
27
- void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file")}if(out.command==="task-loop"&&(out.taskLoopAction==="stop"||out.taskLoopAction==="status")){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}
28
- if(out.command==="task-loop"&&out.taskLoopAction==="setup"){if(out.engine!==void 0)out.unknown.push("--engine");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="charter"){if(out.charterOp===void 0){out.unknown.push("charter \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\
29
- \u3055\u3044")}if(out.charterOp!=="push"&&out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOp!=="push"&&out.charterRevision!==void 0)out.unknown.push("--revision");if(out.charterOp!=="pull"&&out.charterOut!==void 0)out.unknown.push("--out");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");
30
- if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}else if(out.command==="task-loop"){if(out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision")}return out}export{parseArgv};
24
+ charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision")}if(out.yes&&out.command!=="task-loop"&&!isDomainRoute)out.unknown.push("--yes");const acceptsOutput=isDomainRoute||out.command==="whoami";if(!acceptsOutput){if(out.output!==void 0)out.unknown.push("--output");if(out.query!==void 0)out.unknown.push("--query")}if(!isDomainRoute){if(out.dryRun)out.unknown.push("--dry-run");if(out.debug)out.unknown.push("--debug");if(out.refresh)out.unknown.push(
25
+ "--refresh")}if(out.command==="api"&&out.refresh){out.unknown.push("--refresh");out.refresh=false}if(out.command==="task-loop"&&out.taskLoopAction!=="schedule"){if(out.verbose)out.unknown.push("--verbose");if(out.scheduleNow!==void 0)out.unknown.push("--now");if(out.scheduleCounts!==void 0)out.unknown.push("--counts");if(out.scheduleGate!==void 0)out.unknown.push("--gate")}if(out.command==="task-loop"&&out.taskLoopAction!=="stop"&&out.stopForce){out.unknown.push("--force")}if(out.command==="task\
26
+ -loop"&&out.taskLoopAction!=="stop"&&out.stopDrain){out.unknown.push("--drain")}if(out.command==="task-loop"&&out.taskLoopAction==="stop"&&out.stopForce&&out.stopDrain){out.unknown.push("--force \u3068 --drain \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093");out.stopForce=false;out.stopDrain=false}if(out.command==="task-loop"&&out.taskLoopAction!=="setup"){if(out.yes&&out.taskLoopAction!=="charter")out.unknown.push("--yes");if(out.ais!==void 0)out.unknown.push("--ai");if(out.
27
+ workspace!==void 0)out.unknown.push("--workspace");if(out.aiConfigFile!==void 0)out.unknown.push("--ai-config-file");if(out.noAiConfigFile)out.unknown.push("--no-ai-config-file")}if(out.command==="task-loop"&&(out.taskLoopAction==="stop"||out.taskLoopAction==="status")){if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push(
28
+ "--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="setup"){if(out.engine!==void 0)out.unknown.push("--engine");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--force-runner");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}if(out.command==="task-loop"&&out.taskLoopAction==="charter"){if(out.
29
+ charterOp===void 0){out.unknown.push("charter \u306B\u306F push \u304B pull \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044")}if(out.charterOp!=="push"&&out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOp!=="push"&&out.charterRevision!==void 0)out.unknown.push("--revision");if(out.charterOp!=="pull"&&out.charterOut!==void 0)out.unknown.push("--out");if(out.safe)out.unknown.push("--safe");if(out.daemon)out.unknown.push("--daemon");if(out.forceRunner)out.unknown.push("--for\
30
+ ce-runner");if(out.engine!==void 0)out.unknown.push("--engine");if(out.interval!==void 0)out.unknown.push("--interval");if(out.maxCycles!==void 0)out.unknown.push("--max-cycles")}else if(out.command==="task-loop"){if(out.charterFile!==void 0)out.unknown.push("--file");if(out.charterOut!==void 0)out.unknown.push("--out");if(out.charterRevision!==void 0)out.unknown.push("--revision")}return out}export{parseArgv};
@@ -0,0 +1,10 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ var MODE_IDS=["dev","biz","plan"];function isModeId(value){return value!==void 0&&MODE_IDS.includes(value)}var MODES=[{id:"dev",label:"\u958B\u767A",color:"green",description:"\u30ED\u30FC\u30AB\u30EB\u30C4\u30FC\u30EB\u5168\u90E8 \uFF0B \u958B\u767A\u7CFB TWP \u30C9\u30E1\u30A4\u30F3\u5E38\u99D0",tools:["read_file","write_file","edit_file","bash","shell","glob","grep","git","twp_*"],permissions:{read_file:"allow",glob:"allow",grep:"allow",git:"ask","twp_get_project-task":"allow","twp_list_proje\
4
+ ct-task":"allow",twp_domains:"allow",twp_search_tools:"allow",twp_describe_tools:"allow",twp_mount:"allow","twp_update_project-task":"ask",bash:"ask",shell:"ask",write_file:"ask",edit_file:"ask","*":"ask"}},{id:"biz",label:"\u696D\u52D9",color:"cyan",description:"TWP \u30C9\u30E1\u30A4\u30F3\u4E2D\u5FC3\u3002bash \u3068 write_file \u306F deny",tools:["twp_*","read_file","glob","grep"],permissions:{read_file:"allow",glob:"allow",grep:"allow","twp_get_project-task":"allow","twp_list_project-task":"\
5
+ allow",twp_domains:"allow",twp_search_tools:"allow",twp_describe_tools:"allow",twp_mount:"allow","twp_update_project-task":"ask",bash:"deny",shell:"deny",git:"deny",write_file:"deny",edit_file:"deny","*":"ask"}},{id:"plan",label:"\u30D7\u30E9\u30F3",color:"magenta",description:"\u8AAD\u307F\u53D6\u308A\u306E\u307F\u3002\u5168\u66F8\u304D\u8FBC\u307F deny",tools:["read_file","glob","grep","twp_get_*","twp_list_*","twp_domains","twp_search_tools","twp_describe_tools","twp_mount"],permissions:{read_file:"\
6
+ allow",glob:"allow",grep:"allow","twp_get_project-task":"allow","twp_list_project-task":"allow",twp_domains:"allow",twp_search_tools:"allow",twp_describe_tools:"allow",twp_mount:"allow",bash:"deny",shell:"deny",git:"deny",write_file:"deny",edit_file:"deny","*":"deny"}}];var activeModeList=MODES;var activeModeSources=new Map;function setActiveModes(modes,sources=new Map){activeModeList=MODES.map(builtin=>modes.find(m=>m.id===builtin.id)??builtin);activeModeSources=sources}function modeSource(id){
7
+ return activeModeSources.get(id)??null}function getMode(id){const found=activeModeList.find(m=>m.id===id);if(!found)throw new Error(`unknown mode: ${id}`);return found}function nextMode(id){const i=activeModeList.findIndex(m=>m.id===id);const next=activeModeList[(i+1)%activeModeList.length];return next?next.id:"dev"}function checkPermission(toolName,mode){const own=key=>Object.hasOwn(mode.permissions,key)?mode.permissions[key]:void 0;const found=own(toolName)??own("*");return found==="allow"||found==="ask"||found==="deny"?found:"ask"}var PERMISSION_MODE_IDS=["plan","acceptEdits","denyAll"];function isPermissionModeId(value){return value!==void 0&&PERMISSION_MODE_IDS.includes(value)}function describePermissionMode(permissionMode){if(permissionMode===void 0)return"\u672A\u6307\u5B9A\uFF08\u30E2\u30FC\u30C9\u306E\u65B9\u91DD\u306E\u307E\u307E\uFF09";switch(permissionMode){case"plan":return"plan\uFF08read \u306E\u307F\u8A31\u53EF\u3002write / exec \u306F\u62D2\u5426\uFF09";case"acceptEdits":return"acceptEdits\uFF08write \u306E\u78BA\u8A8D\u3092\u81EA\u52D5\u627F\u8A8D\u3002read\
8
+ / exec \u306F\u30E2\u30FC\u30C9\u306E\u307E\u307E\uFF09";case"denyAll":return"denyAll\uFF08read \u3092\u542B\u3080\u5168\u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09";default:{const exhaustive=permissionMode;return`${String(exhaustive)}\uFF08\u4E0D\u660E\u306A\u5024\u3002\u5B89\u5168\u5074\u3067\u5168\u62D2\u5426\uFF09`}}}function applyPermissionMode(decision,risk,permissionMode){if(permissionMode===void 0)return{decision,reason:null};if(decision==="deny")return{decision,reason:null};switch(permissionMode){case"\
9
+ denyAll":return{decision:"deny",reason:"permission-mode=denyAll\uFF08\u5168\u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09"};case"plan":if(risk==="read")return{decision,reason:null};return{decision:"deny",reason:`permission-mode=plan\uFF08${risk} \u30C4\u30FC\u30EB\u3092\u62D2\u5426\uFF09`};case"acceptEdits":if(risk==="write"&&decision==="ask"){return{decision:"allow",reason:"permission-mode=acceptEdits\uFF08write \u3092\u81EA\u52D5\u627F\u8A8D\uFF09"}}return{decision,reason:null};default:return{decision:"\
10
+ deny",reason:"\u4E0D\u660E\u306A permission-mode\uFF08\u5B89\u5168\u5074\u3067\u62D2\u5426\uFF09"}}}export{isModeId,MODES,setActiveModes,modeSource,getMode,nextMode,checkPermission,isPermissionModeId,describePermissionMode,applyPermissionMode};
@@ -0,0 +1,18 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{readFile}from"fs/promises";import{existsSync}from"fs";import{dirname,join,resolve}from"path";import{fileURLToPath}from"url";var DIR_NAME="command-model";var cachedDir;function commandModelDir(){if(cachedDir!==void 0)return cachedDir;let current=dirname(fileURLToPath(import.meta.url));for(let depth=0;depth<6;depth+=1){const candidate=join(current,DIR_NAME);if(existsSync(join(candidate,"index.json"))){cachedDir=candidate;return cachedDir}if(existsSync(join(current,"package.json")))break;const parent=resolve(
4
+ current,"..");if(parent===current)break;current=parent}cachedDir=null;return cachedDir}var CommandModelMissingError=class extends Error{constructor(detail){super(`\u30B3\u30DE\u30F3\u30C9\u30E2\u30C7\u30EB\uFF08${DIR_NAME}/\uFF09\u3092\u8AAD\u3081\u307E\u305B\u3093: ${detail}
5
+ \u958B\u767A\u6642\u306F \`npm run generate:command-model -- --spec <api.json>\` \u3067\u751F\u6210\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);this.name="CommandModelMissingError"}};var domainCache=new Map;var indexCache=null;var routesCache=null;async function readJson(file){const dir=commandModelDir();if(dir===null)throw new CommandModelMissingError("\u30D1\u30C3\u30B1\u30FC\u30B8\u306B\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u304C\u3042\u308A\u307E\u305B\u3093");const path=join(dir,file);try{return JSON.
6
+ parse(await readFile(path,"utf8"))}catch(cause){throw new CommandModelMissingError(`${path} \u3092\u8AAD\u3081\u307E\u305B\u3093\uFF08${cause.message}\uFF09`)}}async function loadCommandModelIndex(){indexCache??=await readJson("index.json");return indexCache}async function loadCommandModelRoutes(){if(routesCache!==null)return routesCache;const file=await readJson("_routes.json");if(typeof file?.routes!=="object"||file.routes===null||Array.isArray(file.routes)){throw new CommandModelMissingError(
7
+ "_routes.json \u306E\u5F62\u304C\u9055\u3044\u307E\u3059\uFF08routes \u304C\u8AAD\u3081\u307E\u305B\u3093\uFF09")}routesCache=file;return routesCache}async function loadCommandModelDomain(domain){const cached=domainCache.get(domain);if(cached!==void 0)return cached;if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(domain)){throw new CommandModelMissingError(`\u30C9\u30E1\u30A4\u30F3\u540D\u3068\u3057\u3066\u4E0D\u6B63\u3067\u3059: ${domain}`)}const file=await readJson(`${domain}.json`);if(typeof file?.domain!==
8
+ "string"||!Array.isArray(file?.operations)){throw new CommandModelMissingError(`${domain}.json \u306E\u5F62\u304C\u9055\u3044\u307E\u3059\uFF08domain / operations \u304C\u8AAD\u3081\u307E\u305B\u3093\uFF09`)}domainCache.set(domain,file);return file}var MAX_REPORTED_VIOLATIONS=20;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function typesOf(schema){const type=schema["type"];if(typeof type==="string")return[type];if(Array.isArray(type)&&type.every(t=>typeof t==="string"))return type;return null}var INTEGER_STRING=/^[+-]?\d+$/;var BOOLEAN_STRINGS=new Set(["0","1","true","false","yes","no","on","off"]);var NUMBER_STRING=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;function matchesType(type,value){switch(type){case"\
9
+ null":return value===null;case"string":return typeof value==="string";case"integer":return typeof value==="number"&&Number.isInteger(value)||typeof value==="string"&&INTEGER_STRING.test(value);case"number":return typeof value==="number"&&Number.isFinite(value)||typeof value==="string"&&NUMBER_STRING.test(value);case"boolean":return typeof value==="boolean"||value===0||value===1||typeof value==="string"&&BOOLEAN_STRINGS.has(value.toLowerCase());case"array":case"object":return typeof value==="obje\
10
+ ct"&&value!==null;default:return true}}function describe(value){if(value===null)return"null";if(Array.isArray(value))return"\u914D\u5217";if(typeof value==="object")return"\u30AA\u30D6\u30B8\u30A7\u30AF\u30C8";if(typeof value==="string")return`\u6587\u5B57\u5217\uFF08${[...value].length} \u6587\u5B57\uFF09`;return`${typeof value==="number"?"\u6570\u5024":typeof value==="boolean"?"\u771F\u507D\u5024":typeof value} ${String(value)}`}function numericValue(value){if(typeof value==="number")return value;
11
+ if(typeof value==="string"&&NUMBER_STRING.test(value))return Number(value);return null}var PHP_DELIMITED=/^([^A-Za-z0-9\\\s^])[\s\S]*\1[A-Za-z]*$/;function compilePattern(pattern){if(PHP_DELIMITED.test(pattern))return null;try{return new RegExp(pattern,"u")}catch{return null}}function walk(schema,value,at,out){if(!isRecord(schema))return;const types=typesOf(schema);if(types!==null&&!types.some(type=>matchesType(type,value))){out.push(`${at}: ${types.join(" / ")} \u3092\u671F\u5F85\u3057\u307E\u3057\u305F\u304C ${describe(
12
+ value)} \u3067\u3059`);return}if(value===null)return;const enumValues=schema["enum"];if(Array.isArray(enumValues)&&enumValues.length>0){const allowed=enumValues.filter(item=>item!==null).map(item=>String(item));if(!allowed.includes(String(value))){out.push(`${at}: ${allowed.join(" / ")} \u306E\u3044\u305A\u308C\u304B\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\uFF08\u53D7\u3051\u53D6\u3063\u305F\u5024: ${describe(value)}\uFF09`)}}if(typeof value==="string"){const length=[...value].length;
13
+ const max=schema["maxLength"];const min=schema["minLength"];if(typeof max==="number"&&length>max)out.push(`${at}: ${max} \u6587\u5B57\u4EE5\u5185\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${length} \u6587\u5B57\uFF09`);if(typeof min==="number"&&length<min)out.push(`${at}: ${min} \u6587\u5B57\u4EE5\u4E0A\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${length} \u6587\u5B57\uFF09`);const pattern=schema["pattern"];if(typeof pattern==="string"){const re=compilePattern(pattern);if(re!==null&&!re.
14
+ test(value))out.push(`${at}: \u5F62\u5F0F\u304C\u9055\u3044\u307E\u3059\uFF08${pattern}\uFF09`)}}const numeric=types?.some(type=>type==="integer"||type==="number")?numericValue(value):null;if(numeric!==null){const minimum=schema["minimum"];const maximum=schema["maximum"];if(typeof minimum==="number"&&numeric<minimum)out.push(`${at}: ${minimum} \u4EE5\u4E0A\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${numeric}\uFF09`);if(typeof maximum==="number"&&numeric>maximum)out.push(`${at}: ${maximum} \u4EE5\
15
+ \u4E0B\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${numeric}\uFF09`)}if(Array.isArray(value)){const maxItems=schema["maxItems"];const minItems=schema["minItems"];if(typeof maxItems==="number"&&value.length>maxItems)out.push(`${at}: \u8981\u7D20\u306F ${maxItems} \u4EF6\u4EE5\u5185\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${value.length} \u4EF6\uFF09`);if(typeof minItems==="number"&&value.length<minItems)out.push(`${at}: \u8981\u7D20\u306F ${minItems} \u4EF6\u4EE5\u4E0A\u306B\u3057\u3066\u304F\u3060\u3055\u3044\uFF08${value.
16
+ length} \u4EF6\uFF09`);if(isRecord(schema["items"]))value.forEach((item,i)=>walk(schema["items"],item,`${at}[${i}]`,out));return}if(isRecord(value)){const required=schema["required"];if(Array.isArray(required)){for(const key of required){if(typeof key==="string"&&!Object.prototype.hasOwnProperty.call(value,key))out.push(`${at}.${key}: \u5FC5\u9808\u3067\u3059`)}}const properties=schema["properties"];if(isRecord(properties)){for(const[key,child]of Object.entries(properties)){if(Object.prototype.hasOwnProperty.
17
+ call(value,key))walk(child,value[key],`${at}.${key}`,out)}}}}function validateBody(schema,body){const out=[];walk(schema,body,"body",out);return out}function validateQuery(params,query){const out=[];for(const param of params){const has=Object.prototype.hasOwnProperty.call(query,param.name)&&query[param.name]!==void 0;if(!has){if(param.required)out.push(`query.${param.name}: \u5FC5\u9808\u3067\u3059`);continue}if(param.source!=="spec")continue;const declared=param.type;const types=typeof declared===
18
+ "string"?[declared]:Array.isArray(declared)?declared.filter(t=>typeof t==="string"):[];const checked=types.filter(type=>type==="integer"||type==="number"||type==="boolean");if(checked.length===0||types.includes("string"))continue;const raw=query[param.name];if(types.includes("null")&&raw==="")continue;if(!checked.some(type=>matchesType(type,raw))){out.push(`query.${param.name}: ${checked.join(" / ")} \u3092\u671F\u5F85\u3057\u307E\u3057\u305F\u304C ${describe(raw)} \u3067\u3059`)}}return out}export{CommandModelMissingError,loadCommandModelIndex,loadCommandModelRoutes,loadCommandModelDomain,MAX_REPORTED_VIOLATIONS,validateBody,validateQuery};
@@ -0,0 +1,3 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ var DOMAIN_NAMES=["backlog","project","task","user"];function isDomainName(value){return value!==void 0&&DOMAIN_NAMES.includes(value)}var HELP_TOKEN="help";var API_TOKEN="api";export{isDomainName,HELP_TOKEN,API_TOKEN};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{createRuntime}from"./chunk-FOFV2MNL.js";import{findExecutable}from"./chunk-PMOUHEJQ.js";import{describeAutoUpdate}from"./chunk-ILKQDXI5.js";import{PACKAGE_NAME,UPDATE_COMMAND,compareVersionCores,isBelowMinSupported,parseVersionCore}from"./chunk-DXXFUNYN.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{execFile}from"child_process";import fs from"fs";import path from"path";function resolveNpmCommand(deps={}){const platform=deps.platform??process.platform;const env=deps.env??process.env;const npmPath=(deps.find??(name=>findExecutable(name,{env,platform})))("npm");if(npmPath===null)return null;if(platform!=="win32")return{file:npmPath,prefix:[]};if(/\.exe$/i.test(npmPath))return{file:npmPath,prefix:[]};const cliJs=path.win32.join(path.win32.dirname(npmPath),"node_modules","npm","bin","npm-cli.js");return(deps.exists??fs.existsSync)(cliJs)?{file:deps.nodePath??process.
3
+ import{createRuntime}from"./chunk-WOUKWOAR.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{findExecutable}from"./chunk-PMOUHEJQ.js";import{describeAutoUpdate}from"./chunk-DSDVIU6A.js";import{PACKAGE_NAME,UPDATE_COMMAND,compareVersionCores,isBelowMinSupported,parseVersionCore}from"./chunk-DXXFUNYN.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import{execFile}from"child_process";import fs from"fs";import path from"path";function resolveNpmCommand(deps={}){const platform=deps.platform??process.platform;const env=deps.env??process.env;const npmPath=(deps.find??(name=>findExecutable(name,{env,platform})))("npm");if(npmPath===null)return null;if(platform!=="win32")return{file:npmPath,prefix:[]};if(/\.exe$/i.test(npmPath))return{file:npmPath,prefix:[]};const cliJs=path.win32.join(path.win32.dirname(npmPath),"node_modules","npm","bin","npm-cli.js");return(deps.exists??fs.existsSync)(cliJs)?{file:deps.nodePath??process.
4
4
  execPath,prefix:[cliJs]}:null}var DEFAULT_REGISTRY="https://registry.npmjs.org";function registryBase(env=process.env){const configured=env["npm_config_registry"]?.trim();if(configured===void 0||configured==="")return DEFAULT_REGISTRY;try{const url=new URL(configured);if(url.protocol!=="https:"&&url.protocol!=="http:")return DEFAULT_REGISTRY}catch{return DEFAULT_REGISTRY}return configured.replace(/\/+$/,"")}async function fetchFromRegistry(fetchImpl=httpFetch,env=process.env){const url=`${registryBase(env)}/${PACKAGE_NAME.replace(
5
5
  "/","%2f")}`;const res=await fetchImpl(url,{headers:{Accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(5e3)});if(!res.ok){throw new Error(`registry \u304C ${res.status} \u3092\u8FD4\u3057\u307E\u3057\u305F`)}const body=await res.json();const latest=body["dist-tags"]?.latest;if(typeof latest!=="string"||parseVersionCore(latest)===null){throw new Error("registry \u306E\u5FDC\u7B54\u306B dist-tags.latest \u304C\u3042\u308A\u307E\u305B\u3093")}return{version:latest.trim(),source:"\
6
6
  registry"}}async function fetchFromNpmCli(){const npm=resolveNpmCommand();if(npm===null){throw new Error("npm \u304C PATH \u306B\u898B\u3064\u304B\u308A\u307E\u305B\u3093")}const stdout=await new Promise((resolve,reject)=>{execFile(npm.file,[...npm.prefix,"view",PACKAGE_NAME,"version","--json"],{timeout:15e3,windowsHide:true},(error,out)=>error?reject(error):resolve(out))});const parsed=JSON.parse(stdout.trim());const latest=typeof parsed==="string"?parsed:null;if(latest===null||parseVersionCore(
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{AuthSession,loadCredentials,withFileLock}from"./chunk-XNLIEUAW.js";import{parseVersionCore}from"./chunk-DXXFUNYN.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{effectiveApiUrl,effectiveRelayUrl,resolveConfiguredModel,resolveProfile}from"./chunk-NERYSBA4.js";import{ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";var MAX_EVENT_BYTES=8*1024*1024;var SseBufferOverflowError=class extends Error{constructor(limit){super(`SSE \u306E\u30A4\u30D9\u30F3\u30C8\u5883\u754C\uFF08\u7A7A\u884C\uFF09\u304C ${limit} \u30D0\u30A4\u30C8\u4EE5\u5185\u306B\u73FE\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u4E0A\u6D41\u306E\u5FDC\u7B54\u304C\u58CA\u308C\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002`)}};var SseParser=class{constructor(maxEventBytes=MAX_EVENT_BYTES){this.maxEventBytes=maxEventBytes}maxEventBytes;buffer="";pendingCr=false;push(chunk){
3
+ import{AuthSession,loadCredentials,withFileLock}from"./chunk-XNLIEUAW.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{parseVersionCore}from"./chunk-DXXFUNYN.js";import{effectiveApiUrl,effectiveRelayUrl,resolveConfiguredModel,resolveProfile}from"./chunk-NERYSBA4.js";import{ensureTwpHome,twpHomeDir}from"./chunk-RZVI6PMW.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";var MAX_EVENT_BYTES=8*1024*1024;var SseBufferOverflowError=class extends Error{constructor(limit){super(`SSE \u306E\u30A4\u30D9\u30F3\u30C8\u5883\u754C\uFF08\u7A7A\u884C\uFF09\u304C ${limit} \u30D0\u30A4\u30C8\u4EE5\u5185\u306B\u73FE\u308C\u307E\u305B\u3093\u3067\u3057\u305F\u3002\u4E0A\u6D41\u306E\u5FDC\u7B54\u304C\u58CA\u308C\u3066\u3044\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002`)}};var SseParser=class{constructor(maxEventBytes=MAX_EVENT_BYTES){this.maxEventBytes=maxEventBytes}maxEventBytes;buffer="";pendingCr=false;push(chunk){
4
4
  let pending=this.pendingCr?`\r${chunk}`:chunk;this.pendingCr=pending.endsWith("\r");if(this.pendingCr)pending=pending.slice(0,-1);this.buffer+=pending.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(this.buffer.length>this.maxEventBytes){this.buffer="";this.pendingCr=false;throw new SseBufferOverflowError(this.maxEventBytes)}const events=[];for(;;){const boundary=this.buffer.indexOf("\n\n");if(boundary===-1)break;const block=this.buffer.slice(0,boundary);this.buffer=this.buffer.slice(boundary+2);const parsed=parseBlock(
5
5
  block);if(parsed)events.push(parsed)}return events}flush(){const rest=(this.pendingCr?`${this.buffer}
6
6
  `:this.buffer).trim();this.buffer="";this.pendingCr=false;if(rest==="")return[];const parsed=parseBlock(rest);return parsed?[parsed]:[]}};function parseBlock(block){let event="message";const data=[];for(const line of block.split("\n")){if(line.startsWith(":"))continue;const colon=line.indexOf(":");const field=colon===-1?line:line.slice(0,colon);let value=colon===-1?"":line.slice(colon+1);if(value.startsWith(" "))value=value.slice(1);if(field==="event")event=value;else if(field==="data")data.push(
@@ -38,4 +38,4 @@ break;const orphanResult=hasToolResult(head2)&&this.messages.length>1;if(head2.r
38
38
  const freed=before-lengthOf(head);this.lastPromptTokens=Math.max(0,this.lastPromptTokens-Math.ceil(freed/4));this.pendingChars=Math.max(0,this.pendingChars-freed);dropped+=1}this.droppedMessages+=dropped;return dropped}estimatedPromptTokens(){if(this.lastPromptTokens===0){return Math.ceil(this.totalChars()/4)}return this.lastPromptTokens+Math.ceil(this.pendingChars/4)}snapshot(){const used=this.estimatedPromptTokens();const remaining=Math.round((this.contextWindowTokens-used)/this.contextWindowTokens*
39
39
  100);return{totals:{...this.totals},turns:this.turns,lastPromptTokens:this.lastPromptTokens,remainingPercent:Math.max(0,Math.min(100,remaining)),droppedMessages:this.droppedMessages}}totalChars(){return this.messages.reduce((sum,m)=>sum+lengthOf(m),0)}};function lengthOf(message){return message.content.reduce((sum,block)=>sum+blockLength(block),0)}function copyBlock(block){return block.type==="tool_use"?{...block,input:{...block.input}}:{...block}}function hasToolResult(message){return message.content.
40
40
  some(block=>block.type==="tool_result")}function createRuntime(opts){const env=opts.env??process.env;const cwd=opts.cwd??process.cwd();const profile=resolveProfile(opts.profile,env,cwd);const creds=loadCredentials(profile.name,env);const apiUrl=effectiveApiUrl(profile,creds?.api_url,env);const relayUrl=effectiveRelayUrl(profile,creds?.relay_url,env);const session=new AuthSession(profile.name,apiUrl,env);const client=new RelayClient(relayUrl,session,httpFetch,opts.cliVersion);const configured=resolveConfiguredModel(opts.model,profile.name,
41
- env,cwd);return{profileName:profile.name,apiUrl,relayUrl,client,context:new ContextManager,loggedIn:creds!==null,configuredModel:configured?.model??null,loadCatalog:()=>loadCatalog(client,profile.name,relayUrl,env),loadCachedFloor:()=>loadCachedVersionFloor(profile.name,relayUrl,env)}}export{modelLabel,toModelInfos,emptyUsage,RelayError,DEFAULT_MAX_TOKENS,builtinCatalog,loadCachedCatalog,pickModel,createRuntime};
41
+ env,cwd);return{profileName:profile.name,apiUrl,relayUrl,client,session,context:new ContextManager,loggedIn:creds!==null,configuredModel:configured?.model??null,loadCatalog:()=>loadCatalog(client,profile.name,relayUrl,env),loadCachedFloor:()=>loadCachedVersionFloor(profile.name,relayUrl,env)}}export{modelLabel,toModelInfos,emptyUsage,RelayError,DEFAULT_MAX_TOKENS,builtinCatalog,loadCachedCatalog,pickModel,createRuntime};