@tocca-systems/twp-cli 0.23.0 → 0.25.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 (71) hide show
  1. package/CHANGELOG.public.md +14 -0
  2. package/README.md +240 -6
  3. package/command-model/department.json +1 -1
  4. package/dist/agent-loop-ZP47LTUE.js +75 -0
  5. package/dist/{api-command-CLARDKAL.js → api-command-VWJXBUCJ.js} +3 -3
  6. package/dist/{app-X3IKIAKB.js → app-3JIU5OUX.js} +49 -48
  7. package/dist/attendance-42XLURM7.js +21 -0
  8. package/dist/{auto-update-FBZGOQFI.js → auto-update-CV2MM32C.js} +1 -1
  9. package/dist/{auto-update-worker-SI7TVSCN.js → auto-update-worker-OBFGN6FY.js} +2 -2
  10. package/dist/{backlog-X2MQTA6F.js → backlog-KSMQIC2R.js} +2 -2
  11. package/dist/charter-command-ULFOEZWE.js +26 -0
  12. package/dist/{chunk-APYYF7H6.js → chunk-5Q2CH4E7.js} +1 -1
  13. package/dist/{chunk-M3GWY6NT.js → chunk-7WSNIXTQ.js} +2 -1
  14. package/dist/chunk-BKZGBJWT.js +15 -0
  15. package/dist/chunk-DDKZ5IPT.js +11 -0
  16. package/dist/chunk-FTYJZFEK.js +10 -0
  17. package/dist/{chunk-2VISRLWS.js → chunk-G4OO4M44.js} +9 -9
  18. package/dist/{chunk-E4H22AO5.js → chunk-GDM2QUBL.js} +1 -1
  19. package/dist/{chunk-X4RS5VBH.js → chunk-GMBJTG6A.js} +1 -1
  20. package/dist/{chunk-QVXZEUKN.js → chunk-HGTG5XQ7.js} +1 -1
  21. package/dist/{chunk-DSDVIU6A.js → chunk-ILKQDXI5.js} +1 -1
  22. package/dist/{chunk-O52CUEDO.js → chunk-IOGVQVGD.js} +1 -1
  23. package/dist/chunk-IRAZ27WL.js +38 -0
  24. package/dist/{chunk-7PRQ7JW2.js → chunk-KEP5QSS4.js} +40 -15
  25. package/dist/chunk-KUIFIN7P.js +57 -0
  26. package/dist/{chunk-JB27KNCX.js → chunk-NIAOX77K.js} +29 -25
  27. package/dist/chunk-P4AEFKLM.js +13 -0
  28. package/dist/{chunk-SJRK4AVE.js → chunk-PK6CUUAQ.js} +1 -1
  29. package/dist/chunk-SP27PYHC.js +3 -0
  30. package/dist/chunk-UDPJ2IGK.js +7 -0
  31. package/dist/chunk-VCZVITWG.js +13 -0
  32. package/dist/{chunk-XLE4HW6B.js → chunk-VGMWPPGD.js} +12 -10
  33. package/dist/{chunk-UG2I6VRD.js → chunk-VYDEUFGU.js} +1 -1
  34. package/dist/{chunk-Y2QAP6SU.js → chunk-WQ66EYZS.js} +1 -1
  35. package/dist/chunk-X45SJNT2.js +62 -0
  36. package/dist/{chunk-EQWW2F5V.js → chunk-YVAN3H5W.js} +4 -4
  37. package/dist/chunk-YWGYRISN.js +34 -0
  38. package/dist/{chunk-WOUKWOAR.js → chunk-Z2MNO3FT.js} +10 -9
  39. package/dist/chunk-ZN5EFDH7.js +5 -0
  40. package/dist/chunk-ZWVYVS2A.js +4 -0
  41. package/dist/cli.js +100 -8
  42. package/dist/{commands-BE67IDNQ.js → commands-OFLBUP6O.js} +8 -8
  43. package/dist/{commands-JNG5TZ77.js → commands-RG7M6E5K.js} +79 -84
  44. package/dist/department-GH475WCF.js +33 -0
  45. package/dist/job-title-FC2GWDE7.js +8 -0
  46. package/dist/{logout-guard-CMZZBRUL.js → logout-guard-3PB3VMGP.js} +1 -1
  47. package/dist/media-TD7D4TXF.js +64 -0
  48. package/dist/{oneshot-NA756EBO.js → oneshot-QQOOZZDT.js} +5 -5
  49. package/dist/position-4RHTV3IK.js +8 -0
  50. package/dist/{project-2LJZW747.js → project-DBNWB47J.js} +1 -1
  51. package/dist/query-EEALMOSO.js +3 -0
  52. package/dist/{render-ICZOK3HV.js → render-K45EOLHX.js} +1 -1
  53. package/dist/{run-XCAJDHFU.js → run-VNHAQO24.js} +2 -2
  54. package/dist/{schedule-command-GKXKNMLG.js → schedule-command-FJU7JFNR.js} +1 -1
  55. package/dist/{server-settings-CG3EM7R7.js → server-settings-YL6KALXG.js} +1 -1
  56. package/dist/{setup-UI6V2Q3V.js → setup-BJKIHANC.js} +1 -1
  57. package/dist/skill-command-V26WGVXU.js +61 -0
  58. package/dist/storage-ANKKJJJO.js +3 -0
  59. package/dist/{task-GKNM3G4K.js → task-7VOYCG26.js} +7 -63
  60. package/dist/{update-TVVBJNN7.js → update-RLKK6N7U.js} +1 -1
  61. package/dist/user-UU2SLVC4.js +336 -0
  62. package/package.json +1 -1
  63. package/dist/charter-command-UPKTVL7H.js +0 -36
  64. package/dist/chunk-7LTTKKQA.js +0 -56
  65. package/dist/chunk-GFC2ASHE.js +0 -6
  66. package/dist/chunk-JKSXUBND.js +0 -9
  67. package/dist/chunk-LD3AKGH6.js +0 -30
  68. package/dist/chunk-ODLJ2LNQ.js +0 -13
  69. package/dist/chunk-PEGUHUTD.js +0 -3
  70. package/dist/query-NJMVSQR6.js +0 -3
  71. package/dist/user-EU7Z3DAO.js +0 -24
@@ -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{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(
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(
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";
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
3
- import{splitFlagToken}from"./chunk-QQRJLH6B.js";import{UsageError}from"./chunk-M3GWY6NT.js";function parseOperationArgs(argv,specs){const byName=new Map(specs.map(spec=>[spec.name,spec]));const args=[];const flags=new Map;const repeated=new Map;let positionalOnly=false;for(let i=0;i<argv.length;i+=1){const arg=argv[i];if(arg===void 0)continue;if(!positionalOnly&&arg==="--"){positionalOnly=true;continue}if(positionalOnly||!arg.startsWith("-")||arg==="-"){args.push(arg);continue}const{name,value:inline}=splitFlagToken(arg);const spec=byName.get(name);if(spec===void 0){const shortEquals=!arg.
3
+ import{splitFlagToken}from"./chunk-QQRJLH6B.js";import{UsageError}from"./chunk-7WSNIXTQ.js";function parseOperationArgs(argv,specs){const byName=new Map(specs.map(spec=>[spec.name,spec]));const args=[];const flags=new Map;const repeated=new Map;let positionalOnly=false;for(let i=0;i<argv.length;i+=1){const arg=argv[i];if(arg===void 0)continue;if(!positionalOnly&&arg==="--"){positionalOnly=true;continue}if(positionalOnly||!arg.startsWith("-")||arg==="-"){args.push(arg);continue}const{name,value:inline}=splitFlagToken(arg);const spec=byName.get(name);if(spec===void 0){const shortEquals=!arg.
4
4
  startsWith("--")&&arg.includes("=");throw new UsageError(`\u4E0D\u660E\u306A\u30AA\u30D7\u30B7\u30E7\u30F3: ${arg}`,shortEquals?`\u77ED\u3044\u30D5\u30E9\u30B0\u306B = \u306F\u4F7F\u3048\u307E\u305B\u3093\u3002\u7A7A\u767D\u3067\u533A\u5207\u3063\u3066\u304F\u3060\u3055\u3044: ${arg.replace("="," ")}`:void 0)}if(spec.repeatable!==true&&flags.has(name)){throw new UsageError(`${name} \u304C\u8907\u6570\u56DE\u6307\u5B9A\u3055\u308C\u3066\u3044\u307E\u3059`)}if(!spec.takesValue){if(inline!==void 0){
5
5
  throw new UsageError(`${name} \u306F\u5024\u3092\u53D6\u308A\u307E\u305B\u3093`,`${name} \u306F\u6307\u5B9A\u306E\u6709\u7121\u3060\u3051\u304C\u610F\u5473\u3092\u6301\u3061\u307E\u3059\u3002`)}flags.set(name,"");continue}if(inline!==void 0){addValue(flags,repeated,spec,name,inline);continue}const next=argv[i+1];if(next===void 0||next.startsWith("-")&&next!=="-"){throw new UsageError(`${name} \u306B\u306F\u5024\u304C\u5FC5\u8981\u3067\u3059`,`\`-\` \u3067\u59CB\u307E\u308B\u5024\u306F ${name}=\u5024 \
6
6
  \u306E\u5F62\u3067\u6E21\u305B\u307E\u3059\u3002`)}addValue(flags,repeated,spec,name,next);i+=1}return repeated.size>0?{args,flags,repeated}:{args,flags}}function addValue(flags,repeated,spec,name,value){if(spec.repeatable!==true){flags.set(name,value);return}const bucket=repeated.get(name);if(bucket===void 0)repeated.set(name,[value]);else bucket.push(value)}function repeatedValues(input,name){return input.repeated?.get(name)??[]}export{parseOperationArgs,repeatedValues};
@@ -0,0 +1,38 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{booleanText,boundedText,isoDate}from"./chunk-UDPJ2IGK.js";import{nonEmpty,positiveInteger}from"./chunk-G4OO4M44.js";import{ORG_MASTER_LIMIT}from"./chunk-NIAOX77K.js";import{ULID_RE,UUID_RE,isSafePathSegment}from"./chunk-GMBJTG6A.js";import{requireResolved,singleRef,withResolved}from"./chunk-ZN5EFDH7.js";import{acknowledgement,isRecord,pick}from"./chunk-ZWVYVS2A.js";import{ApiResponseError,UsageError}from"./chunk-7WSNIXTQ.js";var CLEAR_DATE="none";function placeholderOf(field){switch(field.kind){case"text":return`<${field.label}>`;case"integer":return"<\u6574\u6570>";case"boolean":return"<true|false>";case"enum":return`<${field.values.join("|")}>`;case"date":return`<YYYY-MM-DD|${CLEAR_DATE}>`;case"ref":return field.placeholder}}function createFlags(fields){return fields.map(field=>({name:field.flag,summary:field.summary,takesValue:true,placeholder:placeholderOf(field)}))}function updateFlags(fields){const flags=[];for(const field of fields){
4
+ flags.push({name:field.flag,summary:field.summary,takesValue:true,placeholder:placeholderOf(field)});if(field.kind==="ref")flags.push({name:field.clearFlag,summary:field.clearSummary,takesValue:false})}return flags}function integerValue(field,raw){const trimmed=raw.trim();const value=/^\d+$/.test(trimmed)?Number(trimmed):Number.NaN;const tooLarge=field.max!==void 0&&value>field.max;if(!Number.isSafeInteger(value)||value<field.min||tooLarge){const range=field.max!==void 0?`${field.min} \u4EE5\u4E0A ${field.
5
+ max} \u4EE5\u4E0B`:`${field.min} \u4EE5\u4E0A`;throw new UsageError(`${field.flag} \u306F ${range}\u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044: ${raw}`,`${field.label}\u3092\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return value}function fieldBody(input,fields){const body={};for(const field of fields){switch(field.kind){case"text":{const value=boundedText(input,field.flag,{maxChars:field.maxChars,label:field.label});if(value!==void 0)body[field.
6
+ key]=value;break}case"integer":{const raw=input.flags.get(field.flag);if(raw!==void 0)body[field.key]=integerValue(field,raw);break}case"boolean":{const raw=input.flags.get(field.flag);if(raw!==void 0)body[field.key]=booleanText(field.flag,raw);break}case"enum":{const raw=input.flags.get(field.flag);if(raw===void 0)break;const value=raw.trim().toLowerCase();if(!field.values.includes(value)){throw new UsageError(`${field.flag} \u306B\u300C${raw}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,
7
+ `\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${field.values.join(" / ")} \u3067\u3059\u3002`)}body[field.key]=value;break}case"date":{const raw=input.flags.get(field.flag);if(raw===void 0)break;body[field.key]=raw.trim().toLowerCase()===CLEAR_DATE?null:isoDate(input,field.flag);break}case"ref":{nonEmpty(input.flags,field.flag);if(input.flags.has(field.flag)&&input.flags.has(field.clearFlag)){throw new UsageError(`${field.flag} \u3068 ${field.clearFlag} \u306F\u540C\u6642\u306B\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,
8
+ "\u3069\u3061\u3089\u304B\u4E00\u65B9\u3060\u3051\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}if(input.flags.has(field.clearFlag))body[field.key]=null;const resolved=input.resolved?.[field.key];if(input.flags.has(field.flag)&&resolved!==void 0)body[field.key]=resolved;break}}}return body}function booleanQuery(flag,raw){return String(booleanText(flag,raw))}function hasAnyField(input,fields){return fields.some(field=>input.flags.has(field.flag)||field.kind==="ref"&&input.flags.has(
9
+ field.clearFlag))}async function resolveRefFields(input,ctx,fields){const resolved={};for(const field of fields){if(field.kind!=="ref")continue;const raw=nonEmpty(input.flags,field.flag);if(raw!==void 0)resolved[field.key]=(await field.resolve(ctx,raw,field.flag)).id}return withResolved(input,resolved)}async function targetId(input,options){const ref=singleRef(input,{flag:options.flag,label:options.label,usage:options.usage});if(ULID_RE.test(ref.toUpperCase()))return ref.toUpperCase();if(UUID_RE.
10
+ test(ref))return ref;return(await options.resolve(ref)).id}function idSegment(input,label){const id=requireResolved(input,"id");if(!isSafePathSegment(id)){throw new ApiResponseError(`\u30B5\u30FC\u30D0\u304C\u8FD4\u3057\u305F${label} ID \u3092\u30D1\u30B9\u306B\u4F7F\u3048\u307E\u305B\u3093: ${id}\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return encodeURIComponent(id)}function masterRows(body,label){const list=isRecord(body)?body["list"]:void 0;if(!Array.
11
+ isArray(list)){throw new ApiResponseError(`${label}\u4E00\u89A7\u306E\u5FDC\u7B54\u306B list \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return list}function truncationNotes(body,label){const rows=masterRows(body,label);const count=isRecord(body)?body["count"]:void 0;if(typeof count!=="number"||count<=rows.length)return[];return[`${label}\u306F ${count} \u4EF6\u3042\u308A\u307E\u3059\u304C\u3001${rows.length}\
12
+ \u4EF6\u3060\u3051\u3092\u8868\u793A\u3057\u3066\u3044\u307E\u3059\u3002--limit \u3092\u5897\u3084\u3057\u3066\u304F\u3060\u3055\u3044\u3002`]}function masterItem(body,itemKey,label){const item=isRecord(body)?body[itemKey]:void 0;if(!isRecord(body)||body["result"]!==true||!isRecord(item)||typeof item["id"]!=="string"){throw new ApiResponseError(`${label}\u306E\u5FDC\u7B54\u306B ${itemKey} \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}
13
+ return item}function cacheNote(label){return`${label}\u4E00\u89A7\u306F10\u5206\u30AD\u30E3\u30C3\u30B7\u30E5\u3057\u307E\u3059\u3002\u3053\u306E\u76F4\u5F8C\u306B\u540D\u524D\u3084\u30B3\u30FC\u30C9\u3067\u6307\u5B9A\u3059\u308B\u3068\u304D\u306F --refresh \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\uFF08ID \u306A\u3089\u305D\u306E\u307E\u307E\u901A\u308A\u307E\u3059\uFF09\u3002`}function referencedDeleteGuidance(guidance){return server=>server.includes("\u524A\u9664\u3067\u304D\u307E\u305B\u3093")&&
14
+ !server.includes("\u4E88\u7D04")?guidance:void 0}function codeNameFields(label){return[{kind:"text",flag:"--code",key:"code",label:`${label}\u30B3\u30FC\u30C9`,maxChars:50,summary:`${label}\u30B3\u30FC\u30C9\uFF08\u30C6\u30CA\u30F3\u30C8\u5185\u3067\u4E00\u610F\uFF09`},{kind:"text",flag:"--name",key:"name",label:`${label}\u540D`,maxChars:255,summary:`${label}\u540D`}]}function masterFields(label,rest){return[...codeNameFields(label),...rest]}var STATUS_VALUES=["active","inactive"];function masterListOperation(options){
15
+ const{name,label}=options;const filters=options.filters??[];return{name:"list",summary:`${label}\u3092\u4E00\u89A7\u3059\u308B`,usage:`twp ${name} list [--status active|inactive] [--keyword <\u8A9E>]${filters.map(f=>` [${f.flag.name} ${f.flag.placeholder??""}]`).join("")} [--limit <\u4EF6\u6570>]`,description:(options.note!==void 0?`${options.note}
16
+ `:"")+`--keyword \u306F\u30B3\u30FC\u30C9\u3068\u540D\u524D\u306E\u90E8\u5206\u4E00\u81F4\u3067\u3059\u3002
17
+ \u3053\u306E API \u306F\u30DA\u30FC\u30B8\u30F3\u30B0\u3092\u6301\u305F\u305A\u3001--limit \u4EF6\uFF08\u65E2\u5B9A ${ORG_MASTER_LIMIT}\uFF09\u3067\u6253\u3061\u5207\u308A\u307E\u3059\u3002\u6253\u3061\u5207\u3063\u305F\u3068\u304D\u306F stderr \u3067\u77E5\u3089\u305B\u307E\u3059\u3002
18
+
19
+ --output json \u306F API \u304C\u8FD4\u3059\u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u51FA\u3057\u307E\u3059\u3002
20
+ --output table / text / tsv \u306F\u8981\u7D04\u5217\uFF08${options.columns.join(" / ")}\uFF09\u3067\u3059\u3002`,flags:[{name:"--status",summary:"\u72B6\u614B\u3067\u7D5E\u308A\u8FBC\u3080\uFF08active / inactive\uFF09",takesValue:true,placeholder:"<active|inactive>"},{name:"--keyword",summary:"\u30B3\u30FC\u30C9\u30FB\u540D\u524D\u306E\u90E8\u5206\u4E00\u81F4\u3067\u7D5E\u308A\u8FBC\u3080",takesValue:true,placeholder:"<\u8A9E>"},...filters.map(f=>f.flag),{name:"--limit",summary:`\u53D6\u5F97\u3059\u308B\u4EF6\u6570\u306E\u4E0A\u9650\uFF08\u65E2\u5B9A ${ORG_MASTER_LIMIT}\
21
+ \uFF09`,takesValue:true,placeholder:"<\u4EF6\u6570>"}],plan(input){if(input.args.length>0){throw new UsageError(`list \u306F\u4F4D\u7F6E\u5F15\u6570\u3092\u53D6\u308A\u307E\u305B\u3093: ${input.args.join(" ")}`,`twp ${name} list help`)}const raw=nonEmpty(input.flags,"--status");const status=raw?.trim().toLowerCase();if(status!==void 0&&!STATUS_VALUES.includes(status)){throw new UsageError(`--status \u306B\u300C${raw}\u300D\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u6307\u5B9A\u3067\u304D\u308B\u306E\u306F ${STATUS_VALUES.
22
+ join(" / ")} \u3067\u3059\u3002`)}const query={status,keyword:nonEmpty(input.flags,"--keyword"),limit:positiveInteger(input.flags,"--limit")??ORG_MASTER_LIMIT};for(const filter of filters){const value=input.flags.get(filter.flag.name);if(value!==void 0)query[filter.query]=filter.value(value)}return{method:"GET",path:options.path,query}},summarize:body=>masterRows(body,label).map(row=>pick(row,options.columns)),raw:body=>masterRows(body,label),notes:body=>truncationNotes(body,label)}}function flatMasterDomain(spec){
23
+ const{label,name}=spec;const fields=masterFields(label,spec.fields);const refHelp=`<${label}> \u306F\u540D\u524D\u30FB\u30B3\u30FC\u30C9\u30FBID \u306E\u3069\u308C\u3067\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\uFF08\u540D\u524D\u304C\u8907\u6570\u306B\u4E00\u81F4\u3059\u308C\u3070\u5019\u88DC\u3092\u51FA\u3057\u3066\u6B62\u307E\u308A\u307E\u3059\uFF09\u3002
24
+ ID \u4EE5\u5916\u306F${label}\u4E00\u89A7\uFF08\u65E2\u5B9A10\u5206\u30AD\u30E3\u30C3\u30B7\u30E5\u30FB--refresh \u3067\u53D6\u308A\u76F4\u3057\uFF09\u3068\u7167\u5408\u3057\u307E\u3059\u3002`;const refFlag={name:`--${name}`,summary:`\u5BFE\u8C61\u306E${label}\uFF08\u4F4D\u7F6E\u5F15\u6570\u306E\u4EE3\u308F\u308A\u306B\u4F7F\u3048\u308B\uFF09`,takesValue:true,placeholder:`<${label}>`};const prepareTarget=async(input,ctx,usage)=>withResolved(input,{id:await targetId(input,{flag:refFlag.name,label,
25
+ usage,resolve:ref=>spec.resolve(ctx,ref,`<${label}>`)})});const itemPath=input=>`${spec.path}/${idSegment(input,label)}`;const item=body=>masterItem(body,spec.itemKey,label);const forbidden=`\u7BA1\u7406\u8005\u306E\u6A29\u9650\u304C\u5FC5\u8981\u3067\u3059\u3002${label}\u306E\u4F5C\u6210\u30FB\u66F4\u65B0\u30FB\u524A\u9664\u306F\u7BA1\u7406\u8005\u3060\u3051\u304C\u884C\u3048\u307E\u3059`;const listOperation=masterListOperation({name,label,path:spec.path,columns:spec.listColumns,...spec.listFilters!==
26
+ void 0?{filters:spec.listFilters}:{}});return{name,summary:spec.summary,operations:[listOperation,{name:"get",summary:`${label}1\u4EF6\u306E\u8A73\u7D30\u3092\u8868\u793A\u3059\u308B`,usage:`twp ${name} get <${label}>`,description:`${refHelp}
27
+
28
+ --output json \u306F API \u304C\u8FD4\u3059\u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u51FA\u3057\u307E\u3059\u3002`,flags:[refFlag],prepare:(input,ctx)=>prepareTarget(input,ctx,`twp ${name} get help`),plan:input=>({method:"GET",path:itemPath(input)}),summarize:body=>pick(item(body),spec.getColumns),raw:body=>item(body)},{name:"create",summary:`${label}\u3092\u4F5C\u6210\u3059\u308B\uFF08\u7BA1\u7406\u8005\u306E\u307F\uFF09`,usage:`twp ${name} create --code <\u30B3\u30FC\u30C9> --name <\u540D\u524D> [\u9805\u76EE\u2026]`,
29
+ description:`--code \u3068 --name \u304C\u5FC5\u9808\u3067\u3059\u3002\u305D\u306E\u307B\u304B\u306E\u9805\u76EE\u306F\u7701\u304F\u3068\u30B5\u30FC\u30D0\u306E\u65E2\u5B9A\u3067\u4F5C\u6210\u3057\u307E\u3059\u3002
30
+
31
+ \u4F5C\u6210\u3057\u305F${label}\u306E ID \u304C\u8FD4\u308A\u307E\u3059\u3002`,forbidden,flags:createFlags(fields),async prepare(input,ctx){if(input.args.length>0){throw new UsageError(`create \u306F\u4F4D\u7F6E\u5F15\u6570\u3092\u53D6\u308A\u307E\u305B\u3093: ${input.args.join(" ")}`,`twp ${name} create help`)}const body=fieldBody(input,fields);for(const flag of["--code","--name"]){const key=flag.slice(2);if(body[key]===void 0)throw new UsageError(`${flag} \u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044`,
32
+ `twp ${name} create help`)}return resolveRefFields(input,ctx,fields)},plan:input=>({method:"POST",path:spec.path,body:fieldBody(input,fields)}),summarize:body=>pick(item(body),spec.getColumns),raw:body=>item(body),notes:()=>[cacheNote(label)]},{name:"update",summary:`${label}\u3092\u66F4\u65B0\u3059\u308B\uFF08\u7BA1\u7406\u8005\u306E\u307F\uFF09`,usage:`twp ${name} update <${label}> [\u9805\u76EE\u2026]`,description:`\u6307\u5B9A\u3057\u305F\u9805\u76EE\u3060\u3051\u3092\u5909\u66F4\u3057\u307E\u3059\uFF08\u6307\u5B9A\u3057\u306A\u304B\u3063\u305F\u9805\u76EE\u306F\u5909\u308F\u308A\u307E\u305B\u3093\uFF09\u3002\u5909\u66F4\u3059\u308B\u9805\u76EE\u30921\u3064\u3082\u6307\u5B9A\u3057\u306A\u3044\u3068\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002
33
+
34
+ ${refHelp}`,forbidden,flags:[...updateFlags(fields),refFlag],async prepare(input,ctx){if(!hasAnyField(input,fields)){throw new UsageError("\u5909\u66F4\u3059\u308B\u9805\u76EE\u30921\u3064\u4EE5\u4E0A\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044",`twp ${name} update help`)}fieldBody(input,fields);const target=await prepareTarget(input,ctx,`twp ${name} update help`);return resolveRefFields(target,ctx,fields)},plan:input=>({method:"PUT",path:itemPath(input),body:fieldBody(input,fields)}),summarize:body=>pick(
35
+ item(body),spec.getColumns),raw:body=>item(body),notes:()=>[cacheNote(label)]},{name:"delete",summary:`${label}\u3092\u524A\u9664\u3059\u308B\uFF08\u7BA1\u7406\u8005\u306E\u307F\u30FB--yes \u304C\u8981\u308B\uFF09`,usage:`twp ${name} delete <${label}> --yes`,description:`\u6240\u5C5E\uFF08\u904E\u53BB\u306E\u5C65\u6B74\u3092\u542B\u3080\uFF09\u304B\u3089\u53C2\u7167\u3055\u308C\u3066\u3044\u308B${label}\u306F\u3001\u30B5\u30FC\u30D0\u304C\u524A\u9664\u3092\u65AD\u308A\u307E\u3059\u3002
36
+ ${spec.deleteGuidance}
37
+
38
+ ${refHelp}`,destructive:true,forbidden,rejected:referencedDeleteGuidance(spec.deleteGuidance),flags:[refFlag],prepare:(input,ctx)=>prepareTarget(input,ctx,`twp ${name} delete help`),plan:input=>({method:"DELETE",path:itemPath(input)}),summarize:body=>acknowledgement(body,`${label}\u524A\u9664`),raw:body=>acknowledgement(body,`${label}\u524A\u9664`),notes:()=>[cacheNote(label)]}]}}export{createFlags,updateFlags,fieldBody,booleanQuery,hasAnyField,resolveRefFields,targetId,idSegment,masterRows,masterItem,cacheNote,referencedDeleteGuidance,masterFields,STATUS_VALUES,masterListOperation,flatMasterDomain};
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
2
  const require = __twpCreateRequire(import.meta.url);
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!==
3
+ import{CommandModelMissingError,MAX_REPORTED_VIOLATIONS,loadCommandModelDomain,loadCommandModelIndex,validateBody,validateQuery}from"./chunk-NZ7WI4RZ.js";import{redactSecretValues,redactSecrets}from"./chunk-YVAN3H5W.js";import{isForceOnly,killProcessTree,system32}from"./chunk-N2UVRM3Z.js";import{isSafePathSegment}from"./chunk-GMBJTG6A.js";import{ApiError,TwpApiClient,appendQuery}from"./chunk-FTYJZFEK.js";import{MODES,applyPermissionMode,checkPermission,isModeId,setActiveModes}from"./chunk-NAUH75MM.js";
4
+ import{DEFAULT_MAX_TOKENS,emptyUsage,isPrivateTwpHome,isTrustworthyCacheFile,writePrivateFileAtomic}from"./chunk-Z2MNO3FT.js";import{AuthSession,NotLoggedInError,SessionExpiredError,withFileLock}from"./chunk-XNLIEUAW.js";import{findExecutable,isWindowsDriveAbsolute}from"./chunk-PMOUHEJQ.js";import{httpFetch}from"./chunk-J7QYPKVK.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!==
5
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=[];
6
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.
7
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\
@@ -74,9 +74,9 @@ home}:{},...c.root?{root:c.root}:{}}}function verdictFromRule(decision,c,target)
74
74
  \u300C${name==="git"?`git ${prefix}`:prefix}\u300D\u3067\u59CB\u307E\u308B\u30B3\u30DE\u30F3\u30C9\u3092\u78BA\u8A8D\u3057\u306A\u3044`}else{rule=name;label=`\u3053\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3067\u306F ${name} \u3092\u78BA\u8A8D\u3057\u306A\u3044`}if(rejectReason(rule)!==null)return[];const{rule:parsed}=parseRule(rule,"allow");if(parsed===null||!ruleMatches(parsed,{toolName:name,input:target.input,cwd}))return[];return[{rule,label}]}function prefixFor(toolName,input){if(toolName===
75
75
  "git"){const sub=input["subcommand"];return typeof sub==="string"&&SUBCOMMAND.test(sub)?sub:null}if(toolName!=="bash")return null;const command=input["command"];if(typeof command!=="string")return null;const words=command.trim().split(/[ \t]+/);const head=words[0]??"";if(!HEAD.test(head)||NO_PREFIX_HEADS.has(head))return null;const second=words[1];if(second===void 0||!SUBCOMMAND.test(second))return null;const pair=`${head} ${second}`;if(!RUNNER_SUBCOMMANDS.has(pair))return pair;const third=words[2];
76
76
  return third!==void 0&&SCRIPT_NAME.test(third)?`${pair} ${third}`:null}function validateInput(schema,input){const errors=[];if(typeof input!=="object"||input===null||Array.isArray(input)){return{ok:false,errors:["input must be a JSON object"],value:{}}}const value={...input};const props=schema.properties??{};for(const key of schema.required??[]){if(value[key]===void 0||value[key]===null)errors.push(`missing required property: ${key}`)}if(schema.additionalProperties===false){for(const key of Object.keys(value)){if(!(key in props))errors.push(`unknown property: ${key}`)}}
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.
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}
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}:
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(path9,schema,value,errors){switch(schema.type){case"string":if(typeof value!=="string")errors.push(`${path9} must be a string`);break;case"boolean":if(typeof value!=="boolean")errors.push(`${path9} must be a boolean`);break;case"integer":if(typeof value!=="number"||!Number.
78
+ isInteger(value))errors.push(`${path9} must be an integer`);break;case"number":if(typeof value!=="number"||!Number.isFinite(value))errors.push(`${path9} must be a number`);break;case"array":if(!Array.isArray(value)){errors.push(`${path9} must be an array`);break}if(schema.items){value.forEach((item,i)=>checkValue(`${path9}[${i}]`,schema.items,item,errors))}break;case"object":if(typeof value!=="object"||value===null||Array.isArray(value)){errors.push(`${path9} must be an object`)}break;default:break}
79
+ if(schema.enum&&!schema.enum.some(v=>v===value)){errors.push(`${path9} must be one of: ${schema.enum.join(", ")}`)}if(typeof value==="number"){if(schema.minimum!==void 0&&value<schema.minimum)errors.push(`${path9} must be >= ${schema.minimum}`);if(schema.maximum!==void 0&&value>schema.maximum)errors.push(`${path9} 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}:
80
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
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
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.
@@ -204,20 +204,43 @@ limit"]:DEFAULT_LIMIT_LINES;const slice=lines.slice(offset-1,offset-1+limit);let
204
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["\
205
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
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-
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}$`)}import fs5 from"fs";import path8 from"path";import{createHash}from"crypto";var TOOL_CATALOG_PATH="/api/v2/cli/tool-catalog";var CACHE_LOCK_WAIT_MS=2e3;var bundledReader={index:loadCommandModelIndex,domain:loadCommandModelDomain};function cacheKey(profile,apiUrl){return createHash("sha256").update(`${profile}
208
+ ${apiUrl}`).digest("hex").slice(0,24)}function toolCatalogCachePaths(profile,apiUrl,env=process.env){const base=path8.join(twpHomeDir(env),`tool-catalog-${cacheKey(profile,apiUrl)}`);return{meta:`${base}.meta.json`,body:`${base}.json`,lock:`${base}.lock`}}function homeIsPrivate(env){return isPrivateTwpHome(twpHomeDir(env))}var REASON_NO_CACHE="\u30B5\u30FC\u30D0\u914D\u4FE1\u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u3042\u308A\u307E\u305B\u3093";var REASON_UNTRUSTED_HOME="~/.twp \u304C\u4ED6\u30E6\u30FC\u30B6\u30FC\u304B\u3089\u66F8\u3051\u308B\u30FB\u30EA\u30F3\u30AF\u3067\
209
+ \u3042\u308B\u305F\u3081\u3001\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u4F7F\u3044\u307E\u305B\u3093";var REASON_BROKEN="\u30B5\u30FC\u30D0\u914D\u4FE1\u306E\u30AD\u30E3\u30C3\u30B7\u30E5\u304C\u58CA\u308C\u3066\u3044\u308B\u305F\u3081\u540C\u68B1\u7248\u3092\u4F7F\u3044\u307E\u3059";function readTrustedJson(file,env){if(!homeIsPrivate(env)||!isTrustworthyCacheFile(file))return void 0;try{return JSON.parse(fs5.readFileSync(file,"utf8"))}catch{return void 0}}function readMeta(profile,apiUrl,account,env){
210
+ const raw=readTrustedJson(toolCatalogCachePaths(profile,apiUrl,env).meta,env);if(!raw||typeof raw!=="object")return null;if(raw.profile!==profile||raw.api_url!==apiUrl||(raw.account??null)!==account)return null;if(typeof raw.version!=="string"||!isVersionToken(raw.version))return null;return{version:raw.version,profile,api_url:apiUrl,account,catalog_version:typeof raw.catalog_version==="string"?raw.catalog_version:null,tool_count:typeof raw.tool_count==="number"?raw.tool_count:0,fetched_at:typeof raw.
211
+ fetched_at==="string"?raw.fetched_at:"",checked_at:typeof raw.checked_at==="string"?raw.checked_at:"",last_result:raw.last_result==="not-modified"?"not-modified":"updated"}}function isVersionToken(value){return/^[A-Za-z0-9._-]{1,128}$/.test(value)}var DOMAIN_RE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;var METHODS=new Set(["GET","POST","PUT","PATCH","DELETE"]);var PATH_RE=/^\/v2\/[A-Za-z0-9_\-{}/.]*$/;function isSafeOperationPath(value){return PATH_RE.test(value)&&!value.split("/").some(segment=>segment===".\
212
+ ."||segment===".")}var RISKS=new Set(["read","write","destructive"]);function isParam(value){if(typeof value!=="object"||value===null)return false;const p=value;return typeof p["name"]==="string"&&(typeof p["type"]==="string"||Array.isArray(p["type"])&&p["type"].every(t=>typeof t==="string"))&&typeof p["required"]==="boolean"&&(p["description"]===void 0||typeof p["description"]==="string")}function isCatalogOperation(value){if(typeof value!=="object"||value===null)return false;const o=value;const body=o["\
213
+ body"];return typeof o["name"]==="string"&&typeof o["domain"]==="string"&&DOMAIN_RE.test(o["domain"])&&typeof o["operationId"]==="string"&&typeof o["method"]==="string"&&METHODS.has(o["method"])&&typeof o["path"]==="string"&&isSafeOperationPath(o["path"])&&typeof o["summary"]==="string"&&Array.isArray(o["pathParams"])&&o["pathParams"].every(isParam)&&Array.isArray(o["queryParams"])&&o["queryParams"].every(isParam)&&(body===null||typeof body==="object"&&!Array.isArray(body))&&(o["resultPath"]===null||
214
+ typeof o["resultPath"]==="string")&&typeof o["risk"]==="string"&&RISKS.has(o["risk"])&&Array.isArray(o["aliases"])&&o["aliases"].every(a=>typeof a==="string")}function parseToolCatalog(raw){if(typeof raw!=="object"||raw===null)return null;const r=raw;const version=r["version"];const tools=r["tools"];if(typeof version!=="string"||!isVersionToken(version)||!Array.isArray(tools))return null;if(!tools.every(isCatalogOperation))return null;const names=new Set;for(const op of tools){const key=`${op.domain}\
215
+ ${op.name}`;if(names.has(key))return null;names.add(key)}return{version,catalogVersion:typeof r["catalog_version"]==="string"?r["catalog_version"]:null,tools}}var RISK_ORDER={read:0,write:1,destructive:2};function methodFloor(method){if(method==="GET")return"read";return method==="DELETE"?"destructive":"write"}function stronger(a,b){return RISK_ORDER[a]>=RISK_ORDER[b]?a:b}function readerFromTools(tools,bundled=bundledReader){const byDomain=new Map;for(const op of tools){const list=byDomain.get(
216
+ op.domain);if(list)list.push(op);else byDomain.set(op.domain,[op])}let indexCache=null;const domainCache=new Map;return{index:async()=>{if(indexCache!==null)return indexCache;const summaries=new Map;try{for(const entry of(await bundled.index()).domains)summaries.set(entry.domain,entry.summary)}catch{}const domains=[...byDomain.entries()].map(([domain,ops])=>({domain,summary:summaries.get(domain)??"",operationCount:ops.length}));indexCache={schemaVersion:1,specVersion:"",domains,totals:{domains:domains.
217
+ length,operations:tools.length}};return indexCache},domain:async domain=>{const cached=domainCache.get(domain);if(cached!==void 0)return cached;const ops=byDomain.get(domain);if(ops===void 0){throw new CommandModelMissingError(`\u30C9\u30E1\u30A4\u30F3 ${domain} \u306F\u3053\u306E\u30A2\u30AB\u30A6\u30F3\u30C8\u306E\u30AB\u30BF\u30ED\u30B0\u306B\u3042\u308A\u307E\u305B\u3093`)}const floor=new Map;try{for(const op of(await bundled.domain(domain)).operations)floor.set(op.operationId,op.risk)}catch{}
218
+ const file={domain,operations:ops.map(op=>{const risk=stronger(stronger(op.risk,methodFloor(op.method)),floor.get(op.operationId)??"read");return risk===op.risk?op:{...op,risk}})};domainCache.set(domain,file);return file}}}var ToolCatalog=class{profile;apiUrl;env;bundled;now;account;decided=null;refreshState;refreshPromise=null;constructor(opts){this.profile=opts.profile;this.apiUrl=opts.apiUrl;this.env=opts.env??process.env;this.bundled=opts.bundled??bundledReader;this.now=opts.now??Date.now;this.
219
+ account=opts.account??(()=>null)}meta(){return readMeta(this.profile,this.apiUrl,this.account(),this.env)}index(){return this.decide().reader.index()}domain(domain){return this.decide().reader.domain(domain)}status(){const refresh=this.refreshState!==void 0?{refresh:this.refreshState}:{};if(this.decided!==null){const{origin,reason,meta:meta2}=this.decided;return{origin,...reason!==void 0?{reason}:{},...metaFields(meta2),...refresh}}if(!homeIsPrivate(this.env))return{origin:"undecided",next:"bund\
220
+ led",reason:REASON_UNTRUSTED_HOME,...refresh};const meta=this.meta();if(meta!==null&&!isTrustworthyCacheFile(toolCatalogCachePaths(this.profile,this.apiUrl,this.env).body)){return{origin:"undecided",next:"bundled",reason:REASON_BROKEN,...refresh}}return meta!==null?{origin:"undecided",next:"server-cache",...metaFields(meta),...refresh}:{origin:"undecided",next:"bundled",reason:REASON_NO_CACHE,...refresh}}decide(){if(this.decided!==null)return this.decided;this.decided=this.loadCache()??{reader:this.
221
+ bundled,origin:"bundled",reason:homeIsPrivate(this.env)?REASON_NO_CACHE:REASON_UNTRUSTED_HOME};return this.decided}loadCache(){const meta=this.meta();if(meta===null)return null;const paths=toolCatalogCachePaths(this.profile,this.apiUrl,this.env);const parsed=parseToolCatalog(readTrustedJson(paths.body,this.env));if(parsed===null||parsed.version!==meta.version){removeQuietly(paths.meta);return{reader:this.bundled,origin:"bundled",reason:REASON_BROKEN}}return{reader:readerFromTools(parsed.tools,this.
222
+ bundled),origin:"server-cache",meta}}refresh(get){this.refreshPromise??=this.doRefresh(get).then(outcome=>{this.refreshState=outcome;return outcome});if(this.refreshState===void 0)this.refreshState="running";return this.refreshPromise}async doRefresh(get){if(!homeIsPrivate(this.env))return{result:"failed",detail:REASON_UNTRUSTED_HOME};const account=this.account();const meta=this.meta();const paths=toolCatalogCachePaths(this.profile,this.apiUrl,this.env);const since=meta!==null&&isTrustworthyCacheFile(
223
+ paths.body)?meta.version:null;let raw;try{raw=await get(TOOL_CATALOG_PATH,since!==null?{since}:void 0)}catch(err){const status=statusOf(err);if(status===304&&meta!==null){try{await this.locked(paths.lock,async()=>{if(this.meta()?.version===meta.version)this.writeMeta(paths.meta,{...meta,checked_at:this.iso(),last_result:"not-modified"})})}catch{}return{result:"not-modified"}}if(status===404||status===401||status===403||isAuthError(err)){removeQuietly(paths.meta);removeQuietly(paths.body);return{
224
+ result:"unavailable",detail:status!==null?`\u30B5\u30FC\u30D0\u304C ${status} \u3092\u8FD4\u3057\u307E\u3057\u305F`:"\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093"}}return{result:"failed",detail:status!==null?`\u30B5\u30FC\u30D0\u304C ${status} \u3092\u8FD4\u3057\u307E\u3057\u305F`:`\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\uFF08${messageOf(err)}\uFF09`}}const parsed=parseToolCatalog(raw);if(parsed===null)return{result:"failed",detail:"\u30B5\u30FC\u30D0\u306E\u5FDC\u7B54\u306E\u5F62\u304C\u9055\u3044\u307E\u3059"};
225
+ try{ensureTwpHome(this.env);await this.locked(paths.lock,async()=>{writePrivateFileAtomic(paths.body,JSON.stringify({version:parsed.version,catalog_version:parsed.catalogVersion,tools:parsed.tools}));const at=this.iso();this.writeMeta(paths.meta,{version:parsed.version,profile:this.profile,api_url:this.apiUrl,account,catalog_version:parsed.catalogVersion,tool_count:parsed.tools.length,fetched_at:at,checked_at:at,last_result:"updated"})})}catch(err){return{result:"failed",detail:`\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u66F8\u3051\u307E\u305B\u3093\uFF08${messageOf(
226
+ err)}\uFF09`}}return{result:"updated"}}async locked(lockPath,fn){await withFileLock(lockPath,fn,CACHE_LOCK_WAIT_MS)}writeMeta(file,meta){try{ensureTwpHome(this.env);writePrivateFileAtomic(file,`${JSON.stringify(meta,null,2)}
227
+ `)}catch{}}iso(){return new Date(this.now()).toISOString()}};function metaFields(meta){if(meta===void 0)return{};return{version:meta.version,toolCount:meta.tool_count,...meta.fetched_at!==""?{fetchedAt:meta.fetched_at}:{},...meta.checked_at!==""?{checkedAt:meta.checked_at}:{}}}function statusOf(err){const status=err?.status;return typeof status==="number"?status:null}function isAuthError(err){return err instanceof NotLoggedInError||err instanceof SessionExpiredError}function messageOf(err){return err instanceof
228
+ Error?err.message:String(err)}function removeQuietly(file){try{fs5.rmSync(file,{force:true})}catch{}}function describeToolCatalog(status){const origin=status.origin==="undecided"?status.next:status.origin;const head=origin==="server-cache"?`\u30B5\u30FC\u30D0\u914D\u4FE1\uFF08${status.toolCount??"?"} \u64CD\u4F5C\u30FB\u7248 ${status.version?.slice(0,12)??"?"}\u30FB\u53D6\u5F97 ${status.fetchedAt??"?"}\uFF09`:`\u540C\u68B1\u7248\uFF08${status.reason??"\u7406\u7531\u4E0D\u660E"}\uFF09`;const when=status.
229
+ origin==="undecided"?"\uFF08\u3053\u306E\u30BB\u30C3\u30B7\u30E7\u30F3\u3067\u306F\u307E\u3060\u672A\u4F7F\u7528\u30FB\u6B21\u306B\u4F7F\u3046\u51FA\u3069\u3053\u308D\uFF09":"";const refresh=status.refresh;const tail=refresh===void 0?"\u66F4\u65B0: \u672A\u5B9F\u884C":refresh==="running"?"\u66F4\u65B0: \u53D6\u5F97\u4E2D":`\u66F4\u65B0: ${REFRESH_LABEL[refresh.result]}${refresh.detail!==void 0?`\uFF08${refresh.detail}\uFF09`:""}`;return`TWP \u30C4\u30FC\u30EB\u30AB\u30BF\u30ED\u30B0: ${head}${when}\
230
+ \xB7 ${tail}`}var REFRESH_LABEL={updated:"\u65B0\u3057\u3044\u7248\u3092\u53D6\u5F97\u3057\u3066\u4FDD\u5B58","not-modified":"\u6700\u65B0\uFF08304\uFF09",unavailable:"\u30B5\u30FC\u30D0\u914D\u4FE1\u306A\u3057\u30FB\u6B21\u56DE\u304B\u3089\u540C\u68B1\u7248",failed:"\u5931\u6557\u30FB\u30AD\u30E3\u30C3\u30B7\u30E5\u3092\u7DAD\u6301"};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
231
  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
232
  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
233
  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}:
234
+ op),preview:input=>previewOf(op,input),run:async input=>runOperation(op,name,input,deps)}}function previewOf(op,input){let path9=op.path;for(const param of op.pathParams){const value=input[param.name];path9=path9.split(`{${param.name}}`).join(typeof value==="string"||typeof value==="number"?String(value):`{${param.name}}`)}return`${op.method} ${path9}`}function buildRequest(op,input){const errors=[];let path9=op.path;const pathNames=new Set;for(const param of op.pathParams){pathNames.add(param.name);
235
+ 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}path9=path9.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&&
236
+ op.method!=="GET")errors.push(...validateBody(op.body.schema,body??{}));if(errors.length>0)return{ok:false,errors};return{ok:true,path:path9.toLowerCase().startsWith("/api/")?path9:`/api${path9}`,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
237
  - ${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
238
  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
239
+ \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;catalog;constructor(opts){this.catalog=opts.catalog;this.source=opts.catalog?.reader??opts.source??bundledSource;this.client=opts.client;this.meta=[this.domainsTool(),this.searchTool(),this.describeTool(),this.callTool(),this.mountTool()]}refreshCatalog(){
240
+ return this.catalog?this.catalog.reader.refresh(this.catalog.get):Promise.resolve(null)}cancelCatalogRefresh(){this.catalog?.cancel()}catalogStatus(){return this.catalog?.reader.status()??null}metaTools(){return[...this.meta]}mountedTools(){return this.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(
241
+ 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){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.
242
+ 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.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. \
243
+ 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})${d.summary!==""?`: ${d.summary}`:""}`);return{content:`${index.totals.domains} domains / ${index.totals.operations} operations
221
244
  ${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
245
  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
246
  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\
@@ -229,4 +252,6 @@ name);if(!tool)return{content:`Unknown tool: ${name}. Use twp_search_tools.`,isE
229
252
  - ${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
253
  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
254
  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};
255
+ 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,fetchImpl=httpFetch){let session=null;const sharedSession=()=>session??=runtime.session??new AuthSession(runtime.profileName,runtime.apiUrl);let client=null;const abort=new AbortController;const get=(path9,query)=>new TwpApiClient(runtime.apiUrl,sharedSession(),withSignal(fetchImpl,()=>AbortSignal.any([abort.signal,AbortSignal.timeout(CATALOG_FETCH_TIMEOUT_MS)])),cliVersion).get(path9,query);const account=()=>{try{const creds=sharedSession().loadOrThrow();
256
+ return`${creds.tenant_code??""}:${creds.user?.id??""}`}catch{return null}};return new TwpToolkit({client:()=>{client??=new TwpApiClient(runtime.apiUrl,sharedSession(),fetchImpl,cliVersion);return client},catalog:{reader:new ToolCatalog({profile:runtime.profileName,apiUrl:runtime.apiUrl,account}),get,cancel:()=>abort.abort()}})}var CATALOG_FETCH_TIMEOUT_MS=2e4;function withSignal(fetchImpl,signal){return(input,init)=>fetchImpl(input,{...init,signal:signal()})}function residentInputs(toolkit,local=localTools()){
257
+ 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,describeToolCatalog,createTwpToolkit,residentInputs};
@@ -0,0 +1,57 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{PRIVATE_PROJECT_REF,isPrivateProjectRef}from"./chunk-GY7KI5E5.js";import{isSafePathSegment,safeProjectIdPolicy}from"./chunk-GMBJTG6A.js";import{requireResolved,singleRef,withResolved}from"./chunk-ZN5EFDH7.js";import{PRIVATE_TASK_KEY_PREFIX,isPrivateTaskKey,isTaskKey}from"./chunk-II5RVJQN.js";import{checkUploadQuota}from"./chunk-DDKZ5IPT.js";import{isRecord,pick}from"./chunk-ZWVYVS2A.js";import{ApiResponseError,UsageError}from"./chunk-7WSNIXTQ.js";function classifyTaskRef(ref){const value=ref.trim();if(safeProjectIdPolicy.isDirectId(value))return{kind:"id",value};if(isTaskKey(value))return{kind:"key",value};return{kind:"unknown",value}}function wantsPrivateSurface(input){const project=input.flags.get("--project");return project!==void 0&&isPrivateProjectRef(project)}function taskSurface(input,ref){const project=input.flags.get("--project");const{kind,value}=classifyTaskRef(ref);if(project!==void 0&&isPrivateProjectRef(project)){if(kind===
4
+ "key"&&!isPrivateTaskKey(value)){throw new UsageError(`--project ${PRIVATE_PROJECT_REF}\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\uFF09\u306B ${value} \u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093`,`\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u306F ${PRIVATE_TASK_KEY_PREFIX}-<\u756A\u53F7> \u306E\u5F62\u3067\u3059\u3002ID\uFF08UUID / ULID\uFF09\u3067\u3082\u6307\u5B9A\u3067\u304D\u307E\u3059\u3002
5
+ \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3092\u6307\u3059\u306A\u3089 --project ${PRIVATE_PROJECT_REF} \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return"private"}if(kind==="key"&&isPrivateTaskKey(value)&&project===void 0){throw new UsageError(`${value} \u306F\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u306B\u3082\u3001\u30B3\u30FC\u30C9 ${PRIVATE_TASK_KEY_PREFIX} \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u30AD\u30FC\u306B\u3082\u8AAD\u3081\u307E\u3059`,
6
+ `\u3069\u3061\u3089\u3092\u6307\u3059\u304B --project \u3067\u9078\u3093\u3067\u304F\u3060\u3055\u3044\u3002
7
+ \u500B\u4EBA\u30BF\u30B9\u30AF : --project ${PRIVATE_PROJECT_REF}
8
+ \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8: --project ${PRIVATE_TASK_KEY_PREFIX}`)}return"project"}function rejectPrivateSurface(input,what){if(!wantsPrivateSurface(input))return;throw new UsageError(`--project ${PRIVATE_PROJECT_REF}\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\uFF09\u3067\u306F${what}\u3092\u6271\u3048\u307E\u305B\u3093`,`\u30B5\u30FC\u30D0\u5074\u306B\u500B\u4EBA\u30BF\u30B9\u30AF\u7528\u306E API \u304C\u3042\u308A\u307E\u305B\u3093\u3002TWP \u306E\u753B\u9762\u304B\u3089\u64CD\u4F5C\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}
9
+ async function resolveTaskLocation(input,ctx,ref){rejectPrivateSurface(input,"\u3053\u306E\u64CD\u4F5C");const{kind,value}=classifyTaskRef(ref);if(kind==="key"){if(isPrivateTaskKey(value)&&input.flags.get("--project")===void 0){throw new UsageError(`${value} \u306F\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u306B\u3082\u3001\u30B3\u30FC\u30C9 ${PRIVATE_TASK_KEY_PREFIX} \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u30AD\u30FC\u306B\u3082\u8AAD\u3081\u307E\u3059`,`\u3053\u306E\u64CD\u4F5C\u306F\u500B\
10
+ \u4EBA\u30BF\u30B9\u30AF\u306B\u5BFE\u5FDC\u3057\u3066\u3044\u307E\u305B\u3093\uFF08\u30B5\u30FC\u30D0\u5074\u306B API \u304C\u3042\u308A\u307E\u305B\u3093\uFF09\u3002
11
+ \u30B3\u30FC\u30C9 ${PRIVATE_TASK_KEY_PREFIX} \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3092\u6307\u3059\u306A\u3089 --project ${PRIVATE_TASK_KEY_PREFIX} \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002`)}rejectRedundantProject(input,value);const resolved=await ctx.resolver.taskByKey(value);const id=resolved.task["id"];if(!isSafePathSegment(id)){throw new ApiResponseError(`\u30BF\u30B9\u30AF\u30AD\u30FC\u89E3\u6C7A\u306E\u5FDC\u7B54\u306E task.id \u3092\u305D\u306E\u307E\u307E\u4F7F\u3048\u307E\u305B\u3093\uFF08${String(
12
+ id).slice(0,60)}\uFF09\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}return{projectId:resolved.projectId,taskId:id}}if(kind==="unknown"){throw new UsageError(`\u30BF\u30B9\u30AF\u306E\u6307\u5B9A\u304C\u300C\u30AD\u30FC\uFF08\u4F8B ABC-123\uFF09\u300D\u306B\u3082\u300CID\uFF08UUID / ULID\uFF09\u300D\u306B\u3082\u898B\u3048\u307E\u305B\u3093: ${ref}`,"\u30AD\u30FC\u306F\u300C\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30FC\u30C9-\u756A\u53F7\u300D\u306E\u5F62\u3067\u3059\u3002ID \u3092\u6307\u5B9A\u3059\u308B\u5834\u5408\u306F --project \u3082\u5FC5\u8981\u3067\u3059\u3002")}
13
+ if(kind!=="id"){const exhaustive=kind;throw new Error(`\u672A\u77E5\u306E\u30BF\u30B9\u30AF\u53C2\u7167\u306E\u7A2E\u5225\u3067\u3059: ${String(exhaustive)}`)}return{projectId:await ctx.projectId(input.flags.get("--project")),taskId:value}}function rejectRedundantProject(input,ref){const project=input.flags.get("--project");if(project===void 0)return;if(isPrivateTaskKey(ref)){if(isPrivateProjectRef(project))return;if(project.trim().toLowerCase()===PRIVATE_TASK_KEY_PREFIX.toLowerCase())return;throw new UsageError(
14
+ `\u30AD\u30FC ${ref} \u3068 --project ${project} \u304C\u98DF\u3044\u9055\u3063\u3066\u3044\u307E\u3059`,`${ref} \u304C\u6307\u305B\u308B\u306E\u306F\u6B21\u306E2\u3064\u3060\u3051\u3067\u3059\u3002
15
+ \u500B\u4EBA\u30BF\u30B9\u30AF : --project ${PRIVATE_PROJECT_REF}
16
+ \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8: --project ${PRIVATE_TASK_KEY_PREFIX}\uFF08\u30AD\u30FC\u306E\u63A5\u982D\u8F9E\u3068\u540C\u3058\u30B3\u30FC\u30C9\uFF09
17
+ \u5225\u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u3092\u6307\u3059\u306A\u3089\u3001\u30AD\u30FC\u3067\u306F\u306A\u304F\u305D\u306E\u30BF\u30B9\u30AF\u306E ID\uFF08UUID / ULID\uFF09\u3092\u6E21\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}throw new UsageError(`\u30AD\u30FC\u5F62\u5F0F\uFF08${ref}\uFF09\u3067\u6307\u5B9A\u3057\u305F\u3068\u304D\u306B --project \u306F\u4F7F\u3048\u307E\u305B\u3093\uFF08--project ${project} \u306F\u7121\u8996\u3055\u308C\u307E\u3059\uFF09`,"\
18
+ \u30AD\u30FC\u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u542B\u3093\u3067\u3044\u308B\u306E\u3067 --project \u3092\u5916\u3057\u3066\u304F\u3060\u3055\u3044\u3002--project \u304C\u8981\u308B\u306E\u306F\u3001\u30BF\u30B9\u30AF\u3092 ID\uFF08UUID / ULID\uFF09\u3067\u6307\u5B9A\u3059\u308B\u3068\u304D\u3060\u3051\u3067\u3059\u3002")}var TASK_REF_FLAG={name:"--task",summary:"\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\uFF08\u4F8B ABC-123\uFF09\u307E\u305F\u306F ID\u3002\u4F4D\u7F6E\u5F15\u6570\u3068\u540C\u3058\u610F\u5473\uFF08\u4E21\u65B9\u6307\u5B9A\u306F\u30A8\u30E9\u30FC\uFF09",
19
+ takesValue:true,placeholder:"<\u30AD\u30FC|ID>"};var PROJECT_FLAG={name:"--project",summary:`\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30B3\u30FC\u30C9\u307E\u305F\u306F ID\uFF08\u7701\u7565\u6642\u306F TWP_PROJECT / .twp/config.json / ~/.twp/config.json\uFF09\u3002\u30BF\u30B9\u30AF\u3092\u30AD\u30FC\u3067\u6307\u5B9A\u3059\u308B\u3068\u304D\u306F\u4F7F\u3048\u307E\u305B\u3093\u3002${PRIVATE_PROJECT_REF} \u3067\u500B\u4EBA\u30BF\u30B9\u30AF\u3092\u6307\u3057\u307E\u3059`,takesValue:true,placeholder:`\
20
+ <\u30B3\u30FC\u30C9|ID|${PRIVATE_PROJECT_REF}>`};var TASK_REF_HELP=`\u30AD\u30FC\u5F62\u5F0F\uFF08\u4F8B ABC-123\uFF09\u306A\u3089 --project \u306F\u8981\u308A\u307E\u305B\u3093\uFF081\u5F80\u5FA9\u3067\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3054\u3068\u89E3\u6C7A\u3055\u308C\u307E\u3059\uFF09\u3002
21
+ \u30AD\u30FC\u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u542B\u3093\u3067\u3044\u308B\u306E\u3067\u3001\u30AD\u30FC\u3068 --project \u3092\u4E00\u7DD2\u306B\u6307\u5B9A\u3059\u308B\u3068\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002
22
+ ID\uFF08UUID / ULID\uFF09\u3067\u6307\u5B9A\u3059\u308B\u5834\u5408\u3060\u3051 --project\uFF08\u307E\u305F\u306F\u65E2\u5B9A\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF09\u304C\u8981\u308A\u307E\u3059\u3002
23
+ UUID / ULID \u306E\u5F62\u3092\u3057\u305F\u5024\u306F\u3001\u30AD\u30FC\u306E\u5F62\u306B\u3082\u8AAD\u3081\u308B\u3068\u304D\u3067\u3082 ID \u3068\u3057\u3066\u6271\u3044\u307E\u3059\uFF08\u4F8B: \u672B\u5C3E12\u6841\u304C\u5168\u6570\u5B57\u306E UUID\uFF09\u3002\u3053\u306E\u5834\u5408\u306F --project \u304C\u8981\u308A\u307E\u3059\u3002
24
+ --task <\u30AD\u30FC|ID> \u3067\u3082\u540C\u3058\u610F\u5473\u3067\u3059\u3002\u4F4D\u7F6E\u5F15\u6570\u3068 --task \u306E\u4E21\u65B9\u3092\u6307\u5B9A\u3059\u308B\u3068\u30A8\u30E9\u30FC\u306B\u306A\u308A\u307E\u3059\u3002
25
+ ${PRIVATE_TASK_KEY_PREFIX}-<\u756A\u53F7> \u306E\u5F62\u306E\u30AD\u30FC\u3060\u3051\u306F\u4F8B\u5916\u3067\u3001--project \u304C\u5FC5\u9808\u3067\u3059\uFF08\u500B\u4EBA\u30BF\u30B9\u30AF\u306E\u30AD\u30FC\u3068\u3082\u3001\u30B3\u30FC\u30C9 ${PRIVATE_TASK_KEY_PREFIX} \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30BF\u30B9\u30AF\u30AD\u30FC\u3068\u3082\u8AAD\u3081\u308B\u305F\u3081\uFF09\u3002`;import fs from"fs";import path from"path";var TASK_SOURCE="task";var IDS_PER_REQUEST=100;var LIST_COLUMNS=["id","file_name","content_type","file_size","is_committed","created_at"];var UPLOAD_COLUMNS=["attachment_id","task_id","file_name","content_type","file_size","attachment_count"];var CONTENT_TYPES={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".pdf":"application/pdf",".txt":"text/plain",".log":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".zip":"\
26
+ application/zip",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function contentTypeFor(fileName){return CONTENT_TYPES[path.extname(fileName).toLowerCase()]??"application/octet-stream"}var FILE_FLAG={name:"--file",summary:"\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3059\u308B\u30ED\u30FC\u30AB\u30EB\u30D5\u30A1\u30A4\u30EB\u306E\u30D1\u30B9\uFF08\u5FC5\u9808\uFF09",
27
+ takesValue:true,placeholder:"<\u30D1\u30B9>"};var NAME_FLAG={name:"--name",summary:"\u30B5\u30FC\u30D0\u306B\u4FDD\u5B58\u3059\u308B\u30D5\u30A1\u30A4\u30EB\u540D\uFF08\u7701\u7565\u6642\u306F\u30ED\u30FC\u30AB\u30EB\u306E\u30D5\u30A1\u30A4\u30EB\u540D\uFF09",takesValue:true,placeholder:"<\u30D5\u30A1\u30A4\u30EB\u540D>"};var CONTENT_TYPE_FLAG={name:"--content-type",summary:"Content-Type\uFF08\u7701\u7565\u6642\u306F\u62E1\u5F35\u5B50\u304B\u3089\u63A8\u5B9A\u3002\u4E0D\u660E\u306A\u3089 application/octet-stream\uFF09",
28
+ takesValue:true,placeholder:"<\u578B>"};var OUT_FLAG={name:"--out",summary:"\u66F8\u304D\u51FA\u3057\u5148\u306E\u30D5\u30A1\u30A4\u30EB\u30D1\u30B9\uFF08\u5FC5\u9808\u3002\u6A19\u6E96\u51FA\u529B\u3078\u306F\u51FA\u3057\u307E\u305B\u3093\uFF09",takesValue:true,placeholder:"<\u30D1\u30B9>"};var ATTACHMENT_REF_FLAG={name:"--attachment",summary:"\u6DFB\u4ED8ID\u3002\u4F4D\u7F6E\u5F15\u6570\u3068\u540C\u3058\u610F\u5473\uFF08\u4E21\u65B9\u6307\u5B9A\u306F\u30A8\u30E9\u30FC\uFF09",takesValue:true,placeholder:"\
29
+ <\u6DFB\u4ED8ID>"};var FORCE_FLAG={name:"--force",summary:"\u66F8\u304D\u51FA\u3057\u5148\u304C\u65E2\u306B\u3042\u308C\u3070\u4E0A\u66F8\u304D\u3059\u308B\uFF08\u65E2\u5B9A\u3067\u306F\u4E0A\u66F8\u304D\u3057\u306A\u3044\uFF09",takesValue:false};function taskPath(input){const projectId=encodeURIComponent(requireResolved(input,"projectId"));return`/api/v2/projects/${projectId}/tasks/${encodeURIComponent(requireResolved(input,"taskId"))}`}function taskAttachmentIds(body){const task=isRecord(body)?
30
+ body["task"]:void 0;if(!isRecord(task)){throw new ApiResponseError("\u30BF\u30B9\u30AF\u8A73\u7D30\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")}const ids=task["attachment_ids"];if(ids===null||ids===void 0)return[];if(!Array.isArray(ids)||!ids.every(id=>typeof id==="string")){throw new ApiResponseError("\u30BF\u30B9\u30AF\u8A73\u7D30\u306E attachment_ids \u304C\u6587\u5B57\u5217\u306E\u914D\u5217\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}
31
+ return ids}function attachmentRows(body){const data=isRecord(body)?body["data"]:void 0;if(!Array.isArray(data)){throw new ApiResponseError("\u6DFB\u4ED8\u4E00\u89A7\u306E\u5FDC\u7B54\u306B data \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}return data}async function resolveTask(input,ctx,usage){const ref=singleRef(input,{flag:"--task",label:"\u30BF\u30B9\u30AF",usage});return withResolved(input,await resolveTaskLocation(
32
+ input,ctx,ref))}function localFile(input){const raw=input.flags.get("--file");if(raw===void 0||raw.trim()===""){throw new UsageError("--file \u306F\u5FC5\u9808\u3067\u3059","twp task attachment upload <\u30AD\u30FC|ID> --file <\u30D1\u30B9>")}const file=path.resolve(raw.trim());let stat;try{stat=fs.statSync(file)}catch{throw new UsageError(`\u30D5\u30A1\u30A4\u30EB\u304C\u3042\u308A\u307E\u305B\u3093: ${file}`)}if(!stat.isFile())throw new UsageError(`\u901A\u5E38\u306E\u30D5\u30A1\u30A4\u30EB\u3067\u306F\u3042\u308A\u307E\u305B\u3093: ${file}`);
33
+ if(stat.size===0)throw new UsageError(`\u7A7A\u306E\u30D5\u30A1\u30A4\u30EB\u306F\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u3067\u304D\u307E\u305B\u3093: ${file}`);const nameFlag=input.flags.get("--name");const name=nameFlag!==void 0&&nameFlag.trim()!==""?nameFlag.trim():path.basename(file);const typeFlag=input.flags.get("--content-type");const contentType=typeFlag!==void 0&&typeFlag.trim()!==""?typeFlag.trim():contentTypeFor(name);return{file,name,size:stat.size,contentType}}function uploadUrlPlan(input){
34
+ return{method:"POST",path:"/api/v2/attachments/upload-url",body:{file_name:requireResolved(input,"fileName"),content_type:requireResolved(input,"contentType"),file_size:Number(requireResolved(input,"fileSize")),source:TASK_SOURCE}}}function issued(body){const data=isRecord(body)?body["data"]:void 0;const id=isRecord(data)?data["id"]:void 0;const uploadUrl=isRecord(data)?data["upload_url"]:void 0;if(!isSafePathSegment(id)||typeof uploadUrl!=="string"||!/^https:\/\//.test(uploadUrl)){throw new ApiResponseError(
35
+ "\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9URL\u767A\u884C\u306E\u5FDC\u7B54\u306B data.id / data.upload_url \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}return{id,uploadUrl}}async function upload(input,ctx){const file=requireResolved(input,"file");const size=Number(requireResolved(input,"fileSize"));const contentType=requireResolved(input,"contentType");await checkUploadQuota(ctx,size);const{id,uploadUrl}=issued(await ctx.send(
36
+ uploadUrlPlan(input)));const bytes=new Uint8Array(fs.readFileSync(file));if(bytes.byteLength!==size){throw new UsageError(`\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u4E2D\u306B\u30D5\u30A1\u30A4\u30EB\u306E\u5927\u304D\u3055\u304C\u5909\u308F\u308A\u307E\u3057\u305F\uFF08${size} \u2192 ${bytes.byteLength} \u30D0\u30A4\u30C8\uFF09: ${file}`)}await ctx.putSigned(uploadUrl,bytes,contentType);try{const current=taskAttachmentIds(await ctx.send({method:"GET",path:taskPath(input)}));const next=current.includes(
37
+ id)?current:[...current,id];const updated=await ctx.send({method:"PUT",path:taskPath(input),body:{attachment_ids:next}});const linked=taskAttachmentIds(updated);if(!linked.includes(id)){throw new ApiResponseError("\u30BF\u30B9\u30AF\u66F4\u65B0\u306E\u5FDC\u7B54\u306E attachment_ids \u306B\u4ECA\u56DE\u306E\u6DFB\u4ED8\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}return{attachment_id:id,task_id:requireResolved(input,"ta\
38
+ skId"),project_id:requireResolved(input,"projectId"),file_name:requireResolved(input,"fileName"),content_type:contentType,file_size:size,attachment_count:linked.length}}catch(err){ctx.warn(`\u6DFB\u4ED8 ${id} \u306F\u30B9\u30C8\u30EC\u30FC\u30B8\u3078\u306E\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u307E\u3067\u5B8C\u4E86\u3057\u307E\u3057\u305F\u304C\u3001\u30BF\u30B9\u30AF\u3078\u306E\u7D10\u3065\u3051\u306B\u5931\u6557\u3057\u307E\u3057\u305F\u3002
39
+ \u672A\u7D10\u3065\u3051\u306E\u6DFB\u4ED8\u306F\u30B5\u30FC\u30D0\u304C\u4E00\u5B9A\u6642\u9593\uFF08\u7F72\u540DURL\u306E\u6709\u52B9\u671F\u9650\uFF0B1\u6642\u9593\uFF09\u5F8C\u306B\u81EA\u52D5\u3067\u524A\u9664\u3057\u307E\u3059\u3002\u3082\u3046\u4E00\u5EA6 twp task attachment upload \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002`);throw err}}async function list(input,ctx){const ids=taskAttachmentIds(await ctx.send({method:"GET",path:taskPath(input)}));const rows=[];for(let offset=0;offset<
40
+ ids.length;offset+=IDS_PER_REQUEST){const chunk=ids.slice(offset,offset+IDS_PER_REQUEST);rows.push(...attachmentRows(await ctx.send({method:"GET",path:"/api/v2/attachments",query:{ids:chunk.join(",")}})))}if(rows.length<ids.length){ctx.warn(`\u30BF\u30B9\u30AF\u306B\u7D10\u3065\u304F\u6DFB\u4ED8 ${ids.length} \u4EF6\u306E\u3046\u3061 ${ids.length-rows.length} \u4EF6\u306F\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08\u524A\u9664\u6E08\u307F\u304B\u3001\u95B2\u89A7\u3067\u304D\u307E\u305B\u3093\uFF09\u3002`)}
41
+ return{data:rows}}var taskAttachmentResource={name:"attachment",summary:"\u30BF\u30B9\u30AF\u306E\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\uFF08\u30A2\u30C3\u30D7\u30ED\u30FC\u30C9\u30FB\u4E00\u89A7\u30FB\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9\uFF09",operations:[{name:"list",summary:"\u30BF\u30B9\u30AF\u306E\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\u3092\u4E00\u89A7\u3059\u308B",usage:"twp task attachment list <\u30AD\u30FC|ID> [--project <\u30B3\u30FC\u30C9|ID>]",description:`${TASK_REF_HELP}
42
+
43
+ \u30BF\u30B9\u30AF\u672C\u4F53\u306B\u7D10\u3065\u304F\u6DFB\u4ED8\u3060\u3051\u3092\u8FD4\u3057\u307E\u3059\uFF08\u30B3\u30E1\u30F3\u30C8\u306B\u4ED8\u3044\u305F\u6DFB\u4ED8\u306F\u542B\u307F\u307E\u305B\u3093\uFF09\u3002
44
+ \u30BF\u30B9\u30AF\u3092\u53D6\u5F97\u3057\u3066\u6DFB\u4ED8 ID \u3092\u5F97\u305F\u3042\u3068\u3001ID \u3067\u30E1\u30BF\u60C5\u5831\u3092\u53D6\u5F97\u3057\u307E\u3059\uFF082\u5F80\u5FA9\u4EE5\u4E0A\uFF09\u3002`,flags:[TASK_REF_FLAG,PROJECT_FLAG],prepare:(input,ctx)=>resolveTask(input,ctx,"twp task attachment list help"),plan:input=>({method:"GET",path:taskPath(input)}),plannedNotes:()=>["\u3053\u306E\u3042\u3068\u3001\u30BF\u30B9\u30AF\u306E attachment_ids \u3067 GET /api/v2/attachments?ids=\u2026 \u3092\u9001\u308A\u307E\u3059\u3002"],
45
+ execute:list,summarize:body=>attachmentRows(body).map(row=>pick(row,LIST_COLUMNS)),raw:body=>attachmentRows(body)},{name:"upload",summary:"\u30ED\u30FC\u30AB\u30EB\u30D5\u30A1\u30A4\u30EB\u3092\u30BF\u30B9\u30AF\u306B\u6DFB\u4ED8\u3059\u308B\uFF08\u767A\u884C\u30FB\u8EE2\u9001\u30FB\u7D10\u3065\u3051\u30921\u30B3\u30DE\u30F3\u30C9\u3067\uFF09",usage:"twp task attachment upload <\u30AD\u30FC|ID> --file <\u30D1\u30B9> [--name <\u30D5\u30A1\u30A4\u30EB\u540D>] [--content-type <\u578B>]",description:`${TASK_REF_HELP}\
46
+
47
+
48
+ \u5BB9\u91CF\u3092\u78BA\u304B\u3081\u3066\u304B\u3089\u3001\u6B21\u306E3\u5F80\u5FA9\u30921\u30B3\u30DE\u30F3\u30C9\u3067\u884C\u3044\u307E\u3059\u3002
49
+ 0. POST /api/v2/storage/check-upload\uFF08\u30C6\u30CA\u30F3\u30C8\u306E\u5BB9\u91CF\u691C\u67FB\u3002\u8D85\u904E\u306A\u3089\u4F55\u3082\u9001\u3089\u305A\u306B\u6B62\u307E\u308A\u307E\u3059\uFF09
50
+ 1. POST /api/v2/attachments/upload-url\uFF08\u7F72\u540DURL\u306E\u767A\u884C\uFF09
51
+ 2. \u7F72\u540DURL\u3078 PUT\uFF08\u30D5\u30A1\u30A4\u30EB\u672C\u4F53\u3002TWP \u306E\u8A8D\u8A3C\u60C5\u5831\u306F\u9001\u308A\u307E\u305B\u3093\uFF09
52
+ 3. \u30BF\u30B9\u30AF\u306E attachment_ids \u306B\u8FFD\u52A0\u3057\u3066 PUT\uFF08\u3053\u3053\u3067\u6DFB\u4ED8\u304C\u78BA\u5B9A\u3057\u307E\u3059\uFF09
53
+ 3 \u304C\u5931\u6557\u3057\u305F\u5834\u5408\u306F\u6DFB\u4ED8 ID \u3092 stderr \u306B\u51FA\u3057\u3066\u5931\u6557\u3057\u307E\u3059\u3002\u672A\u78BA\u5B9A\u306E\u6DFB\u4ED8\u306F\u30B5\u30FC\u30D0\u304C\u81EA\u52D5\u3067\u524A\u9664\u3057\u307E\u3059\u3002
54
+ --dry-run \u306F 1 \u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u3060\u3051\u3092\u8868\u793A\u3057\u307E\u3059\uFF082 \u4EE5\u964D\u306F 1 \u306E\u5FDC\u7B54\u306B\u4F9D\u5B58\u3059\u308B\u305F\u3081\uFF09\u3002`,flags:[FILE_FLAG,NAME_FLAG,CONTENT_TYPE_FLAG,TASK_REF_FLAG,PROJECT_FLAG],async prepare(input,ctx){const local=localFile(input);const resolved=await resolveTask(input,ctx,"twp task attachment upload help");return withResolved(resolved,{file:local.file,fileName:local.name,fileSize:String(local.size),
55
+ contentType:local.contentType})},plan:uploadUrlPlan,plannedNotes:input=>[`\u5B9F\u884C\u6642\u306F\u3001\u3053\u306E\u524D\u306B\u5BB9\u91CF\u691C\u67FB\uFF08POST /api/v2/storage/check-upload\uFF09\u3092\u9001\u308A\u3001\u3053\u306E\u3042\u3068\u7F72\u540DURL\u3078 ${requireResolved(input,"fileSize")} \u30D0\u30A4\u30C8\u3092 PUT \u3057\u3001\u30BF\u30B9\u30AF\u306E attachment_ids \u306B\u8FFD\u52A0\u3057\u3066 PUT \u3057\u307E\u3059\u3002`],execute:upload,summarize:body=>pick(body,UPLOAD_COLUMNS),
56
+ raw:body=>body},{name:"download",summary:"\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB\u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9\u3057\u3066\u30D5\u30A1\u30A4\u30EB\u3078\u66F8\u304D\u51FA\u3059",usage:"twp task attachment download <\u6DFB\u4ED8ID> --out <\u30D1\u30B9> [--force]",description:"\u6DFB\u4ED8 ID \u306F twp task attachment list \u306E id \u3067\u3059\u3002\n\u66F8\u304D\u51FA\u3057\u5148\u306F --out \u3067\u5FC5\u305A\u6307\u5B9A\u3057\u307E\u3059\uFF08\u6A19\u6E96\u51FA\u529B\u3078\u306F\u51FA\u3057\u307E\u305B\u3093\uFF09\u3002\u65E2\u5B58\u30D5\u30A1\u30A4\u30EB\u306F --force \u304C\u7121\u3051\u308C\u3070\u4E0A\u66F8\u304D\u3057\u307E\u305B\u3093\u3002",
57
+ flags:[ATTACHMENT_REF_FLAG,OUT_FLAG,FORCE_FLAG],download:{outFlag:"--out",forceFlag:"--force"},plan(input){const id=singleRef(input,{flag:"--attachment",label:"\u6DFB\u4ED8ID",usage:"twp task attachment download help"});if(!isSafePathSegment(id))throw new UsageError(`\u6DFB\u4ED8ID \u306E\u5F62\u5F0F\u304C\u9055\u3044\u307E\u3059: ${id}`);return{method:"GET",path:`/api/v2/attachments/${encodeURIComponent(id)}/download`}},summarize:body=>body,raw:body=>body}]};export{classifyTaskRef,wantsPrivateSurface,taskSurface,resolveTaskLocation,rejectRedundantProject,TASK_REF_FLAG,PROJECT_FLAG,TASK_REF_HELP,contentTypeFor,taskAttachmentResource};
@@ -1,6 +1,6 @@
1
1
  import { createRequire as __twpCreateRequire } from 'node:module';
2
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,
3
+ import{ResolveError,UUID_RE,isSafePathSegment,resolveProjectRef,safeProjectIdPolicy}from"./chunk-GMBJTG6A.js";import{ApiError}from"./chunk-FTYJZFEK.js";import{isTaskKey}from"./chunk-II5RVJQN.js";import{loadProjectConfig,loadUserConfig}from"./chunk-NERYSBA4.js";import{twpHomeDir}from"./chunk-RZVI6PMW.js";import{UsageError}from"./chunk-7WSNIXTQ.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
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
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
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");
@@ -15,9 +15,9 @@ env);const fromProfile=usable(user.profiles?.[profileName]?.project);if(fromProf
15
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
16
  const tmp=`${file}.${process.pid}.tmp`;try{fs.mkdirSync(dir,{recursive:true,mode:448});fs.writeFileSync(tmp,`${JSON.stringify(body)}
17
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");
18
+ /list";var DEPARTMENTS_PATH="/api/v2/organization/departments";var POSITIONS_PATH="/api/v2/organization/positions";var JOB_TITLES_PATH="/api/v2/organization/job-titles";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=>{
19
+ try{return{ok:true,status:200,json:await client.request("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"},
20
+ milestone:{path:"task-milestones",envelope:"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
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
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
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.
@@ -29,24 +29,28 @@ flag,label:spec.label})}async taskMasterRefs(kind,projectId){const spec=TASK_MAS
29
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
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
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};
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 primaryAssignment(userId){if(!isSafePathSegment(userId)){throw new ResolveError(`\u30E6\u30FC\u30B6\u30FC ID \u3092\u30D1\u30B9\u306B\u4F7F\u3048\u307E\u305B\u3093: ${userId}\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}
33
+ const res=await this.get(`/api/v2/organization/users/${encodeURIComponent(userId)}/assignments/primary`);if(res.status===404)return null;if(!res.ok){throw new ResolveError(`\u73FE\u5728\u306E\u4E3B\u6240\u5C5E\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}${res.error?`: ${res.error}`:""}\uFF09\u3002`,res.status)}const assignment=isRecord(res.json)?res.json["assignment"]:void 0;if(!isRecord(assignment)||typeof assignment["id"]!=="string"){throw new ResolveError(
34
+ "\u4E3B\u6240\u5C5E\u306E\u5FDC\u7B54\u306B assignment.id \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",res.status)}return assignment}async assignments(userId){if(!isSafePathSegment(userId)){throw new ResolveError(`\u30E6\u30FC\u30B6\u30FC ID \u3092\u30D1\u30B9\u306B\u4F7F\u3048\u307E\u305B\u3093: ${userId}\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)}const res=await this.get(`/ap\
35
+ i/v2/organization/users/${encodeURIComponent(userId)}/assignments`);if(!res.ok){throw new ResolveError(`\u6240\u5C5E\u306E\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF08HTTP ${res.status}${res.error?`: ${res.error}`:""}\uFF09\u3002`,res.status)}const list=isRecord(res.json)?res.json["list"]:void 0;if(!Array.isArray(list)||!list.every(isRecord)){throw new ResolveError("\u6240\u5C5E\u4E00\u89A7\u306E\u5FDC\u7B54\u306B list \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
36
+ res.status)}return list}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,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(
37
+ "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"])].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()===
38
+ 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.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.
39
+ 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.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(
40
+ {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"),"\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(
41
+ `\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`)}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,
42
+ "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",res.status)}cursor=next}return namedFromRows(rows,"\u30E6\u30FC\u30B6\u30FC",userRow)})}async department(input,flag="\
43
+ --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 jobTitle(input,flag="--job-title"){return resolveNamed(input,await this.jobTitles(),{flag,label:"\u8077\u4F4D",scope:TENANT_SCOPE_LABEL})}async departments(){return this.cached("departments",TENANT_CACHE_KEY,async()=>namedFromRows(
44
+ masterList(await this.get(`${DEPARTMENTS_PATH}?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 jobTitles(){return this.cached("job-titles",TENANT_CACHE_KEY,async()=>namedFromRows(masterList(await this.get(`${JOB_TITLES_PATH}?limit=${ORG_MASTER_LIMIT}`),"\u8077\u4F4D"),
45
+ "\u8077\u4F4D",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={...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&&
46
+ 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.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}/\
47
+ 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.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\
48
+ 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.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){
49
+ return this.cached("backlog-projects",spaceId,()=>this.namedList(backlogSpacePath(spaceId,"/projects"),"projects","Backlog \u30D7\u30ED\u30B8\u30A7\u30AF\u30C8",backlogProjectRow))}async backlogStatuses(spaceId,projectId){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",
50
+ backlogStatusRow))}async backlogUsers(spaceId,projectId){return this.cached("backlog-users",`${spaceId}/${projectId}`,()=>this.namedList(backlogSpacePath(spaceId,`/projects/${encodeURIComponent(assertBacklogPathSegment(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.
51
+ 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 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(
52
+ 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`,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){
53
+ 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.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(
54
+ 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)}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`,
55
+ status)}return{id:mapped.id,name:mapped.name,...mapped.code!==void 0?{code:mapped.code}:{},...mapped.aliases!==void 0&&mapped.aliases.length>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.
56
+ label}\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\uFF09`,`\u6307\u5B9A\u3067\u304D\u308B${ctx.label}: ${candidates.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,JOB_TITLES_PATH,ORG_MASTER_LIMIT,TASK_MASTERS,Resolver};
@@ -0,0 +1,13 @@
1
+ import { createRequire as __twpCreateRequire } from 'node:module';
2
+ const require = __twpCreateRequire(import.meta.url);
3
+ import{buildDiffLines,diffStat}from"./chunk-VRBI2NPI.js";import{EXIT_API_CLIENT,EXIT_API_SERVER,EXIT_AUTH}from"./chunk-7WSNIXTQ.js";import*as fs from"fs";function readUtf8Strict(p){return new TextDecoder("utf-8",{fatal:true,ignoreBOM:true}).decode(fs.readFileSync(p))}function apiExit(res){if(res.status===401)return EXIT_AUTH;if(res.status!==null&&res.status>=400&&res.status<500)return EXIT_API_CLIENT;return EXIT_API_SERVER}function pickNumber(b,key){const v=b[key];return typeof v==="number"&&Number.isInteger(v)&&v>=0?v:null}function str(v){return typeof v==="string"?v:""}function currentRevisionOf(res){const json=res.json??{};const data=json["dat\
4
+ a"]&&typeof json["data"]==="object"?json["data"]:{};return pickNumber(json,"current_revision")??pickNumber(data,"current_revision")}function errorDetail(res){if(res.status===null)return`transport_error=${res.transportError??"\u4E0D\u660E"}`;const json=res.json??{};const data=json["data"]&&typeof json["data"]==="object"?json["data"]:{};const errorField=json["error"];const errorObj=errorField&&typeof errorField==="object"?errorField:{};const reason=(typeof errorField==="string"?errorField:"")||str(
5
+ errorObj["code"])||str(json["reason"])||str(data["reason"]);const message=str(json["error_description"])||str(errorObj["message"])||str(json["message"])||str(data["message"]);const parts=[`http=${res.status}`];if(reason)parts.push(`reason=${reason}`);if(message)parts.push(message.slice(0,300));const errors=json["errors"]??data["errors"]??json["error_list"];if(errors&&typeof errors==="object")parts.push(JSON.stringify(errors).slice(0,300));if(!reason&&!message)parts.push(`\u5FDC\u7B54\u306E\u5148\u982D: ${res.
6
+ raw.slice(0,160)}`);return parts.join(" ")}var HIDDEN_CHARS=/[\x00-\x08\x0B-\x1F\x7F-\x9F\u00AD\u061C\u180E\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF\uFFF9-\uFFFB\u{E0000}-\u{E007F}\u{E0100}-\u{E01EF}]/gu;function printDiff(out,fromLabel,toLabel,before,after){const lines=buildDiffLines(before,after);const{added,removed}=diffStat(lines);out(`--- ${fromLabel}
7
+ +++ ${toLabel}
8
+ `);for(const l of lines)out(`${l.sign} ${l.text}
9
+ `);out(`\uFF08+${added} / -${removed} \u884C\uFF09
10
+ `);if(before!==after&&before.replace(/\n$/,"")===after.replace(/\n$/,"")){out(`\uFF08\u9055\u3044\u306F\u672B\u5C3E\u306E\u6539\u884C\u306E\u6709\u7121\u3060\u3051\u3067\u3059: ${after.endsWith("\n")?"\u6539\u884C\u3092\u8DB3\u3059":"\u6539\u884C\u3092\u6D88\u3059"}\uFF09
11
+ `)}warnHiddenChars(out,after)}function warnHiddenChars(out,content,label){const hidden=(content.match(HIDDEN_CHARS)??[]).length;if(hidden>0){out(`\u26A0\uFE0F ${label!==void 0?`${label}: `:""}\u66F8\u304D\u8FBC\u307E\u308C\u308B\u5185\u5BB9\u306B\u3001\u5DEE\u5206\u8868\u793A\u3067\u306F\u898B\u3048\u306A\u3044\u6587\u5B57\uFF08\u5236\u5FA1\u6587\u5B57\u30FBCR\u30FB\u53CC\u65B9\u5411\u5236\u5FA1\u30FB\u30BC\u30ED\u5E45\u30FB\u30BF\u30B0\u6587\u5B57\u7B49\uFF09\u304C ${hidden} \u7B87\u6240\u3042\u308A\u307E\u3059\u3002\u78BA\u5B9A\u3059\u308B\u524D\u306B\u5185\u5BB9\u3092\u78BA\u8A8D\u3057\
12
+ \u3066\u304F\u3060\u3055\u3044
13
+ `)}}function shellQuote(v){return/^[A-Za-z0-9_./:@=-]+$/.test(v)?v:`'${v.replace(/'/g,`'\\''`)}'`}export{readUtf8Strict,apiExit,pickNumber,str,currentRevisionOf,errorDetail,printDiff,warnHiddenChars,shellQuote};
@@ -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-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.
3
+ import{createRuntime}from"./chunk-Z2MNO3FT.js";import{findExecutable}from"./chunk-PMOUHEJQ.js";import{httpFetch}from"./chunk-J7QYPKVK.js";import{describeAutoUpdate}from"./chunk-ILKQDXI5.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(